Reapply r235977 "[DebugInfo] Add debug locations to constant SD nodes"
[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(
1454             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1455             BinNode->hasNoSignedWrap(), BinNode->isExact());
1456       } else {
1457         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1458       }
1459       if (CSENode)
1460         return SDValue(CSENode, 0);
1461     }
1462   }
1463
1464   return RV;
1465 }
1466
1467 /// Given a node, return its input chain if it has one, otherwise return a null
1468 /// sd operand.
1469 static SDValue getInputChainForNode(SDNode *N) {
1470   if (unsigned NumOps = N->getNumOperands()) {
1471     if (N->getOperand(0).getValueType() == MVT::Other)
1472       return N->getOperand(0);
1473     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1474       return N->getOperand(NumOps-1);
1475     for (unsigned i = 1; i < NumOps-1; ++i)
1476       if (N->getOperand(i).getValueType() == MVT::Other)
1477         return N->getOperand(i);
1478   }
1479   return SDValue();
1480 }
1481
1482 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1483   // If N has two operands, where one has an input chain equal to the other,
1484   // the 'other' chain is redundant.
1485   if (N->getNumOperands() == 2) {
1486     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1487       return N->getOperand(0);
1488     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1489       return N->getOperand(1);
1490   }
1491
1492   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1493   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1494   SmallPtrSet<SDNode*, 16> SeenOps;
1495   bool Changed = false;             // If we should replace this token factor.
1496
1497   // Start out with this token factor.
1498   TFs.push_back(N);
1499
1500   // Iterate through token factors.  The TFs grows when new token factors are
1501   // encountered.
1502   for (unsigned i = 0; i < TFs.size(); ++i) {
1503     SDNode *TF = TFs[i];
1504
1505     // Check each of the operands.
1506     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1507       SDValue Op = TF->getOperand(i);
1508
1509       switch (Op.getOpcode()) {
1510       case ISD::EntryToken:
1511         // Entry tokens don't need to be added to the list. They are
1512         // redundant.
1513         Changed = true;
1514         break;
1515
1516       case ISD::TokenFactor:
1517         if (Op.hasOneUse() &&
1518             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1519           // Queue up for processing.
1520           TFs.push_back(Op.getNode());
1521           // Clean up in case the token factor is removed.
1522           AddToWorklist(Op.getNode());
1523           Changed = true;
1524           break;
1525         }
1526         // Fall thru
1527
1528       default:
1529         // Only add if it isn't already in the list.
1530         if (SeenOps.insert(Op.getNode()).second)
1531           Ops.push_back(Op);
1532         else
1533           Changed = true;
1534         break;
1535       }
1536     }
1537   }
1538
1539   SDValue Result;
1540
1541   // If we've changed things around then replace token factor.
1542   if (Changed) {
1543     if (Ops.empty()) {
1544       // The entry token is the only possible outcome.
1545       Result = DAG.getEntryNode();
1546     } else {
1547       // New and improved token factor.
1548       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1549     }
1550
1551     // Add users to worklist if AA is enabled, since it may introduce
1552     // a lot of new chained token factors while removing memory deps.
1553     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1554       : DAG.getSubtarget().useAA();
1555     return CombineTo(N, Result, UseAA /*add to worklist*/);
1556   }
1557
1558   return Result;
1559 }
1560
1561 /// MERGE_VALUES can always be eliminated.
1562 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1563   WorklistRemover DeadNodes(*this);
1564   // Replacing results may cause a different MERGE_VALUES to suddenly
1565   // be CSE'd with N, and carry its uses with it. Iterate until no
1566   // uses remain, to ensure that the node can be safely deleted.
1567   // First add the users of this node to the work list so that they
1568   // can be tried again once they have new operands.
1569   AddUsersToWorklist(N);
1570   do {
1571     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1572       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1573   } while (!N->use_empty());
1574   deleteAndRecombine(N);
1575   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1576 }
1577
1578 SDValue DAGCombiner::visitADD(SDNode *N) {
1579   SDValue N0 = N->getOperand(0);
1580   SDValue N1 = N->getOperand(1);
1581   EVT VT = N0.getValueType();
1582
1583   // fold vector ops
1584   if (VT.isVector()) {
1585     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1586       return FoldedVOp;
1587
1588     // fold (add x, 0) -> x, vector edition
1589     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1590       return N0;
1591     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1592       return N1;
1593   }
1594
1595   // fold (add x, undef) -> undef
1596   if (N0.getOpcode() == ISD::UNDEF)
1597     return N0;
1598   if (N1.getOpcode() == ISD::UNDEF)
1599     return N1;
1600   // fold (add c1, c2) -> c1+c2
1601   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1602   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1603   if (N0C && N1C)
1604     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1605   // canonicalize constant to RHS
1606   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1607      !isConstantIntBuildVectorOrConstantInt(N1))
1608     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1609   // fold (add x, 0) -> x
1610   if (N1C && N1C->isNullValue())
1611     return N0;
1612   // fold (add Sym, c) -> Sym+c
1613   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1614     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1615         GA->getOpcode() == ISD::GlobalAddress)
1616       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1617                                   GA->getOffset() +
1618                                     (uint64_t)N1C->getSExtValue());
1619   // fold ((c1-A)+c2) -> (c1+c2)-A
1620   if (N1C && N0.getOpcode() == ISD::SUB)
1621     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1622       SDLoc DL(N);
1623       return DAG.getNode(ISD::SUB, DL, VT,
1624                          DAG.getConstant(N1C->getAPIntValue()+
1625                                          N0C->getAPIntValue(), DL, VT),
1626                          N0.getOperand(1));
1627     }
1628   // reassociate add
1629   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1630     return RADD;
1631   // fold ((0-A) + B) -> B-A
1632   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1633       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1634     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1635   // fold (A + (0-B)) -> A-B
1636   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1637       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1638     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1639   // fold (A+(B-A)) -> B
1640   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1641     return N1.getOperand(0);
1642   // fold ((B-A)+A) -> B
1643   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1644     return N0.getOperand(0);
1645   // fold (A+(B-(A+C))) to (B-C)
1646   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1647       N0 == N1.getOperand(1).getOperand(0))
1648     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1649                        N1.getOperand(1).getOperand(1));
1650   // fold (A+(B-(C+A))) to (B-C)
1651   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1652       N0 == N1.getOperand(1).getOperand(1))
1653     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1654                        N1.getOperand(1).getOperand(0));
1655   // fold (A+((B-A)+or-C)) to (B+or-C)
1656   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1657       N1.getOperand(0).getOpcode() == ISD::SUB &&
1658       N0 == N1.getOperand(0).getOperand(1))
1659     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1660                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1661
1662   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1663   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1664     SDValue N00 = N0.getOperand(0);
1665     SDValue N01 = N0.getOperand(1);
1666     SDValue N10 = N1.getOperand(0);
1667     SDValue N11 = N1.getOperand(1);
1668
1669     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1670       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1671                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1672                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1673   }
1674
1675   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1676     return SDValue(N, 0);
1677
1678   // fold (a+b) -> (a|b) iff a and b share no bits.
1679   if (VT.isInteger() && !VT.isVector()) {
1680     APInt LHSZero, LHSOne;
1681     APInt RHSZero, RHSOne;
1682     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1683
1684     if (LHSZero.getBoolValue()) {
1685       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1686
1687       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1688       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1689       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1690         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1691           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1692       }
1693     }
1694   }
1695
1696   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1697   if (N1.getOpcode() == ISD::SHL &&
1698       N1.getOperand(0).getOpcode() == ISD::SUB)
1699     if (ConstantSDNode *C =
1700           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1701       if (C->getAPIntValue() == 0)
1702         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1703                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1704                                        N1.getOperand(0).getOperand(1),
1705                                        N1.getOperand(1)));
1706   if (N0.getOpcode() == ISD::SHL &&
1707       N0.getOperand(0).getOpcode() == ISD::SUB)
1708     if (ConstantSDNode *C =
1709           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1710       if (C->getAPIntValue() == 0)
1711         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1712                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1713                                        N0.getOperand(0).getOperand(1),
1714                                        N0.getOperand(1)));
1715
1716   if (N1.getOpcode() == ISD::AND) {
1717     SDValue AndOp0 = N1.getOperand(0);
1718     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1719     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1720     unsigned DestBits = VT.getScalarType().getSizeInBits();
1721
1722     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1723     // and similar xforms where the inner op is either ~0 or 0.
1724     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1725       SDLoc DL(N);
1726       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1727     }
1728   }
1729
1730   // add (sext i1), X -> sub X, (zext i1)
1731   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1732       N0.getOperand(0).getValueType() == MVT::i1 &&
1733       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1734     SDLoc DL(N);
1735     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1736     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1737   }
1738
1739   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1740   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1741     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1742     if (TN->getVT() == MVT::i1) {
1743       SDLoc DL(N);
1744       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1745                                  DAG.getConstant(1, DL, VT));
1746       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1747     }
1748   }
1749
1750   return SDValue();
1751 }
1752
1753 SDValue DAGCombiner::visitADDC(SDNode *N) {
1754   SDValue N0 = N->getOperand(0);
1755   SDValue N1 = N->getOperand(1);
1756   EVT VT = N0.getValueType();
1757
1758   // If the flag result is dead, turn this into an ADD.
1759   if (!N->hasAnyUseOfValue(1))
1760     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1761                      DAG.getNode(ISD::CARRY_FALSE,
1762                                  SDLoc(N), MVT::Glue));
1763
1764   // canonicalize constant to RHS.
1765   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1766   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1767   if (N0C && !N1C)
1768     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1769
1770   // fold (addc x, 0) -> x + no carry out
1771   if (N1C && N1C->isNullValue())
1772     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1773                                         SDLoc(N), MVT::Glue));
1774
1775   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1776   APInt LHSZero, LHSOne;
1777   APInt RHSZero, RHSOne;
1778   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1779
1780   if (LHSZero.getBoolValue()) {
1781     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1782
1783     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1784     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1785     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1786       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1787                        DAG.getNode(ISD::CARRY_FALSE,
1788                                    SDLoc(N), MVT::Glue));
1789   }
1790
1791   return SDValue();
1792 }
1793
1794 SDValue DAGCombiner::visitADDE(SDNode *N) {
1795   SDValue N0 = N->getOperand(0);
1796   SDValue N1 = N->getOperand(1);
1797   SDValue CarryIn = N->getOperand(2);
1798
1799   // canonicalize constant to RHS
1800   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1801   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1802   if (N0C && !N1C)
1803     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1804                        N1, N0, CarryIn);
1805
1806   // fold (adde x, y, false) -> (addc x, y)
1807   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1808     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1809
1810   return SDValue();
1811 }
1812
1813 // Since it may not be valid to emit a fold to zero for vector initializers
1814 // check if we can before folding.
1815 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1816                              SelectionDAG &DAG,
1817                              bool LegalOperations, bool LegalTypes) {
1818   if (!VT.isVector())
1819     return DAG.getConstant(0, DL, VT);
1820   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1821     return DAG.getConstant(0, DL, VT);
1822   return SDValue();
1823 }
1824
1825 SDValue DAGCombiner::visitSUB(SDNode *N) {
1826   SDValue N0 = N->getOperand(0);
1827   SDValue N1 = N->getOperand(1);
1828   EVT VT = N0.getValueType();
1829
1830   // fold vector ops
1831   if (VT.isVector()) {
1832     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1833       return FoldedVOp;
1834
1835     // fold (sub x, 0) -> x, vector edition
1836     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1837       return N0;
1838   }
1839
1840   // fold (sub x, x) -> 0
1841   // FIXME: Refactor this and xor and other similar operations together.
1842   if (N0 == N1)
1843     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1844   // fold (sub c1, c2) -> c1-c2
1845   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1846   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1847   if (N0C && N1C)
1848     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1849   // fold (sub x, c) -> (add x, -c)
1850   if (N1C) {
1851     SDLoc DL(N);
1852     return DAG.getNode(ISD::ADD, DL, VT, N0,
1853                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1854   }
1855   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1856   if (N0C && N0C->isAllOnesValue())
1857     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1858   // fold A-(A-B) -> B
1859   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1860     return N1.getOperand(1);
1861   // fold (A+B)-A -> B
1862   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1863     return N0.getOperand(1);
1864   // fold (A+B)-B -> A
1865   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1866     return N0.getOperand(0);
1867   // fold C2-(A+C1) -> (C2-C1)-A
1868   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1869     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1870   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1871     SDLoc DL(N);
1872     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1873                                    DL, VT);
1874     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1875                        N1.getOperand(0));
1876   }
1877   // fold ((A+(B+or-C))-B) -> A+or-C
1878   if (N0.getOpcode() == ISD::ADD &&
1879       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1880        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1881       N0.getOperand(1).getOperand(0) == N1)
1882     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1883                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1884   // fold ((A+(C+B))-B) -> A+C
1885   if (N0.getOpcode() == ISD::ADD &&
1886       N0.getOperand(1).getOpcode() == ISD::ADD &&
1887       N0.getOperand(1).getOperand(1) == N1)
1888     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1889                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1890   // fold ((A-(B-C))-C) -> A-B
1891   if (N0.getOpcode() == ISD::SUB &&
1892       N0.getOperand(1).getOpcode() == ISD::SUB &&
1893       N0.getOperand(1).getOperand(1) == N1)
1894     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1895                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1896
1897   // If either operand of a sub is undef, the result is undef
1898   if (N0.getOpcode() == ISD::UNDEF)
1899     return N0;
1900   if (N1.getOpcode() == ISD::UNDEF)
1901     return N1;
1902
1903   // If the relocation model supports it, consider symbol offsets.
1904   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1905     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1906       // fold (sub Sym, c) -> Sym-c
1907       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1908         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1909                                     GA->getOffset() -
1910                                       (uint64_t)N1C->getSExtValue());
1911       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1912       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1913         if (GA->getGlobal() == GB->getGlobal())
1914           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1915                                  SDLoc(N), VT);
1916     }
1917
1918   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1919   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1920     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1921     if (TN->getVT() == MVT::i1) {
1922       SDLoc DL(N);
1923       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1924                                  DAG.getConstant(1, DL, VT));
1925       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1926     }
1927   }
1928
1929   return SDValue();
1930 }
1931
1932 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1933   SDValue N0 = N->getOperand(0);
1934   SDValue N1 = N->getOperand(1);
1935   EVT VT = N0.getValueType();
1936
1937   // If the flag result is dead, turn this into an SUB.
1938   if (!N->hasAnyUseOfValue(1))
1939     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1940                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1941                                  MVT::Glue));
1942
1943   // fold (subc x, x) -> 0 + no borrow
1944   if (N0 == N1) {
1945     SDLoc DL(N);
1946     return CombineTo(N, DAG.getConstant(0, DL, VT),
1947                      DAG.getNode(ISD::CARRY_FALSE, DL,
1948                                  MVT::Glue));
1949   }
1950
1951   // fold (subc x, 0) -> x + no borrow
1952   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1953   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1954   if (N1C && N1C->isNullValue())
1955     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1956                                         MVT::Glue));
1957
1958   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1959   if (N0C && N0C->isAllOnesValue())
1960     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1961                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1962                                  MVT::Glue));
1963
1964   return SDValue();
1965 }
1966
1967 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1968   SDValue N0 = N->getOperand(0);
1969   SDValue N1 = N->getOperand(1);
1970   SDValue CarryIn = N->getOperand(2);
1971
1972   // fold (sube x, y, false) -> (subc x, y)
1973   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1974     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1975
1976   return SDValue();
1977 }
1978
1979 SDValue DAGCombiner::visitMUL(SDNode *N) {
1980   SDValue N0 = N->getOperand(0);
1981   SDValue N1 = N->getOperand(1);
1982   EVT VT = N0.getValueType();
1983
1984   // fold (mul x, undef) -> 0
1985   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1986     return DAG.getConstant(0, SDLoc(N), VT);
1987
1988   bool N0IsConst = false;
1989   bool N1IsConst = false;
1990   APInt ConstValue0, ConstValue1;
1991   // fold vector ops
1992   if (VT.isVector()) {
1993     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1994       return FoldedVOp;
1995
1996     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1997     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1998   } else {
1999     N0IsConst = isa<ConstantSDNode>(N0);
2000     if (N0IsConst)
2001       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2002     N1IsConst = isa<ConstantSDNode>(N1);
2003     if (N1IsConst)
2004       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2005   }
2006
2007   // fold (mul c1, c2) -> c1*c2
2008   if (N0IsConst && N1IsConst)
2009     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2010                                       N0.getNode(), N1.getNode());
2011
2012   // canonicalize constant to RHS (vector doesn't have to splat)
2013   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2014      !isConstantIntBuildVectorOrConstantInt(N1))
2015     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2016   // fold (mul x, 0) -> 0
2017   if (N1IsConst && ConstValue1 == 0)
2018     return N1;
2019   // We require a splat of the entire scalar bit width for non-contiguous
2020   // bit patterns.
2021   bool IsFullSplat =
2022     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2023   // fold (mul x, 1) -> x
2024   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2025     return N0;
2026   // fold (mul x, -1) -> 0-x
2027   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2028     SDLoc DL(N);
2029     return DAG.getNode(ISD::SUB, DL, VT,
2030                        DAG.getConstant(0, DL, VT), N0);
2031   }
2032   // fold (mul x, (1 << c)) -> x << c
2033   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2034     SDLoc DL(N);
2035     return DAG.getNode(ISD::SHL, DL, VT, N0,
2036                        DAG.getConstant(ConstValue1.logBase2(), DL,
2037                                        getShiftAmountTy(N0.getValueType())));
2038   }
2039   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2040   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2041     unsigned Log2Val = (-ConstValue1).logBase2();
2042     SDLoc DL(N);
2043     // FIXME: If the input is something that is easily negated (e.g. a
2044     // single-use add), we should put the negate there.
2045     return DAG.getNode(ISD::SUB, DL, VT,
2046                        DAG.getConstant(0, DL, VT),
2047                        DAG.getNode(ISD::SHL, DL, VT, N0,
2048                             DAG.getConstant(Log2Val, DL,
2049                                       getShiftAmountTy(N0.getValueType()))));
2050   }
2051
2052   APInt Val;
2053   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2054   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2055       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2056                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2057     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2058                              N1, N0.getOperand(1));
2059     AddToWorklist(C3.getNode());
2060     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2061                        N0.getOperand(0), C3);
2062   }
2063
2064   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2065   // use.
2066   {
2067     SDValue Sh(nullptr,0), Y(nullptr,0);
2068     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2069     if (N0.getOpcode() == ISD::SHL &&
2070         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2071                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2072         N0.getNode()->hasOneUse()) {
2073       Sh = N0; Y = N1;
2074     } else if (N1.getOpcode() == ISD::SHL &&
2075                isa<ConstantSDNode>(N1.getOperand(1)) &&
2076                N1.getNode()->hasOneUse()) {
2077       Sh = N1; Y = N0;
2078     }
2079
2080     if (Sh.getNode()) {
2081       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2082                                 Sh.getOperand(0), Y);
2083       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2084                          Mul, Sh.getOperand(1));
2085     }
2086   }
2087
2088   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2089   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2090       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2091                      isa<ConstantSDNode>(N0.getOperand(1))))
2092     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2093                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2094                                    N0.getOperand(0), N1),
2095                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2096                                    N0.getOperand(1), N1));
2097
2098   // reassociate mul
2099   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2100     return RMUL;
2101
2102   return SDValue();
2103 }
2104
2105 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2106   SDValue N0 = N->getOperand(0);
2107   SDValue N1 = N->getOperand(1);
2108   EVT VT = N->getValueType(0);
2109
2110   // fold vector ops
2111   if (VT.isVector())
2112     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2113       return FoldedVOp;
2114
2115   // fold (sdiv c1, c2) -> c1/c2
2116   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2117   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2118   if (N0C && N1C && !N1C->isNullValue())
2119     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2120   // fold (sdiv X, 1) -> X
2121   if (N1C && N1C->getAPIntValue() == 1LL)
2122     return N0;
2123   // fold (sdiv X, -1) -> 0-X
2124   if (N1C && N1C->isAllOnesValue()) {
2125     SDLoc DL(N);
2126     return DAG.getNode(ISD::SUB, DL, VT,
2127                        DAG.getConstant(0, DL, VT), N0);
2128   }
2129   // If we know the sign bits of both operands are zero, strength reduce to a
2130   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2131   if (!VT.isVector()) {
2132     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2133       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2134                          N0, N1);
2135   }
2136
2137   // fold (sdiv X, pow2) -> simple ops after legalize
2138   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2139                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2140     // If dividing by powers of two is cheap, then don't perform the following
2141     // fold.
2142     if (TLI.isPow2SDivCheap())
2143       return SDValue();
2144
2145     // Target-specific implementation of sdiv x, pow2.
2146     SDValue Res = BuildSDIVPow2(N);
2147     if (Res.getNode())
2148       return Res;
2149
2150     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2151     SDLoc DL(N);
2152
2153     // Splat the sign bit into the register
2154     SDValue SGN =
2155         DAG.getNode(ISD::SRA, DL, VT, N0,
2156                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2157                                     getShiftAmountTy(N0.getValueType())));
2158     AddToWorklist(SGN.getNode());
2159
2160     // Add (N0 < 0) ? abs2 - 1 : 0;
2161     SDValue SRL =
2162         DAG.getNode(ISD::SRL, DL, VT, SGN,
2163                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2164                                     getShiftAmountTy(SGN.getValueType())));
2165     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2166     AddToWorklist(SRL.getNode());
2167     AddToWorklist(ADD.getNode());    // Divide by pow2
2168     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2169                   DAG.getConstant(lg2, DL,
2170                                   getShiftAmountTy(ADD.getValueType())));
2171
2172     // If we're dividing by a positive value, we're done.  Otherwise, we must
2173     // negate the result.
2174     if (N1C->getAPIntValue().isNonNegative())
2175       return SRA;
2176
2177     AddToWorklist(SRA.getNode());
2178     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2179   }
2180
2181   // If integer divide is expensive and we satisfy the requirements, emit an
2182   // alternate sequence.
2183   if (N1C && !TLI.isIntDivCheap()) {
2184     SDValue Op = BuildSDIV(N);
2185     if (Op.getNode()) return Op;
2186   }
2187
2188   // undef / X -> 0
2189   if (N0.getOpcode() == ISD::UNDEF)
2190     return DAG.getConstant(0, SDLoc(N), VT);
2191   // X / undef -> undef
2192   if (N1.getOpcode() == ISD::UNDEF)
2193     return N1;
2194
2195   return SDValue();
2196 }
2197
2198 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2199   SDValue N0 = N->getOperand(0);
2200   SDValue N1 = N->getOperand(1);
2201   EVT VT = N->getValueType(0);
2202
2203   // fold vector ops
2204   if (VT.isVector())
2205     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2206       return FoldedVOp;
2207
2208   // fold (udiv c1, c2) -> c1/c2
2209   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2210   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2211   if (N0C && N1C && !N1C->isNullValue())
2212     return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2213   // fold (udiv x, (1 << c)) -> x >>u c
2214   if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2215     SDLoc DL(N);
2216     return DAG.getNode(ISD::SRL, DL, VT, N0,
2217                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2218                                        getShiftAmountTy(N0.getValueType())));
2219   }
2220   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2221   if (N1.getOpcode() == ISD::SHL) {
2222     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2223       if (SHC->getAPIntValue().isPowerOf2()) {
2224         EVT ADDVT = N1.getOperand(1).getValueType();
2225         SDLoc DL(N);
2226         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2227                                   N1.getOperand(1),
2228                                   DAG.getConstant(SHC->getAPIntValue()
2229                                                                   .logBase2(),
2230                                                   DL, ADDVT));
2231         AddToWorklist(Add.getNode());
2232         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2233       }
2234     }
2235   }
2236   // fold (udiv x, c) -> alternate
2237   if (N1C && !TLI.isIntDivCheap()) {
2238     SDValue Op = BuildUDIV(N);
2239     if (Op.getNode()) return Op;
2240   }
2241
2242   // undef / X -> 0
2243   if (N0.getOpcode() == ISD::UNDEF)
2244     return DAG.getConstant(0, SDLoc(N), VT);
2245   // X / undef -> undef
2246   if (N1.getOpcode() == ISD::UNDEF)
2247     return N1;
2248
2249   return SDValue();
2250 }
2251
2252 SDValue DAGCombiner::visitSREM(SDNode *N) {
2253   SDValue N0 = N->getOperand(0);
2254   SDValue N1 = N->getOperand(1);
2255   EVT VT = N->getValueType(0);
2256
2257   // fold (srem c1, c2) -> c1%c2
2258   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2259   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2260   if (N0C && N1C && !N1C->isNullValue())
2261     return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2262   // If we know the sign bits of both operands are zero, strength reduce to a
2263   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2264   if (!VT.isVector()) {
2265     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2266       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2267   }
2268
2269   // If X/C can be simplified by the division-by-constant logic, lower
2270   // X%C to the equivalent of X-X/C*C.
2271   if (N1C && !N1C->isNullValue()) {
2272     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2273     AddToWorklist(Div.getNode());
2274     SDValue OptimizedDiv = combine(Div.getNode());
2275     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2276       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2277                                 OptimizedDiv, N1);
2278       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2279       AddToWorklist(Mul.getNode());
2280       return Sub;
2281     }
2282   }
2283
2284   // undef % X -> 0
2285   if (N0.getOpcode() == ISD::UNDEF)
2286     return DAG.getConstant(0, SDLoc(N), VT);
2287   // X % undef -> undef
2288   if (N1.getOpcode() == ISD::UNDEF)
2289     return N1;
2290
2291   return SDValue();
2292 }
2293
2294 SDValue DAGCombiner::visitUREM(SDNode *N) {
2295   SDValue N0 = N->getOperand(0);
2296   SDValue N1 = N->getOperand(1);
2297   EVT VT = N->getValueType(0);
2298
2299   // fold (urem c1, c2) -> c1%c2
2300   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2301   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2302   if (N0C && N1C && !N1C->isNullValue())
2303     return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2304   // fold (urem x, pow2) -> (and x, pow2-1)
2305   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2306     SDLoc DL(N);
2307     return DAG.getNode(ISD::AND, DL, VT, N0,
2308                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2309   }
2310   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2311   if (N1.getOpcode() == ISD::SHL) {
2312     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2313       if (SHC->getAPIntValue().isPowerOf2()) {
2314         SDLoc DL(N);
2315         SDValue Add =
2316           DAG.getNode(ISD::ADD, DL, VT, N1,
2317                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2318                                  VT));
2319         AddToWorklist(Add.getNode());
2320         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2321       }
2322     }
2323   }
2324
2325   // If X/C can be simplified by the division-by-constant logic, lower
2326   // X%C to the equivalent of X-X/C*C.
2327   if (N1C && !N1C->isNullValue()) {
2328     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2329     AddToWorklist(Div.getNode());
2330     SDValue OptimizedDiv = combine(Div.getNode());
2331     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2332       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2333                                 OptimizedDiv, N1);
2334       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2335       AddToWorklist(Mul.getNode());
2336       return Sub;
2337     }
2338   }
2339
2340   // undef % X -> 0
2341   if (N0.getOpcode() == ISD::UNDEF)
2342     return DAG.getConstant(0, SDLoc(N), VT);
2343   // X % undef -> undef
2344   if (N1.getOpcode() == ISD::UNDEF)
2345     return N1;
2346
2347   return SDValue();
2348 }
2349
2350 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2351   SDValue N0 = N->getOperand(0);
2352   SDValue N1 = N->getOperand(1);
2353   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2354   EVT VT = N->getValueType(0);
2355   SDLoc DL(N);
2356
2357   // fold (mulhs x, 0) -> 0
2358   if (N1C && N1C->isNullValue())
2359     return N1;
2360   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2361   if (N1C && N1C->getAPIntValue() == 1) {
2362     SDLoc DL(N);
2363     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2364                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2365                                        DL,
2366                                        getShiftAmountTy(N0.getValueType())));
2367   }
2368   // fold (mulhs x, undef) -> 0
2369   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2370     return DAG.getConstant(0, SDLoc(N), VT);
2371
2372   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2373   // plus a shift.
2374   if (VT.isSimple() && !VT.isVector()) {
2375     MVT Simple = VT.getSimpleVT();
2376     unsigned SimpleSize = Simple.getSizeInBits();
2377     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2378     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2379       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2380       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2381       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2382       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2383             DAG.getConstant(SimpleSize, DL,
2384                             getShiftAmountTy(N1.getValueType())));
2385       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2386     }
2387   }
2388
2389   return SDValue();
2390 }
2391
2392 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2393   SDValue N0 = N->getOperand(0);
2394   SDValue N1 = N->getOperand(1);
2395   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2396   EVT VT = N->getValueType(0);
2397   SDLoc DL(N);
2398
2399   // fold (mulhu x, 0) -> 0
2400   if (N1C && N1C->isNullValue())
2401     return N1;
2402   // fold (mulhu x, 1) -> 0
2403   if (N1C && N1C->getAPIntValue() == 1)
2404     return DAG.getConstant(0, DL, N0.getValueType());
2405   // fold (mulhu x, undef) -> 0
2406   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2407     return DAG.getConstant(0, DL, VT);
2408
2409   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2410   // plus a shift.
2411   if (VT.isSimple() && !VT.isVector()) {
2412     MVT Simple = VT.getSimpleVT();
2413     unsigned SimpleSize = Simple.getSizeInBits();
2414     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2415     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2416       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2417       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2418       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2419       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2420             DAG.getConstant(SimpleSize, DL,
2421                             getShiftAmountTy(N1.getValueType())));
2422       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2423     }
2424   }
2425
2426   return SDValue();
2427 }
2428
2429 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2430 /// give the opcodes for the two computations that are being performed. Return
2431 /// true if a simplification was made.
2432 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2433                                                 unsigned HiOp) {
2434   // If the high half is not needed, just compute the low half.
2435   bool HiExists = N->hasAnyUseOfValue(1);
2436   if (!HiExists &&
2437       (!LegalOperations ||
2438        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2439     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2440     return CombineTo(N, Res, Res);
2441   }
2442
2443   // If the low half is not needed, just compute the high half.
2444   bool LoExists = N->hasAnyUseOfValue(0);
2445   if (!LoExists &&
2446       (!LegalOperations ||
2447        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2448     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2449     return CombineTo(N, Res, Res);
2450   }
2451
2452   // If both halves are used, return as it is.
2453   if (LoExists && HiExists)
2454     return SDValue();
2455
2456   // If the two computed results can be simplified separately, separate them.
2457   if (LoExists) {
2458     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2459     AddToWorklist(Lo.getNode());
2460     SDValue LoOpt = combine(Lo.getNode());
2461     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2462         (!LegalOperations ||
2463          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2464       return CombineTo(N, LoOpt, LoOpt);
2465   }
2466
2467   if (HiExists) {
2468     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2469     AddToWorklist(Hi.getNode());
2470     SDValue HiOpt = combine(Hi.getNode());
2471     if (HiOpt.getNode() && HiOpt != Hi &&
2472         (!LegalOperations ||
2473          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2474       return CombineTo(N, HiOpt, HiOpt);
2475   }
2476
2477   return SDValue();
2478 }
2479
2480 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2481   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2482   if (Res.getNode()) return Res;
2483
2484   EVT VT = N->getValueType(0);
2485   SDLoc DL(N);
2486
2487   // If the type is twice as wide is legal, transform the mulhu to a wider
2488   // multiply plus a shift.
2489   if (VT.isSimple() && !VT.isVector()) {
2490     MVT Simple = VT.getSimpleVT();
2491     unsigned SimpleSize = Simple.getSizeInBits();
2492     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2493     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2494       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2495       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2496       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2497       // Compute the high part as N1.
2498       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2499             DAG.getConstant(SimpleSize, DL,
2500                             getShiftAmountTy(Lo.getValueType())));
2501       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2502       // Compute the low part as N0.
2503       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2504       return CombineTo(N, Lo, Hi);
2505     }
2506   }
2507
2508   return SDValue();
2509 }
2510
2511 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2512   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2513   if (Res.getNode()) return Res;
2514
2515   EVT VT = N->getValueType(0);
2516   SDLoc DL(N);
2517
2518   // If the type is twice as wide is legal, transform the mulhu to a wider
2519   // multiply plus a shift.
2520   if (VT.isSimple() && !VT.isVector()) {
2521     MVT Simple = VT.getSimpleVT();
2522     unsigned SimpleSize = Simple.getSizeInBits();
2523     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2524     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2525       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2526       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2527       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2528       // Compute the high part as N1.
2529       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2530             DAG.getConstant(SimpleSize, DL,
2531                             getShiftAmountTy(Lo.getValueType())));
2532       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2533       // Compute the low part as N0.
2534       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2535       return CombineTo(N, Lo, Hi);
2536     }
2537   }
2538
2539   return SDValue();
2540 }
2541
2542 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2543   // (smulo x, 2) -> (saddo x, x)
2544   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2545     if (C2->getAPIntValue() == 2)
2546       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2547                          N->getOperand(0), N->getOperand(0));
2548
2549   return SDValue();
2550 }
2551
2552 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2553   // (umulo x, 2) -> (uaddo x, x)
2554   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2555     if (C2->getAPIntValue() == 2)
2556       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2557                          N->getOperand(0), N->getOperand(0));
2558
2559   return SDValue();
2560 }
2561
2562 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2563   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2564   if (Res.getNode()) return Res;
2565
2566   return SDValue();
2567 }
2568
2569 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2570   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2571   if (Res.getNode()) return Res;
2572
2573   return SDValue();
2574 }
2575
2576 /// If this is a binary operator with two operands of the same opcode, try to
2577 /// simplify it.
2578 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2579   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2580   EVT VT = N0.getValueType();
2581   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2582
2583   // Bail early if none of these transforms apply.
2584   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2585
2586   // For each of OP in AND/OR/XOR:
2587   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2588   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2589   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2590   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2591   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2592   //
2593   // do not sink logical op inside of a vector extend, since it may combine
2594   // into a vsetcc.
2595   EVT Op0VT = N0.getOperand(0).getValueType();
2596   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2597        N0.getOpcode() == ISD::SIGN_EXTEND ||
2598        N0.getOpcode() == ISD::BSWAP ||
2599        // Avoid infinite looping with PromoteIntBinOp.
2600        (N0.getOpcode() == ISD::ANY_EXTEND &&
2601         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2602        (N0.getOpcode() == ISD::TRUNCATE &&
2603         (!TLI.isZExtFree(VT, Op0VT) ||
2604          !TLI.isTruncateFree(Op0VT, VT)) &&
2605         TLI.isTypeLegal(Op0VT))) &&
2606       !VT.isVector() &&
2607       Op0VT == N1.getOperand(0).getValueType() &&
2608       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2609     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2610                                  N0.getOperand(0).getValueType(),
2611                                  N0.getOperand(0), N1.getOperand(0));
2612     AddToWorklist(ORNode.getNode());
2613     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2614   }
2615
2616   // For each of OP in SHL/SRL/SRA/AND...
2617   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2618   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2619   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2620   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2621        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2622       N0.getOperand(1) == N1.getOperand(1)) {
2623     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2624                                  N0.getOperand(0).getValueType(),
2625                                  N0.getOperand(0), N1.getOperand(0));
2626     AddToWorklist(ORNode.getNode());
2627     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2628                        ORNode, N0.getOperand(1));
2629   }
2630
2631   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2632   // Only perform this optimization after type legalization and before
2633   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2634   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2635   // we don't want to undo this promotion.
2636   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2637   // on scalars.
2638   if ((N0.getOpcode() == ISD::BITCAST ||
2639        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2640       Level == AfterLegalizeTypes) {
2641     SDValue In0 = N0.getOperand(0);
2642     SDValue In1 = N1.getOperand(0);
2643     EVT In0Ty = In0.getValueType();
2644     EVT In1Ty = In1.getValueType();
2645     SDLoc DL(N);
2646     // If both incoming values are integers, and the original types are the
2647     // same.
2648     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2649       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2650       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2651       AddToWorklist(Op.getNode());
2652       return BC;
2653     }
2654   }
2655
2656   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2657   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2658   // If both shuffles use the same mask, and both shuffle within a single
2659   // vector, then it is worthwhile to move the swizzle after the operation.
2660   // The type-legalizer generates this pattern when loading illegal
2661   // vector types from memory. In many cases this allows additional shuffle
2662   // optimizations.
2663   // There are other cases where moving the shuffle after the xor/and/or
2664   // is profitable even if shuffles don't perform a swizzle.
2665   // If both shuffles use the same mask, and both shuffles have the same first
2666   // or second operand, then it might still be profitable to move the shuffle
2667   // after the xor/and/or operation.
2668   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2669     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2670     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2671
2672     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2673            "Inputs to shuffles are not the same type");
2674
2675     // Check that both shuffles use the same mask. The masks are known to be of
2676     // the same length because the result vector type is the same.
2677     // Check also that shuffles have only one use to avoid introducing extra
2678     // instructions.
2679     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2680         SVN0->getMask().equals(SVN1->getMask())) {
2681       SDValue ShOp = N0->getOperand(1);
2682
2683       // Don't try to fold this node if it requires introducing a
2684       // build vector of all zeros that might be illegal at this stage.
2685       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2686         if (!LegalTypes)
2687           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2688         else
2689           ShOp = SDValue();
2690       }
2691
2692       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2693       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2694       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2695       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2696         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2697                                       N0->getOperand(0), N1->getOperand(0));
2698         AddToWorklist(NewNode.getNode());
2699         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2700                                     &SVN0->getMask()[0]);
2701       }
2702
2703       // Don't try to fold this node if it requires introducing a
2704       // build vector of all zeros that might be illegal at this stage.
2705       ShOp = N0->getOperand(0);
2706       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2707         if (!LegalTypes)
2708           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2709         else
2710           ShOp = SDValue();
2711       }
2712
2713       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2714       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2715       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2716       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2717         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2718                                       N0->getOperand(1), N1->getOperand(1));
2719         AddToWorklist(NewNode.getNode());
2720         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2721                                     &SVN0->getMask()[0]);
2722       }
2723     }
2724   }
2725
2726   return SDValue();
2727 }
2728
2729 /// This contains all DAGCombine rules which reduce two values combined by
2730 /// an And operation to a single value. This makes them reusable in the context
2731 /// of visitSELECT(). Rules involving constants are not included as
2732 /// visitSELECT() already handles those cases.
2733 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2734                                   SDNode *LocReference) {
2735   EVT VT = N1.getValueType();
2736
2737   // fold (and x, undef) -> 0
2738   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2739     return DAG.getConstant(0, SDLoc(LocReference), VT);
2740   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2741   SDValue LL, LR, RL, RR, CC0, CC1;
2742   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2743     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2744     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2745
2746     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2747         LL.getValueType().isInteger()) {
2748       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2749       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2750         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2751                                      LR.getValueType(), LL, RL);
2752         AddToWorklist(ORNode.getNode());
2753         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2754       }
2755       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2756       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2757         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2758                                       LR.getValueType(), LL, RL);
2759         AddToWorklist(ANDNode.getNode());
2760         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2761       }
2762       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2763       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2764         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2765                                      LR.getValueType(), LL, RL);
2766         AddToWorklist(ORNode.getNode());
2767         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2768       }
2769     }
2770     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2771     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2772         Op0 == Op1 && LL.getValueType().isInteger() &&
2773       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2774                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2775                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2776                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2777       SDLoc DL(N0);
2778       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2779                                     LL, DAG.getConstant(1, DL,
2780                                                         LL.getValueType()));
2781       AddToWorklist(ADDNode.getNode());
2782       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2783                           DAG.getConstant(2, DL, LL.getValueType()),
2784                           ISD::SETUGE);
2785     }
2786     // canonicalize equivalent to ll == rl
2787     if (LL == RR && LR == RL) {
2788       Op1 = ISD::getSetCCSwappedOperands(Op1);
2789       std::swap(RL, RR);
2790     }
2791     if (LL == RL && LR == RR) {
2792       bool isInteger = LL.getValueType().isInteger();
2793       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2794       if (Result != ISD::SETCC_INVALID &&
2795           (!LegalOperations ||
2796            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2797             TLI.isOperationLegal(ISD::SETCC,
2798                             getSetCCResultType(N0.getSimpleValueType())))))
2799         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2800                             LL, LR, Result);
2801     }
2802   }
2803
2804   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2805       VT.getSizeInBits() <= 64) {
2806     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2807       APInt ADDC = ADDI->getAPIntValue();
2808       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2809         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2810         // immediate for an add, but it is legal if its top c2 bits are set,
2811         // transform the ADD so the immediate doesn't need to be materialized
2812         // in a register.
2813         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2814           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2815                                              SRLI->getZExtValue());
2816           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2817             ADDC |= Mask;
2818             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2819               SDLoc DL(N0);
2820               SDValue NewAdd =
2821                 DAG.getNode(ISD::ADD, DL, VT,
2822                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2823               CombineTo(N0.getNode(), NewAdd);
2824               // Return N so it doesn't get rechecked!
2825               return SDValue(LocReference, 0);
2826             }
2827           }
2828         }
2829       }
2830     }
2831   }
2832
2833   return SDValue();
2834 }
2835
2836 SDValue DAGCombiner::visitAND(SDNode *N) {
2837   SDValue N0 = N->getOperand(0);
2838   SDValue N1 = N->getOperand(1);
2839   EVT VT = N1.getValueType();
2840
2841   // fold vector ops
2842   if (VT.isVector()) {
2843     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2844       return FoldedVOp;
2845
2846     // fold (and x, 0) -> 0, vector edition
2847     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2848       // do not return N0, because undef node may exist in N0
2849       return DAG.getConstant(
2850           APInt::getNullValue(
2851               N0.getValueType().getScalarType().getSizeInBits()),
2852           SDLoc(N), N0.getValueType());
2853     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2854       // do not return N1, because undef node may exist in N1
2855       return DAG.getConstant(
2856           APInt::getNullValue(
2857               N1.getValueType().getScalarType().getSizeInBits()),
2858           SDLoc(N), N1.getValueType());
2859
2860     // fold (and x, -1) -> x, vector edition
2861     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2862       return N1;
2863     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2864       return N0;
2865   }
2866
2867   // fold (and c1, c2) -> c1&c2
2868   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2869   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2870   if (N0C && N1C)
2871     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2872   // canonicalize constant to RHS
2873   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2874      !isConstantIntBuildVectorOrConstantInt(N1))
2875     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2876   // fold (and x, -1) -> x
2877   if (N1C && N1C->isAllOnesValue())
2878     return N0;
2879   // if (and x, c) is known to be zero, return 0
2880   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2881   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2882                                    APInt::getAllOnesValue(BitWidth)))
2883     return DAG.getConstant(0, SDLoc(N), VT);
2884   // reassociate and
2885   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2886     return RAND;
2887   // fold (and (or x, C), D) -> D if (C & D) == D
2888   if (N1C && N0.getOpcode() == ISD::OR)
2889     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2890       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2891         return N1;
2892   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2893   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2894     SDValue N0Op0 = N0.getOperand(0);
2895     APInt Mask = ~N1C->getAPIntValue();
2896     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2897     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2898       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2899                                  N0.getValueType(), N0Op0);
2900
2901       // Replace uses of the AND with uses of the Zero extend node.
2902       CombineTo(N, Zext);
2903
2904       // We actually want to replace all uses of the any_extend with the
2905       // zero_extend, to avoid duplicating things.  This will later cause this
2906       // AND to be folded.
2907       CombineTo(N0.getNode(), Zext);
2908       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2909     }
2910   }
2911   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2912   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2913   // already be zero by virtue of the width of the base type of the load.
2914   //
2915   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2916   // more cases.
2917   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2918        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2919       N0.getOpcode() == ISD::LOAD) {
2920     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2921                                          N0 : N0.getOperand(0) );
2922
2923     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2924     // This can be a pure constant or a vector splat, in which case we treat the
2925     // vector as a scalar and use the splat value.
2926     APInt Constant = APInt::getNullValue(1);
2927     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2928       Constant = C->getAPIntValue();
2929     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2930       APInt SplatValue, SplatUndef;
2931       unsigned SplatBitSize;
2932       bool HasAnyUndefs;
2933       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2934                                              SplatBitSize, HasAnyUndefs);
2935       if (IsSplat) {
2936         // Undef bits can contribute to a possible optimisation if set, so
2937         // set them.
2938         SplatValue |= SplatUndef;
2939
2940         // The splat value may be something like "0x00FFFFFF", which means 0 for
2941         // the first vector value and FF for the rest, repeating. We need a mask
2942         // that will apply equally to all members of the vector, so AND all the
2943         // lanes of the constant together.
2944         EVT VT = Vector->getValueType(0);
2945         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2946
2947         // If the splat value has been compressed to a bitlength lower
2948         // than the size of the vector lane, we need to re-expand it to
2949         // the lane size.
2950         if (BitWidth > SplatBitSize)
2951           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2952                SplatBitSize < BitWidth;
2953                SplatBitSize = SplatBitSize * 2)
2954             SplatValue |= SplatValue.shl(SplatBitSize);
2955
2956         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2957         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2958         if (SplatBitSize % BitWidth == 0) {
2959           Constant = APInt::getAllOnesValue(BitWidth);
2960           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2961             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2962         }
2963       }
2964     }
2965
2966     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2967     // actually legal and isn't going to get expanded, else this is a false
2968     // optimisation.
2969     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2970                                                     Load->getValueType(0),
2971                                                     Load->getMemoryVT());
2972
2973     // Resize the constant to the same size as the original memory access before
2974     // extension. If it is still the AllOnesValue then this AND is completely
2975     // unneeded.
2976     Constant =
2977       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2978
2979     bool B;
2980     switch (Load->getExtensionType()) {
2981     default: B = false; break;
2982     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2983     case ISD::ZEXTLOAD:
2984     case ISD::NON_EXTLOAD: B = true; break;
2985     }
2986
2987     if (B && Constant.isAllOnesValue()) {
2988       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2989       // preserve semantics once we get rid of the AND.
2990       SDValue NewLoad(Load, 0);
2991       if (Load->getExtensionType() == ISD::EXTLOAD) {
2992         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2993                               Load->getValueType(0), SDLoc(Load),
2994                               Load->getChain(), Load->getBasePtr(),
2995                               Load->getOffset(), Load->getMemoryVT(),
2996                               Load->getMemOperand());
2997         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2998         if (Load->getNumValues() == 3) {
2999           // PRE/POST_INC loads have 3 values.
3000           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3001                            NewLoad.getValue(2) };
3002           CombineTo(Load, To, 3, true);
3003         } else {
3004           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3005         }
3006       }
3007
3008       // Fold the AND away, taking care not to fold to the old load node if we
3009       // replaced it.
3010       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3011
3012       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3013     }
3014   }
3015
3016   // fold (and (load x), 255) -> (zextload x, i8)
3017   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3018   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3019   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3020               (N0.getOpcode() == ISD::ANY_EXTEND &&
3021                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3022     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3023     LoadSDNode *LN0 = HasAnyExt
3024       ? cast<LoadSDNode>(N0.getOperand(0))
3025       : cast<LoadSDNode>(N0);
3026     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3027         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3028       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3029       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3030         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3031         EVT LoadedVT = LN0->getMemoryVT();
3032         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3033
3034         if (ExtVT == LoadedVT &&
3035             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3036                                                     ExtVT))) {
3037
3038           SDValue NewLoad =
3039             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3040                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3041                            LN0->getMemOperand());
3042           AddToWorklist(N);
3043           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3044           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3045         }
3046
3047         // Do not change the width of a volatile load.
3048         // Do not generate loads of non-round integer types since these can
3049         // be expensive (and would be wrong if the type is not byte sized).
3050         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3051             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3052                                                     ExtVT))) {
3053           EVT PtrType = LN0->getOperand(1).getValueType();
3054
3055           unsigned Alignment = LN0->getAlignment();
3056           SDValue NewPtr = LN0->getBasePtr();
3057
3058           // For big endian targets, we need to add an offset to the pointer
3059           // to load the correct bytes.  For little endian systems, we merely
3060           // need to read fewer bytes from the same pointer.
3061           if (TLI.isBigEndian()) {
3062             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3063             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3064             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3065             SDLoc DL(LN0);
3066             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3067                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3068             Alignment = MinAlign(Alignment, PtrOff);
3069           }
3070
3071           AddToWorklist(NewPtr.getNode());
3072
3073           SDValue Load =
3074             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3075                            LN0->getChain(), NewPtr,
3076                            LN0->getPointerInfo(),
3077                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3078                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3079           AddToWorklist(N);
3080           CombineTo(LN0, Load, Load.getValue(1));
3081           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3082         }
3083       }
3084     }
3085   }
3086
3087   if (SDValue Combined = visitANDLike(N0, N1, N))
3088     return Combined;
3089
3090   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3091   if (N0.getOpcode() == N1.getOpcode()) {
3092     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3093     if (Tmp.getNode()) return Tmp;
3094   }
3095
3096   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3097   // fold (and (sra)) -> (and (srl)) when possible.
3098   if (!VT.isVector() &&
3099       SimplifyDemandedBits(SDValue(N, 0)))
3100     return SDValue(N, 0);
3101
3102   // fold (zext_inreg (extload x)) -> (zextload x)
3103   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3104     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3105     EVT MemVT = LN0->getMemoryVT();
3106     // If we zero all the possible extended bits, then we can turn this into
3107     // a zextload if we are running before legalize or the operation is legal.
3108     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3109     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3110                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3111         ((!LegalOperations && !LN0->isVolatile()) ||
3112          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3113       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3114                                        LN0->getChain(), LN0->getBasePtr(),
3115                                        MemVT, LN0->getMemOperand());
3116       AddToWorklist(N);
3117       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3118       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3119     }
3120   }
3121   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3122   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3123       N0.hasOneUse()) {
3124     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3125     EVT MemVT = LN0->getMemoryVT();
3126     // If we zero all the possible extended bits, then we can turn this into
3127     // a zextload if we are running before legalize or the operation is legal.
3128     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3129     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3130                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3131         ((!LegalOperations && !LN0->isVolatile()) ||
3132          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3133       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3134                                        LN0->getChain(), LN0->getBasePtr(),
3135                                        MemVT, LN0->getMemOperand());
3136       AddToWorklist(N);
3137       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3138       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3139     }
3140   }
3141   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3142   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3143     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3144                                        N0.getOperand(1), false);
3145     if (BSwap.getNode())
3146       return BSwap;
3147   }
3148
3149   return SDValue();
3150 }
3151
3152 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3153 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3154                                         bool DemandHighBits) {
3155   if (!LegalOperations)
3156     return SDValue();
3157
3158   EVT VT = N->getValueType(0);
3159   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3160     return SDValue();
3161   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3162     return SDValue();
3163
3164   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3165   bool LookPassAnd0 = false;
3166   bool LookPassAnd1 = false;
3167   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3168       std::swap(N0, N1);
3169   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3170       std::swap(N0, N1);
3171   if (N0.getOpcode() == ISD::AND) {
3172     if (!N0.getNode()->hasOneUse())
3173       return SDValue();
3174     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3175     if (!N01C || N01C->getZExtValue() != 0xFF00)
3176       return SDValue();
3177     N0 = N0.getOperand(0);
3178     LookPassAnd0 = true;
3179   }
3180
3181   if (N1.getOpcode() == ISD::AND) {
3182     if (!N1.getNode()->hasOneUse())
3183       return SDValue();
3184     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3185     if (!N11C || N11C->getZExtValue() != 0xFF)
3186       return SDValue();
3187     N1 = N1.getOperand(0);
3188     LookPassAnd1 = true;
3189   }
3190
3191   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3192     std::swap(N0, N1);
3193   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3194     return SDValue();
3195   if (!N0.getNode()->hasOneUse() ||
3196       !N1.getNode()->hasOneUse())
3197     return SDValue();
3198
3199   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3200   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3201   if (!N01C || !N11C)
3202     return SDValue();
3203   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3204     return SDValue();
3205
3206   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3207   SDValue N00 = N0->getOperand(0);
3208   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3209     if (!N00.getNode()->hasOneUse())
3210       return SDValue();
3211     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3212     if (!N001C || N001C->getZExtValue() != 0xFF)
3213       return SDValue();
3214     N00 = N00.getOperand(0);
3215     LookPassAnd0 = true;
3216   }
3217
3218   SDValue N10 = N1->getOperand(0);
3219   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3220     if (!N10.getNode()->hasOneUse())
3221       return SDValue();
3222     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3223     if (!N101C || N101C->getZExtValue() != 0xFF00)
3224       return SDValue();
3225     N10 = N10.getOperand(0);
3226     LookPassAnd1 = true;
3227   }
3228
3229   if (N00 != N10)
3230     return SDValue();
3231
3232   // Make sure everything beyond the low halfword gets set to zero since the SRL
3233   // 16 will clear the top bits.
3234   unsigned OpSizeInBits = VT.getSizeInBits();
3235   if (DemandHighBits && OpSizeInBits > 16) {
3236     // If the left-shift isn't masked out then the only way this is a bswap is
3237     // if all bits beyond the low 8 are 0. In that case the entire pattern
3238     // reduces to a left shift anyway: leave it for other parts of the combiner.
3239     if (!LookPassAnd0)
3240       return SDValue();
3241
3242     // However, if the right shift isn't masked out then it might be because
3243     // it's not needed. See if we can spot that too.
3244     if (!LookPassAnd1 &&
3245         !DAG.MaskedValueIsZero(
3246             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3247       return SDValue();
3248   }
3249
3250   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3251   if (OpSizeInBits > 16) {
3252     SDLoc DL(N);
3253     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3254                       DAG.getConstant(OpSizeInBits - 16, DL,
3255                                       getShiftAmountTy(VT)));
3256   }
3257   return Res;
3258 }
3259
3260 /// Return true if the specified node is an element that makes up a 32-bit
3261 /// packed halfword byteswap.
3262 /// ((x & 0x000000ff) << 8) |
3263 /// ((x & 0x0000ff00) >> 8) |
3264 /// ((x & 0x00ff0000) << 8) |
3265 /// ((x & 0xff000000) >> 8)
3266 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3267   if (!N.getNode()->hasOneUse())
3268     return false;
3269
3270   unsigned Opc = N.getOpcode();
3271   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3272     return false;
3273
3274   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3275   if (!N1C)
3276     return false;
3277
3278   unsigned Num;
3279   switch (N1C->getZExtValue()) {
3280   default:
3281     return false;
3282   case 0xFF:       Num = 0; break;
3283   case 0xFF00:     Num = 1; break;
3284   case 0xFF0000:   Num = 2; break;
3285   case 0xFF000000: Num = 3; break;
3286   }
3287
3288   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3289   SDValue N0 = N.getOperand(0);
3290   if (Opc == ISD::AND) {
3291     if (Num == 0 || Num == 2) {
3292       // (x >> 8) & 0xff
3293       // (x >> 8) & 0xff0000
3294       if (N0.getOpcode() != ISD::SRL)
3295         return false;
3296       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3297       if (!C || C->getZExtValue() != 8)
3298         return false;
3299     } else {
3300       // (x << 8) & 0xff00
3301       // (x << 8) & 0xff000000
3302       if (N0.getOpcode() != ISD::SHL)
3303         return false;
3304       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3305       if (!C || C->getZExtValue() != 8)
3306         return false;
3307     }
3308   } else if (Opc == ISD::SHL) {
3309     // (x & 0xff) << 8
3310     // (x & 0xff0000) << 8
3311     if (Num != 0 && Num != 2)
3312       return false;
3313     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3314     if (!C || C->getZExtValue() != 8)
3315       return false;
3316   } else { // Opc == ISD::SRL
3317     // (x & 0xff00) >> 8
3318     // (x & 0xff000000) >> 8
3319     if (Num != 1 && Num != 3)
3320       return false;
3321     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3322     if (!C || C->getZExtValue() != 8)
3323       return false;
3324   }
3325
3326   if (Parts[Num])
3327     return false;
3328
3329   Parts[Num] = N0.getOperand(0).getNode();
3330   return true;
3331 }
3332
3333 /// Match a 32-bit packed halfword bswap. That is
3334 /// ((x & 0x000000ff) << 8) |
3335 /// ((x & 0x0000ff00) >> 8) |
3336 /// ((x & 0x00ff0000) << 8) |
3337 /// ((x & 0xff000000) >> 8)
3338 /// => (rotl (bswap x), 16)
3339 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3340   if (!LegalOperations)
3341     return SDValue();
3342
3343   EVT VT = N->getValueType(0);
3344   if (VT != MVT::i32)
3345     return SDValue();
3346   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3347     return SDValue();
3348
3349   // Look for either
3350   // (or (or (and), (and)), (or (and), (and)))
3351   // (or (or (or (and), (and)), (and)), (and))
3352   if (N0.getOpcode() != ISD::OR)
3353     return SDValue();
3354   SDValue N00 = N0.getOperand(0);
3355   SDValue N01 = N0.getOperand(1);
3356   SDNode *Parts[4] = {};
3357
3358   if (N1.getOpcode() == ISD::OR &&
3359       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3360     // (or (or (and), (and)), (or (and), (and)))
3361     SDValue N000 = N00.getOperand(0);
3362     if (!isBSwapHWordElement(N000, Parts))
3363       return SDValue();
3364
3365     SDValue N001 = N00.getOperand(1);
3366     if (!isBSwapHWordElement(N001, Parts))
3367       return SDValue();
3368     SDValue N010 = N01.getOperand(0);
3369     if (!isBSwapHWordElement(N010, Parts))
3370       return SDValue();
3371     SDValue N011 = N01.getOperand(1);
3372     if (!isBSwapHWordElement(N011, Parts))
3373       return SDValue();
3374   } else {
3375     // (or (or (or (and), (and)), (and)), (and))
3376     if (!isBSwapHWordElement(N1, Parts))
3377       return SDValue();
3378     if (!isBSwapHWordElement(N01, Parts))
3379       return SDValue();
3380     if (N00.getOpcode() != ISD::OR)
3381       return SDValue();
3382     SDValue N000 = N00.getOperand(0);
3383     if (!isBSwapHWordElement(N000, Parts))
3384       return SDValue();
3385     SDValue N001 = N00.getOperand(1);
3386     if (!isBSwapHWordElement(N001, Parts))
3387       return SDValue();
3388   }
3389
3390   // Make sure the parts are all coming from the same node.
3391   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3392     return SDValue();
3393
3394   SDLoc DL(N);
3395   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3396                               SDValue(Parts[0], 0));
3397
3398   // Result of the bswap should be rotated by 16. If it's not legal, then
3399   // do  (x << 16) | (x >> 16).
3400   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3401   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3402     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3403   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3404     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3405   return DAG.getNode(ISD::OR, DL, VT,
3406                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3407                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3408 }
3409
3410 /// This contains all DAGCombine rules which reduce two values combined by
3411 /// an Or operation to a single value \see visitANDLike().
3412 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3413   EVT VT = N1.getValueType();
3414   // fold (or x, undef) -> -1
3415   if (!LegalOperations &&
3416       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3417     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3418     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3419                            SDLoc(LocReference), VT);
3420   }
3421   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3422   SDValue LL, LR, RL, RR, CC0, CC1;
3423   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3424     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3425     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3426
3427     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3428         LL.getValueType().isInteger()) {
3429       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3430       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3431       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3432           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3433         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3434                                      LR.getValueType(), LL, RL);
3435         AddToWorklist(ORNode.getNode());
3436         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3437       }
3438       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3439       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3440       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3441           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3442         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3443                                       LR.getValueType(), LL, RL);
3444         AddToWorklist(ANDNode.getNode());
3445         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3446       }
3447     }
3448     // canonicalize equivalent to ll == rl
3449     if (LL == RR && LR == RL) {
3450       Op1 = ISD::getSetCCSwappedOperands(Op1);
3451       std::swap(RL, RR);
3452     }
3453     if (LL == RL && LR == RR) {
3454       bool isInteger = LL.getValueType().isInteger();
3455       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3456       if (Result != ISD::SETCC_INVALID &&
3457           (!LegalOperations ||
3458            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3459             TLI.isOperationLegal(ISD::SETCC,
3460               getSetCCResultType(N0.getValueType())))))
3461         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3462                             LL, LR, Result);
3463     }
3464   }
3465
3466   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3467   if (N0.getOpcode() == ISD::AND &&
3468       N1.getOpcode() == ISD::AND &&
3469       N0.getOperand(1).getOpcode() == ISD::Constant &&
3470       N1.getOperand(1).getOpcode() == ISD::Constant &&
3471       // Don't increase # computations.
3472       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3473     // We can only do this xform if we know that bits from X that are set in C2
3474     // but not in C1 are already zero.  Likewise for Y.
3475     const APInt &LHSMask =
3476       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3477     const APInt &RHSMask =
3478       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3479
3480     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3481         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3482       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3483                               N0.getOperand(0), N1.getOperand(0));
3484       SDLoc DL(LocReference);
3485       return DAG.getNode(ISD::AND, DL, VT, X,
3486                          DAG.getConstant(LHSMask | RHSMask, DL, VT));
3487     }
3488   }
3489
3490   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3491   if (N0.getOpcode() == ISD::AND &&
3492       N1.getOpcode() == ISD::AND &&
3493       N0.getOperand(0) == N1.getOperand(0) &&
3494       // Don't increase # computations.
3495       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3496     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3497                             N0.getOperand(1), N1.getOperand(1));
3498     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3499   }
3500
3501   return SDValue();
3502 }
3503
3504 SDValue DAGCombiner::visitOR(SDNode *N) {
3505   SDValue N0 = N->getOperand(0);
3506   SDValue N1 = N->getOperand(1);
3507   EVT VT = N1.getValueType();
3508
3509   // fold vector ops
3510   if (VT.isVector()) {
3511     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3512       return FoldedVOp;
3513
3514     // fold (or x, 0) -> x, vector edition
3515     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3516       return N1;
3517     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3518       return N0;
3519
3520     // fold (or x, -1) -> -1, vector edition
3521     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3522       // do not return N0, because undef node may exist in N0
3523       return DAG.getConstant(
3524           APInt::getAllOnesValue(
3525               N0.getValueType().getScalarType().getSizeInBits()),
3526           SDLoc(N), N0.getValueType());
3527     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3528       // do not return N1, because undef node may exist in N1
3529       return DAG.getConstant(
3530           APInt::getAllOnesValue(
3531               N1.getValueType().getScalarType().getSizeInBits()),
3532           SDLoc(N), N1.getValueType());
3533
3534     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3535     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3536     // Do this only if the resulting shuffle is legal.
3537     if (isa<ShuffleVectorSDNode>(N0) &&
3538         isa<ShuffleVectorSDNode>(N1) &&
3539         // Avoid folding a node with illegal type.
3540         TLI.isTypeLegal(VT) &&
3541         N0->getOperand(1) == N1->getOperand(1) &&
3542         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3543       bool CanFold = true;
3544       unsigned NumElts = VT.getVectorNumElements();
3545       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3546       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3547       // We construct two shuffle masks:
3548       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3549       // and N1 as the second operand.
3550       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3551       // and N0 as the second operand.
3552       // We do this because OR is commutable and therefore there might be
3553       // two ways to fold this node into a shuffle.
3554       SmallVector<int,4> Mask1;
3555       SmallVector<int,4> Mask2;
3556
3557       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3558         int M0 = SV0->getMaskElt(i);
3559         int M1 = SV1->getMaskElt(i);
3560
3561         // Both shuffle indexes are undef. Propagate Undef.
3562         if (M0 < 0 && M1 < 0) {
3563           Mask1.push_back(M0);
3564           Mask2.push_back(M0);
3565           continue;
3566         }
3567
3568         if (M0 < 0 || M1 < 0 ||
3569             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3570             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3571           CanFold = false;
3572           break;
3573         }
3574
3575         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3576         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3577       }
3578
3579       if (CanFold) {
3580         // Fold this sequence only if the resulting shuffle is 'legal'.
3581         if (TLI.isShuffleMaskLegal(Mask1, VT))
3582           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3583                                       N1->getOperand(0), &Mask1[0]);
3584         if (TLI.isShuffleMaskLegal(Mask2, VT))
3585           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3586                                       N0->getOperand(0), &Mask2[0]);
3587       }
3588     }
3589   }
3590
3591   // fold (or c1, c2) -> c1|c2
3592   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3593   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3594   if (N0C && N1C)
3595     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3596   // canonicalize constant to RHS
3597   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3598      !isConstantIntBuildVectorOrConstantInt(N1))
3599     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3600   // fold (or x, 0) -> x
3601   if (N1C && N1C->isNullValue())
3602     return N0;
3603   // fold (or x, -1) -> -1
3604   if (N1C && N1C->isAllOnesValue())
3605     return N1;
3606   // fold (or x, c) -> c iff (x & ~c) == 0
3607   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3608     return N1;
3609
3610   if (SDValue Combined = visitORLike(N0, N1, N))
3611     return Combined;
3612
3613   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3614   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3615   if (BSwap.getNode())
3616     return BSwap;
3617   BSwap = MatchBSwapHWordLow(N, N0, N1);
3618   if (BSwap.getNode())
3619     return BSwap;
3620
3621   // reassociate or
3622   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3623     return ROR;
3624   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3625   // iff (c1 & c2) == 0.
3626   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3627              isa<ConstantSDNode>(N0.getOperand(1))) {
3628     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3629     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3630       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3631                                                    N1C, C1))
3632         return DAG.getNode(
3633             ISD::AND, SDLoc(N), VT,
3634             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3635       return SDValue();
3636     }
3637   }
3638   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3639   if (N0.getOpcode() == N1.getOpcode()) {
3640     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3641     if (Tmp.getNode()) return Tmp;
3642   }
3643
3644   // See if this is some rotate idiom.
3645   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3646     return SDValue(Rot, 0);
3647
3648   // Simplify the operands using demanded-bits information.
3649   if (!VT.isVector() &&
3650       SimplifyDemandedBits(SDValue(N, 0)))
3651     return SDValue(N, 0);
3652
3653   return SDValue();
3654 }
3655
3656 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3657 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3658   if (Op.getOpcode() == ISD::AND) {
3659     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3660       Mask = Op.getOperand(1);
3661       Op = Op.getOperand(0);
3662     } else {
3663       return false;
3664     }
3665   }
3666
3667   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3668     Shift = Op;
3669     return true;
3670   }
3671
3672   return false;
3673 }
3674
3675 // Return true if we can prove that, whenever Neg and Pos are both in the
3676 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3677 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3678 //
3679 //     (or (shift1 X, Neg), (shift2 X, Pos))
3680 //
3681 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3682 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3683 // to consider shift amounts with defined behavior.
3684 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3685   // If OpSize is a power of 2 then:
3686   //
3687   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3688   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3689   //
3690   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3691   // for the stronger condition:
3692   //
3693   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3694   //
3695   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3696   // we can just replace Neg with Neg' for the rest of the function.
3697   //
3698   // In other cases we check for the even stronger condition:
3699   //
3700   //     Neg == OpSize - Pos                                    [B]
3701   //
3702   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3703   // behavior if Pos == 0 (and consequently Neg == OpSize).
3704   //
3705   // We could actually use [A] whenever OpSize is a power of 2, but the
3706   // only extra cases that it would match are those uninteresting ones
3707   // where Neg and Pos are never in range at the same time.  E.g. for
3708   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3709   // as well as (sub 32, Pos), but:
3710   //
3711   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3712   //
3713   // always invokes undefined behavior for 32-bit X.
3714   //
3715   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3716   unsigned MaskLoBits = 0;
3717   if (Neg.getOpcode() == ISD::AND &&
3718       isPowerOf2_64(OpSize) &&
3719       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3720       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3721     Neg = Neg.getOperand(0);
3722     MaskLoBits = Log2_64(OpSize);
3723   }
3724
3725   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3726   if (Neg.getOpcode() != ISD::SUB)
3727     return 0;
3728   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3729   if (!NegC)
3730     return 0;
3731   SDValue NegOp1 = Neg.getOperand(1);
3732
3733   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3734   // Pos'.  The truncation is redundant for the purpose of the equality.
3735   if (MaskLoBits &&
3736       Pos.getOpcode() == ISD::AND &&
3737       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3738       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3739     Pos = Pos.getOperand(0);
3740
3741   // The condition we need is now:
3742   //
3743   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3744   //
3745   // If NegOp1 == Pos then we need:
3746   //
3747   //              OpSize & Mask == NegC & Mask
3748   //
3749   // (because "x & Mask" is a truncation and distributes through subtraction).
3750   APInt Width;
3751   if (Pos == NegOp1)
3752     Width = NegC->getAPIntValue();
3753   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3754   // Then the condition we want to prove becomes:
3755   //
3756   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3757   //
3758   // which, again because "x & Mask" is a truncation, becomes:
3759   //
3760   //                NegC & Mask == (OpSize - PosC) & Mask
3761   //              OpSize & Mask == (NegC + PosC) & Mask
3762   else if (Pos.getOpcode() == ISD::ADD &&
3763            Pos.getOperand(0) == NegOp1 &&
3764            Pos.getOperand(1).getOpcode() == ISD::Constant)
3765     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3766              NegC->getAPIntValue());
3767   else
3768     return false;
3769
3770   // Now we just need to check that OpSize & Mask == Width & Mask.
3771   if (MaskLoBits)
3772     // Opsize & Mask is 0 since Mask is Opsize - 1.
3773     return Width.getLoBits(MaskLoBits) == 0;
3774   return Width == OpSize;
3775 }
3776
3777 // A subroutine of MatchRotate used once we have found an OR of two opposite
3778 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3779 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3780 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3781 // Neg with outer conversions stripped away.
3782 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3783                                        SDValue Neg, SDValue InnerPos,
3784                                        SDValue InnerNeg, unsigned PosOpcode,
3785                                        unsigned NegOpcode, SDLoc DL) {
3786   // fold (or (shl x, (*ext y)),
3787   //          (srl x, (*ext (sub 32, y)))) ->
3788   //   (rotl x, y) or (rotr x, (sub 32, y))
3789   //
3790   // fold (or (shl x, (*ext (sub 32, y))),
3791   //          (srl x, (*ext y))) ->
3792   //   (rotr x, y) or (rotl x, (sub 32, y))
3793   EVT VT = Shifted.getValueType();
3794   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3795     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3796     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3797                        HasPos ? Pos : Neg).getNode();
3798   }
3799
3800   return nullptr;
3801 }
3802
3803 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3804 // idioms for rotate, and if the target supports rotation instructions, generate
3805 // a rot[lr].
3806 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3807   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3808   EVT VT = LHS.getValueType();
3809   if (!TLI.isTypeLegal(VT)) return nullptr;
3810
3811   // The target must have at least one rotate flavor.
3812   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3813   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3814   if (!HasROTL && !HasROTR) return nullptr;
3815
3816   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3817   SDValue LHSShift;   // The shift.
3818   SDValue LHSMask;    // AND value if any.
3819   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3820     return nullptr; // Not part of a rotate.
3821
3822   SDValue RHSShift;   // The shift.
3823   SDValue RHSMask;    // AND value if any.
3824   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3825     return nullptr; // Not part of a rotate.
3826
3827   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3828     return nullptr;   // Not shifting the same value.
3829
3830   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3831     return nullptr;   // Shifts must disagree.
3832
3833   // Canonicalize shl to left side in a shl/srl pair.
3834   if (RHSShift.getOpcode() == ISD::SHL) {
3835     std::swap(LHS, RHS);
3836     std::swap(LHSShift, RHSShift);
3837     std::swap(LHSMask , RHSMask );
3838   }
3839
3840   unsigned OpSizeInBits = VT.getSizeInBits();
3841   SDValue LHSShiftArg = LHSShift.getOperand(0);
3842   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3843   SDValue RHSShiftArg = RHSShift.getOperand(0);
3844   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3845
3846   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3847   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3848   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3849       RHSShiftAmt.getOpcode() == ISD::Constant) {
3850     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3851     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3852     if ((LShVal + RShVal) != OpSizeInBits)
3853       return nullptr;
3854
3855     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3856                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3857
3858     // If there is an AND of either shifted operand, apply it to the result.
3859     if (LHSMask.getNode() || RHSMask.getNode()) {
3860       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3861
3862       if (LHSMask.getNode()) {
3863         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3864         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3865       }
3866       if (RHSMask.getNode()) {
3867         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3868         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3869       }
3870
3871       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3872     }
3873
3874     return Rot.getNode();
3875   }
3876
3877   // If there is a mask here, and we have a variable shift, we can't be sure
3878   // that we're masking out the right stuff.
3879   if (LHSMask.getNode() || RHSMask.getNode())
3880     return nullptr;
3881
3882   // If the shift amount is sign/zext/any-extended just peel it off.
3883   SDValue LExtOp0 = LHSShiftAmt;
3884   SDValue RExtOp0 = RHSShiftAmt;
3885   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3886        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3887        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3888        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3889       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3890        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3891        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3892        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3893     LExtOp0 = LHSShiftAmt.getOperand(0);
3894     RExtOp0 = RHSShiftAmt.getOperand(0);
3895   }
3896
3897   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3898                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3899   if (TryL)
3900     return TryL;
3901
3902   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3903                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3904   if (TryR)
3905     return TryR;
3906
3907   return nullptr;
3908 }
3909
3910 SDValue DAGCombiner::visitXOR(SDNode *N) {
3911   SDValue N0 = N->getOperand(0);
3912   SDValue N1 = N->getOperand(1);
3913   EVT VT = N0.getValueType();
3914
3915   // fold vector ops
3916   if (VT.isVector()) {
3917     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3918       return FoldedVOp;
3919
3920     // fold (xor x, 0) -> x, vector edition
3921     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3922       return N1;
3923     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3924       return N0;
3925   }
3926
3927   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3928   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3929     return DAG.getConstant(0, SDLoc(N), VT);
3930   // fold (xor x, undef) -> undef
3931   if (N0.getOpcode() == ISD::UNDEF)
3932     return N0;
3933   if (N1.getOpcode() == ISD::UNDEF)
3934     return N1;
3935   // fold (xor c1, c2) -> c1^c2
3936   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3937   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3938   if (N0C && N1C)
3939     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3940   // canonicalize constant to RHS
3941   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3942      !isConstantIntBuildVectorOrConstantInt(N1))
3943     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3944   // fold (xor x, 0) -> x
3945   if (N1C && N1C->isNullValue())
3946     return N0;
3947   // reassociate xor
3948   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3949     return RXOR;
3950
3951   // fold !(x cc y) -> (x !cc y)
3952   SDValue LHS, RHS, CC;
3953   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3954     bool isInt = LHS.getValueType().isInteger();
3955     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3956                                                isInt);
3957
3958     if (!LegalOperations ||
3959         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3960       switch (N0.getOpcode()) {
3961       default:
3962         llvm_unreachable("Unhandled SetCC Equivalent!");
3963       case ISD::SETCC:
3964         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3965       case ISD::SELECT_CC:
3966         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3967                                N0.getOperand(3), NotCC);
3968       }
3969     }
3970   }
3971
3972   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3973   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3974       N0.getNode()->hasOneUse() &&
3975       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3976     SDValue V = N0.getOperand(0);
3977     SDLoc DL(N0);
3978     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3979                     DAG.getConstant(1, DL, V.getValueType()));
3980     AddToWorklist(V.getNode());
3981     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3982   }
3983
3984   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3985   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3986       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3987     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3988     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3989       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3990       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3991       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3992       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3993       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3994     }
3995   }
3996   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3997   if (N1C && N1C->isAllOnesValue() &&
3998       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3999     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4000     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4001       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4002       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4003       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4004       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4005       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4006     }
4007   }
4008   // fold (xor (and x, y), y) -> (and (not x), y)
4009   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4010       N0->getOperand(1) == N1) {
4011     SDValue X = N0->getOperand(0);
4012     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4013     AddToWorklist(NotX.getNode());
4014     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4015   }
4016   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4017   if (N1C && N0.getOpcode() == ISD::XOR) {
4018     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4019     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4020     if (N00C) {
4021       SDLoc DL(N);
4022       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4023                          DAG.getConstant(N1C->getAPIntValue() ^
4024                                          N00C->getAPIntValue(), DL, VT));
4025     }
4026     if (N01C) {
4027       SDLoc DL(N);
4028       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4029                          DAG.getConstant(N1C->getAPIntValue() ^
4030                                          N01C->getAPIntValue(), DL, VT));
4031     }
4032   }
4033   // fold (xor x, x) -> 0
4034   if (N0 == N1)
4035     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4036
4037   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4038   // Here is a concrete example of this equivalence:
4039   // i16   x ==  14
4040   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4041   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4042   //
4043   // =>
4044   //
4045   // i16     ~1      == 0b1111111111111110
4046   // i16 rol(~1, 14) == 0b1011111111111111
4047   //
4048   // Some additional tips to help conceptualize this transform:
4049   // - Try to see the operation as placing a single zero in a value of all ones.
4050   // - There exists no value for x which would allow the result to contain zero.
4051   // - Values of x larger than the bitwidth are undefined and do not require a
4052   //   consistent result.
4053   // - Pushing the zero left requires shifting one bits in from the right.
4054   // A rotate left of ~1 is a nice way of achieving the desired result.
4055   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4056     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4057       if (N0.getOpcode() == ISD::SHL)
4058         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4059           if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4060             SDLoc DL(N);
4061             return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4062                                N0.getOperand(1));
4063           }
4064
4065   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4066   if (N0.getOpcode() == N1.getOpcode()) {
4067     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4068     if (Tmp.getNode()) return Tmp;
4069   }
4070
4071   // Simplify the expression using non-local knowledge.
4072   if (!VT.isVector() &&
4073       SimplifyDemandedBits(SDValue(N, 0)))
4074     return SDValue(N, 0);
4075
4076   return SDValue();
4077 }
4078
4079 /// Handle transforms common to the three shifts, when the shift amount is a
4080 /// constant.
4081 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4082   // We can't and shouldn't fold opaque constants.
4083   if (Amt->isOpaque())
4084     return SDValue();
4085
4086   SDNode *LHS = N->getOperand(0).getNode();
4087   if (!LHS->hasOneUse()) return SDValue();
4088
4089   // We want to pull some binops through shifts, so that we have (and (shift))
4090   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4091   // thing happens with address calculations, so it's important to canonicalize
4092   // it.
4093   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4094
4095   switch (LHS->getOpcode()) {
4096   default: return SDValue();
4097   case ISD::OR:
4098   case ISD::XOR:
4099     HighBitSet = false; // We can only transform sra if the high bit is clear.
4100     break;
4101   case ISD::AND:
4102     HighBitSet = true;  // We can only transform sra if the high bit is set.
4103     break;
4104   case ISD::ADD:
4105     if (N->getOpcode() != ISD::SHL)
4106       return SDValue(); // only shl(add) not sr[al](add).
4107     HighBitSet = false; // We can only transform sra if the high bit is clear.
4108     break;
4109   }
4110
4111   // We require the RHS of the binop to be a constant and not opaque as well.
4112   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4113   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4114
4115   // FIXME: disable this unless the input to the binop is a shift by a constant.
4116   // If it is not a shift, it pessimizes some common cases like:
4117   //
4118   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4119   //    int bar(int *X, int i) { return X[i & 255]; }
4120   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4121   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4122        BinOpLHSVal->getOpcode() != ISD::SRA &&
4123        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4124       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4125     return SDValue();
4126
4127   EVT VT = N->getValueType(0);
4128
4129   // If this is a signed shift right, and the high bit is modified by the
4130   // logical operation, do not perform the transformation. The highBitSet
4131   // boolean indicates the value of the high bit of the constant which would
4132   // cause it to be modified for this operation.
4133   if (N->getOpcode() == ISD::SRA) {
4134     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4135     if (BinOpRHSSignSet != HighBitSet)
4136       return SDValue();
4137   }
4138
4139   if (!TLI.isDesirableToCommuteWithShift(LHS))
4140     return SDValue();
4141
4142   // Fold the constants, shifting the binop RHS by the shift amount.
4143   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4144                                N->getValueType(0),
4145                                LHS->getOperand(1), N->getOperand(1));
4146   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4147
4148   // Create the new shift.
4149   SDValue NewShift = DAG.getNode(N->getOpcode(),
4150                                  SDLoc(LHS->getOperand(0)),
4151                                  VT, LHS->getOperand(0), N->getOperand(1));
4152
4153   // Create the new binop.
4154   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4155 }
4156
4157 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4158   assert(N->getOpcode() == ISD::TRUNCATE);
4159   assert(N->getOperand(0).getOpcode() == ISD::AND);
4160
4161   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4162   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4163     SDValue N01 = N->getOperand(0).getOperand(1);
4164
4165     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4166       EVT TruncVT = N->getValueType(0);
4167       SDValue N00 = N->getOperand(0).getOperand(0);
4168       APInt TruncC = N01C->getAPIntValue();
4169       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4170       SDLoc DL(N);
4171
4172       return DAG.getNode(ISD::AND, DL, TruncVT,
4173                          DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4174                          DAG.getConstant(TruncC, DL, TruncVT));
4175     }
4176   }
4177
4178   return SDValue();
4179 }
4180
4181 SDValue DAGCombiner::visitRotate(SDNode *N) {
4182   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4183   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4184       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4185     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4186     if (NewOp1.getNode())
4187       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4188                          N->getOperand(0), NewOp1);
4189   }
4190   return SDValue();
4191 }
4192
4193 SDValue DAGCombiner::visitSHL(SDNode *N) {
4194   SDValue N0 = N->getOperand(0);
4195   SDValue N1 = N->getOperand(1);
4196   EVT VT = N0.getValueType();
4197   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4198
4199   // fold vector ops
4200   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4201   if (VT.isVector()) {
4202     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4203       return FoldedVOp;
4204
4205     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4206     // If setcc produces all-one true value then:
4207     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4208     if (N1CV && N1CV->isConstant()) {
4209       if (N0.getOpcode() == ISD::AND) {
4210         SDValue N00 = N0->getOperand(0);
4211         SDValue N01 = N0->getOperand(1);
4212         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4213
4214         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4215             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4216                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4217           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4218                                                      N01CV, N1CV))
4219             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4220         }
4221       } else {
4222         N1C = isConstOrConstSplat(N1);
4223       }
4224     }
4225   }
4226
4227   // fold (shl c1, c2) -> c1<<c2
4228   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4229   if (N0C && N1C)
4230     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4231   // fold (shl 0, x) -> 0
4232   if (N0C && N0C->isNullValue())
4233     return N0;
4234   // fold (shl x, c >= size(x)) -> undef
4235   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4236     return DAG.getUNDEF(VT);
4237   // fold (shl x, 0) -> x
4238   if (N1C && N1C->isNullValue())
4239     return N0;
4240   // fold (shl undef, x) -> 0
4241   if (N0.getOpcode() == ISD::UNDEF)
4242     return DAG.getConstant(0, SDLoc(N), VT);
4243   // if (shl x, c) is known to be zero, return 0
4244   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4245                             APInt::getAllOnesValue(OpSizeInBits)))
4246     return DAG.getConstant(0, SDLoc(N), VT);
4247   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4248   if (N1.getOpcode() == ISD::TRUNCATE &&
4249       N1.getOperand(0).getOpcode() == ISD::AND) {
4250     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4251     if (NewOp1.getNode())
4252       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4253   }
4254
4255   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4256     return SDValue(N, 0);
4257
4258   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4259   if (N1C && N0.getOpcode() == ISD::SHL) {
4260     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4261       uint64_t c1 = N0C1->getZExtValue();
4262       uint64_t c2 = N1C->getZExtValue();
4263       SDLoc DL(N);
4264       if (c1 + c2 >= OpSizeInBits)
4265         return DAG.getConstant(0, DL, VT);
4266       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4267                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4268     }
4269   }
4270
4271   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4272   // For this to be valid, the second form must not preserve any of the bits
4273   // that are shifted out by the inner shift in the first form.  This means
4274   // the outer shift size must be >= the number of bits added by the ext.
4275   // As a corollary, we don't care what kind of ext it is.
4276   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4277               N0.getOpcode() == ISD::ANY_EXTEND ||
4278               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4279       N0.getOperand(0).getOpcode() == ISD::SHL) {
4280     SDValue N0Op0 = N0.getOperand(0);
4281     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4282       uint64_t c1 = N0Op0C1->getZExtValue();
4283       uint64_t c2 = N1C->getZExtValue();
4284       EVT InnerShiftVT = N0Op0.getValueType();
4285       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4286       if (c2 >= OpSizeInBits - InnerShiftSize) {
4287         SDLoc DL(N0);
4288         if (c1 + c2 >= OpSizeInBits)
4289           return DAG.getConstant(0, DL, VT);
4290         return DAG.getNode(ISD::SHL, DL, VT,
4291                            DAG.getNode(N0.getOpcode(), DL, VT,
4292                                        N0Op0->getOperand(0)),
4293                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4294       }
4295     }
4296   }
4297
4298   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4299   // Only fold this if the inner zext has no other uses to avoid increasing
4300   // the total number of instructions.
4301   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4302       N0.getOperand(0).getOpcode() == ISD::SRL) {
4303     SDValue N0Op0 = N0.getOperand(0);
4304     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4305       uint64_t c1 = N0Op0C1->getZExtValue();
4306       if (c1 < VT.getScalarSizeInBits()) {
4307         uint64_t c2 = N1C->getZExtValue();
4308         if (c1 == c2) {
4309           SDValue NewOp0 = N0.getOperand(0);
4310           EVT CountVT = NewOp0.getOperand(1).getValueType();
4311           SDLoc DL(N);
4312           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4313                                        NewOp0,
4314                                        DAG.getConstant(c2, DL, CountVT));
4315           AddToWorklist(NewSHL.getNode());
4316           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4317         }
4318       }
4319     }
4320   }
4321
4322   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4323   //                               (and (srl x, (sub c1, c2), MASK)
4324   // Only fold this if the inner shift has no other uses -- if it does, folding
4325   // this will increase the total number of instructions.
4326   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4327     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4328       uint64_t c1 = N0C1->getZExtValue();
4329       if (c1 < OpSizeInBits) {
4330         uint64_t c2 = N1C->getZExtValue();
4331         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4332         SDValue Shift;
4333         if (c2 > c1) {
4334           Mask = Mask.shl(c2 - c1);
4335           SDLoc DL(N);
4336           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4337                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4338         } else {
4339           Mask = Mask.lshr(c1 - c2);
4340           SDLoc DL(N);
4341           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4342                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4343         }
4344         SDLoc DL(N0);
4345         return DAG.getNode(ISD::AND, DL, VT, Shift,
4346                            DAG.getConstant(Mask, DL, VT));
4347       }
4348     }
4349   }
4350   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4351   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4352     unsigned BitSize = VT.getScalarSizeInBits();
4353     SDLoc DL(N);
4354     SDValue HiBitsMask =
4355       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4356                                             BitSize - N1C->getZExtValue()),
4357                       DL, VT);
4358     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4359                        HiBitsMask);
4360   }
4361
4362   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4363   // Variant of version done on multiply, except mul by a power of 2 is turned
4364   // into a shift.
4365   APInt Val;
4366   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4367       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4368        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4369     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4370     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4371     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4372   }
4373
4374   if (N1C) {
4375     SDValue NewSHL = visitShiftByConstant(N, N1C);
4376     if (NewSHL.getNode())
4377       return NewSHL;
4378   }
4379
4380   return SDValue();
4381 }
4382
4383 SDValue DAGCombiner::visitSRA(SDNode *N) {
4384   SDValue N0 = N->getOperand(0);
4385   SDValue N1 = N->getOperand(1);
4386   EVT VT = N0.getValueType();
4387   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4388
4389   // fold vector ops
4390   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4391   if (VT.isVector()) {
4392     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4393       return FoldedVOp;
4394
4395     N1C = isConstOrConstSplat(N1);
4396   }
4397
4398   // fold (sra c1, c2) -> (sra c1, c2)
4399   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4400   if (N0C && N1C)
4401     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4402   // fold (sra 0, x) -> 0
4403   if (N0C && N0C->isNullValue())
4404     return N0;
4405   // fold (sra -1, x) -> -1
4406   if (N0C && N0C->isAllOnesValue())
4407     return N0;
4408   // fold (sra x, (setge c, size(x))) -> undef
4409   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4410     return DAG.getUNDEF(VT);
4411   // fold (sra x, 0) -> x
4412   if (N1C && N1C->isNullValue())
4413     return N0;
4414   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4415   // sext_inreg.
4416   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4417     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4418     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4419     if (VT.isVector())
4420       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4421                                ExtVT, VT.getVectorNumElements());
4422     if ((!LegalOperations ||
4423          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4424       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4425                          N0.getOperand(0), DAG.getValueType(ExtVT));
4426   }
4427
4428   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4429   if (N1C && N0.getOpcode() == ISD::SRA) {
4430     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4431       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4432       if (Sum >= OpSizeInBits)
4433         Sum = OpSizeInBits - 1;
4434       SDLoc DL(N);
4435       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4436                          DAG.getConstant(Sum, DL, N1.getValueType()));
4437     }
4438   }
4439
4440   // fold (sra (shl X, m), (sub result_size, n))
4441   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4442   // result_size - n != m.
4443   // If truncate is free for the target sext(shl) is likely to result in better
4444   // code.
4445   if (N0.getOpcode() == ISD::SHL && N1C) {
4446     // Get the two constanst of the shifts, CN0 = m, CN = n.
4447     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4448     if (N01C) {
4449       LLVMContext &Ctx = *DAG.getContext();
4450       // Determine what the truncate's result bitsize and type would be.
4451       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4452
4453       if (VT.isVector())
4454         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4455
4456       // Determine the residual right-shift amount.
4457       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4458
4459       // If the shift is not a no-op (in which case this should be just a sign
4460       // extend already), the truncated to type is legal, sign_extend is legal
4461       // on that type, and the truncate to that type is both legal and free,
4462       // perform the transform.
4463       if ((ShiftAmt > 0) &&
4464           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4465           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4466           TLI.isTruncateFree(VT, TruncVT)) {
4467
4468         SDLoc DL(N);
4469         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4470             getShiftAmountTy(N0.getOperand(0).getValueType()));
4471         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4472                                     N0.getOperand(0), Amt);
4473         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4474                                     Shift);
4475         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4476                            N->getValueType(0), Trunc);
4477       }
4478     }
4479   }
4480
4481   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4482   if (N1.getOpcode() == ISD::TRUNCATE &&
4483       N1.getOperand(0).getOpcode() == ISD::AND) {
4484     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4485     if (NewOp1.getNode())
4486       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4487   }
4488
4489   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4490   //      if c1 is equal to the number of bits the trunc removes
4491   if (N0.getOpcode() == ISD::TRUNCATE &&
4492       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4493        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4494       N0.getOperand(0).hasOneUse() &&
4495       N0.getOperand(0).getOperand(1).hasOneUse() &&
4496       N1C) {
4497     SDValue N0Op0 = N0.getOperand(0);
4498     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4499       unsigned LargeShiftVal = LargeShift->getZExtValue();
4500       EVT LargeVT = N0Op0.getValueType();
4501
4502       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4503         SDLoc DL(N);
4504         SDValue Amt =
4505           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4506                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4507         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4508                                   N0Op0.getOperand(0), Amt);
4509         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4510       }
4511     }
4512   }
4513
4514   // Simplify, based on bits shifted out of the LHS.
4515   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4516     return SDValue(N, 0);
4517
4518
4519   // If the sign bit is known to be zero, switch this to a SRL.
4520   if (DAG.SignBitIsZero(N0))
4521     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4522
4523   if (N1C) {
4524     SDValue NewSRA = visitShiftByConstant(N, N1C);
4525     if (NewSRA.getNode())
4526       return NewSRA;
4527   }
4528
4529   return SDValue();
4530 }
4531
4532 SDValue DAGCombiner::visitSRL(SDNode *N) {
4533   SDValue N0 = N->getOperand(0);
4534   SDValue N1 = N->getOperand(1);
4535   EVT VT = N0.getValueType();
4536   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4537
4538   // fold vector ops
4539   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4540   if (VT.isVector()) {
4541     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4542       return FoldedVOp;
4543
4544     N1C = isConstOrConstSplat(N1);
4545   }
4546
4547   // fold (srl c1, c2) -> c1 >>u c2
4548   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4549   if (N0C && N1C)
4550     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4551   // fold (srl 0, x) -> 0
4552   if (N0C && N0C->isNullValue())
4553     return N0;
4554   // fold (srl x, c >= size(x)) -> undef
4555   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4556     return DAG.getUNDEF(VT);
4557   // fold (srl x, 0) -> x
4558   if (N1C && N1C->isNullValue())
4559     return N0;
4560   // if (srl x, c) is known to be zero, return 0
4561   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4562                                    APInt::getAllOnesValue(OpSizeInBits)))
4563     return DAG.getConstant(0, SDLoc(N), VT);
4564
4565   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4566   if (N1C && N0.getOpcode() == ISD::SRL) {
4567     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4568       uint64_t c1 = N01C->getZExtValue();
4569       uint64_t c2 = N1C->getZExtValue();
4570       SDLoc DL(N);
4571       if (c1 + c2 >= OpSizeInBits)
4572         return DAG.getConstant(0, DL, VT);
4573       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4574                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4575     }
4576   }
4577
4578   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4579   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4580       N0.getOperand(0).getOpcode() == ISD::SRL &&
4581       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4582     uint64_t c1 =
4583       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4584     uint64_t c2 = N1C->getZExtValue();
4585     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4586     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4587     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4588     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4589     if (c1 + OpSizeInBits == InnerShiftSize) {
4590       SDLoc DL(N0);
4591       if (c1 + c2 >= InnerShiftSize)
4592         return DAG.getConstant(0, DL, VT);
4593       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4594                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4595                                      N0.getOperand(0)->getOperand(0),
4596                                      DAG.getConstant(c1 + c2, DL,
4597                                                      ShiftCountVT)));
4598     }
4599   }
4600
4601   // fold (srl (shl x, c), c) -> (and x, cst2)
4602   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4603     unsigned BitSize = N0.getScalarValueSizeInBits();
4604     if (BitSize <= 64) {
4605       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4606       SDLoc DL(N);
4607       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4608                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4609     }
4610   }
4611
4612   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4613   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4614     // Shifting in all undef bits?
4615     EVT SmallVT = N0.getOperand(0).getValueType();
4616     unsigned BitSize = SmallVT.getScalarSizeInBits();
4617     if (N1C->getZExtValue() >= BitSize)
4618       return DAG.getUNDEF(VT);
4619
4620     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4621       uint64_t ShiftAmt = N1C->getZExtValue();
4622       SDLoc DL0(N0);
4623       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4624                                        N0.getOperand(0),
4625                           DAG.getConstant(ShiftAmt, DL0,
4626                                           getShiftAmountTy(SmallVT)));
4627       AddToWorklist(SmallShift.getNode());
4628       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4629       SDLoc DL(N);
4630       return DAG.getNode(ISD::AND, DL, VT,
4631                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4632                          DAG.getConstant(Mask, DL, VT));
4633     }
4634   }
4635
4636   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4637   // bit, which is unmodified by sra.
4638   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4639     if (N0.getOpcode() == ISD::SRA)
4640       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4641   }
4642
4643   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4644   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4645       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4646     APInt KnownZero, KnownOne;
4647     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4648
4649     // If any of the input bits are KnownOne, then the input couldn't be all
4650     // zeros, thus the result of the srl will always be zero.
4651     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4652
4653     // If all of the bits input the to ctlz node are known to be zero, then
4654     // the result of the ctlz is "32" and the result of the shift is one.
4655     APInt UnknownBits = ~KnownZero;
4656     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4657
4658     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4659     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4660       // Okay, we know that only that the single bit specified by UnknownBits
4661       // could be set on input to the CTLZ node. If this bit is set, the SRL
4662       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4663       // to an SRL/XOR pair, which is likely to simplify more.
4664       unsigned ShAmt = UnknownBits.countTrailingZeros();
4665       SDValue Op = N0.getOperand(0);
4666
4667       if (ShAmt) {
4668         SDLoc DL(N0);
4669         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4670                   DAG.getConstant(ShAmt, DL,
4671                                   getShiftAmountTy(Op.getValueType())));
4672         AddToWorklist(Op.getNode());
4673       }
4674
4675       SDLoc DL(N);
4676       return DAG.getNode(ISD::XOR, DL, VT,
4677                          Op, DAG.getConstant(1, DL, VT));
4678     }
4679   }
4680
4681   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4682   if (N1.getOpcode() == ISD::TRUNCATE &&
4683       N1.getOperand(0).getOpcode() == ISD::AND) {
4684     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4685     if (NewOp1.getNode())
4686       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4687   }
4688
4689   // fold operands of srl based on knowledge that the low bits are not
4690   // demanded.
4691   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4692     return SDValue(N, 0);
4693
4694   if (N1C) {
4695     SDValue NewSRL = visitShiftByConstant(N, N1C);
4696     if (NewSRL.getNode())
4697       return NewSRL;
4698   }
4699
4700   // Attempt to convert a srl of a load into a narrower zero-extending load.
4701   SDValue NarrowLoad = ReduceLoadWidth(N);
4702   if (NarrowLoad.getNode())
4703     return NarrowLoad;
4704
4705   // Here is a common situation. We want to optimize:
4706   //
4707   //   %a = ...
4708   //   %b = and i32 %a, 2
4709   //   %c = srl i32 %b, 1
4710   //   brcond i32 %c ...
4711   //
4712   // into
4713   //
4714   //   %a = ...
4715   //   %b = and %a, 2
4716   //   %c = setcc eq %b, 0
4717   //   brcond %c ...
4718   //
4719   // However when after the source operand of SRL is optimized into AND, the SRL
4720   // itself may not be optimized further. Look for it and add the BRCOND into
4721   // the worklist.
4722   if (N->hasOneUse()) {
4723     SDNode *Use = *N->use_begin();
4724     if (Use->getOpcode() == ISD::BRCOND)
4725       AddToWorklist(Use);
4726     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4727       // Also look pass the truncate.
4728       Use = *Use->use_begin();
4729       if (Use->getOpcode() == ISD::BRCOND)
4730         AddToWorklist(Use);
4731     }
4732   }
4733
4734   return SDValue();
4735 }
4736
4737 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4738   SDValue N0 = N->getOperand(0);
4739   EVT VT = N->getValueType(0);
4740
4741   // fold (ctlz c1) -> c2
4742   if (isa<ConstantSDNode>(N0))
4743     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4744   return SDValue();
4745 }
4746
4747 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4748   SDValue N0 = N->getOperand(0);
4749   EVT VT = N->getValueType(0);
4750
4751   // fold (ctlz_zero_undef c1) -> c2
4752   if (isa<ConstantSDNode>(N0))
4753     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4754   return SDValue();
4755 }
4756
4757 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4758   SDValue N0 = N->getOperand(0);
4759   EVT VT = N->getValueType(0);
4760
4761   // fold (cttz c1) -> c2
4762   if (isa<ConstantSDNode>(N0))
4763     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4764   return SDValue();
4765 }
4766
4767 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4768   SDValue N0 = N->getOperand(0);
4769   EVT VT = N->getValueType(0);
4770
4771   // fold (cttz_zero_undef c1) -> c2
4772   if (isa<ConstantSDNode>(N0))
4773     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4774   return SDValue();
4775 }
4776
4777 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4778   SDValue N0 = N->getOperand(0);
4779   EVT VT = N->getValueType(0);
4780
4781   // fold (ctpop c1) -> c2
4782   if (isa<ConstantSDNode>(N0))
4783     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4784   return SDValue();
4785 }
4786
4787
4788 /// \brief Generate Min/Max node
4789 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4790                                    SDValue True, SDValue False,
4791                                    ISD::CondCode CC, const TargetLowering &TLI,
4792                                    SelectionDAG &DAG) {
4793   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4794     return SDValue();
4795
4796   switch (CC) {
4797   case ISD::SETOLT:
4798   case ISD::SETOLE:
4799   case ISD::SETLT:
4800   case ISD::SETLE:
4801   case ISD::SETULT:
4802   case ISD::SETULE: {
4803     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4804     if (TLI.isOperationLegal(Opcode, VT))
4805       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4806     return SDValue();
4807   }
4808   case ISD::SETOGT:
4809   case ISD::SETOGE:
4810   case ISD::SETGT:
4811   case ISD::SETGE:
4812   case ISD::SETUGT:
4813   case ISD::SETUGE: {
4814     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4815     if (TLI.isOperationLegal(Opcode, VT))
4816       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4817     return SDValue();
4818   }
4819   default:
4820     return SDValue();
4821   }
4822 }
4823
4824 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4825   SDValue N0 = N->getOperand(0);
4826   SDValue N1 = N->getOperand(1);
4827   SDValue N2 = N->getOperand(2);
4828   EVT VT = N->getValueType(0);
4829   EVT VT0 = N0.getValueType();
4830
4831   // fold (select C, X, X) -> X
4832   if (N1 == N2)
4833     return N1;
4834   // fold (select true, X, Y) -> X
4835   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4836   if (N0C && !N0C->isNullValue())
4837     return N1;
4838   // fold (select false, X, Y) -> Y
4839   if (N0C && N0C->isNullValue())
4840     return N2;
4841   // fold (select C, 1, X) -> (or C, X)
4842   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4843   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4844     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4845   // fold (select C, 0, 1) -> (xor C, 1)
4846   // We can't do this reliably if integer based booleans have different contents
4847   // to floating point based booleans. This is because we can't tell whether we
4848   // have an integer-based boolean or a floating-point-based boolean unless we
4849   // can find the SETCC that produced it and inspect its operands. This is
4850   // fairly easy if C is the SETCC node, but it can potentially be
4851   // undiscoverable (or not reasonably discoverable). For example, it could be
4852   // in another basic block or it could require searching a complicated
4853   // expression.
4854   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4855   if (VT.isInteger() &&
4856       (VT0 == MVT::i1 || (VT0.isInteger() &&
4857                           TLI.getBooleanContents(false, false) ==
4858                               TLI.getBooleanContents(false, true) &&
4859                           TLI.getBooleanContents(false, false) ==
4860                               TargetLowering::ZeroOrOneBooleanContent)) &&
4861       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4862     SDValue XORNode;
4863     if (VT == VT0) {
4864       SDLoc DL(N);
4865       return DAG.getNode(ISD::XOR, DL, VT0,
4866                          N0, DAG.getConstant(1, DL, VT0));
4867     }
4868     SDLoc DL0(N0);
4869     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4870                           N0, DAG.getConstant(1, DL0, VT0));
4871     AddToWorklist(XORNode.getNode());
4872     if (VT.bitsGT(VT0))
4873       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4874     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4875   }
4876   // fold (select C, 0, X) -> (and (not C), X)
4877   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4878     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4879     AddToWorklist(NOTNode.getNode());
4880     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4881   }
4882   // fold (select C, X, 1) -> (or (not C), X)
4883   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4884     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4885     AddToWorklist(NOTNode.getNode());
4886     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4887   }
4888   // fold (select C, X, 0) -> (and C, X)
4889   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4890     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4891   // fold (select X, X, Y) -> (or X, Y)
4892   // fold (select X, 1, Y) -> (or X, Y)
4893   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4894     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4895   // fold (select X, Y, X) -> (and X, Y)
4896   // fold (select X, Y, 0) -> (and X, Y)
4897   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4898     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4899
4900   // If we can fold this based on the true/false value, do so.
4901   if (SimplifySelectOps(N, N1, N2))
4902     return SDValue(N, 0);  // Don't revisit N.
4903
4904   // fold selects based on a setcc into other things, such as min/max/abs
4905   if (N0.getOpcode() == ISD::SETCC) {
4906     // select x, y (fcmp lt x, y) -> fminnum x, y
4907     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4908     //
4909     // This is OK if we don't care about what happens if either operand is a
4910     // NaN.
4911     //
4912
4913     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4914     // no signed zeros as well as no nans.
4915     const TargetOptions &Options = DAG.getTarget().Options;
4916     if (Options.UnsafeFPMath &&
4917         VT.isFloatingPoint() && N0.hasOneUse() &&
4918         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4919       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4920
4921       SDValue FMinMax =
4922           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4923                               N1, N2, CC, TLI, DAG);
4924       if (FMinMax)
4925         return FMinMax;
4926     }
4927
4928     if ((!LegalOperations &&
4929          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4930         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4931       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4932                          N0.getOperand(0), N0.getOperand(1),
4933                          N1, N2, N0.getOperand(2));
4934     return SimplifySelect(SDLoc(N), N0, N1, N2);
4935   }
4936
4937   if (VT0 == MVT::i1) {
4938     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4939       // select (and Cond0, Cond1), X, Y
4940       //   -> select Cond0, (select Cond1, X, Y), Y
4941       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4942         SDValue Cond0 = N0->getOperand(0);
4943         SDValue Cond1 = N0->getOperand(1);
4944         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4945                                           N1.getValueType(), Cond1, N1, N2);
4946         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4947                            InnerSelect, N2);
4948       }
4949       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4950       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4951         SDValue Cond0 = N0->getOperand(0);
4952         SDValue Cond1 = N0->getOperand(1);
4953         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4954                                           N1.getValueType(), Cond1, N1, N2);
4955         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4956                            InnerSelect);
4957       }
4958     }
4959
4960     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4961     if (N1->getOpcode() == ISD::SELECT) {
4962       SDValue N1_0 = N1->getOperand(0);
4963       SDValue N1_1 = N1->getOperand(1);
4964       SDValue N1_2 = N1->getOperand(2);
4965       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4966         // Create the actual and node if we can generate good code for it.
4967         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4968           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4969                                     N0, N1_0);
4970           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4971                              N1_1, N2);
4972         }
4973         // Otherwise see if we can optimize the "and" to a better pattern.
4974         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4975           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4976                              N1_1, N2);
4977       }
4978     }
4979     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4980     if (N2->getOpcode() == ISD::SELECT) {
4981       SDValue N2_0 = N2->getOperand(0);
4982       SDValue N2_1 = N2->getOperand(1);
4983       SDValue N2_2 = N2->getOperand(2);
4984       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4985         // Create the actual or node if we can generate good code for it.
4986         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4987           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4988                                    N0, N2_0);
4989           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4990                              N1, N2_2);
4991         }
4992         // Otherwise see if we can optimize to a better pattern.
4993         if (SDValue Combined = visitORLike(N0, N2_0, N))
4994           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4995                              N1, N2_2);
4996       }
4997     }
4998   }
4999
5000   return SDValue();
5001 }
5002
5003 static
5004 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5005   SDLoc DL(N);
5006   EVT LoVT, HiVT;
5007   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5008
5009   // Split the inputs.
5010   SDValue Lo, Hi, LL, LH, RL, RH;
5011   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5012   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5013
5014   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5015   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5016
5017   return std::make_pair(Lo, Hi);
5018 }
5019
5020 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5021 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5022 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5023   SDLoc dl(N);
5024   SDValue Cond = N->getOperand(0);
5025   SDValue LHS = N->getOperand(1);
5026   SDValue RHS = N->getOperand(2);
5027   EVT VT = N->getValueType(0);
5028   int NumElems = VT.getVectorNumElements();
5029   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5030          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5031          Cond.getOpcode() == ISD::BUILD_VECTOR);
5032
5033   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5034   // binary ones here.
5035   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5036     return SDValue();
5037
5038   // We're sure we have an even number of elements due to the
5039   // concat_vectors we have as arguments to vselect.
5040   // Skip BV elements until we find one that's not an UNDEF
5041   // After we find an UNDEF element, keep looping until we get to half the
5042   // length of the BV and see if all the non-undef nodes are the same.
5043   ConstantSDNode *BottomHalf = nullptr;
5044   for (int i = 0; i < NumElems / 2; ++i) {
5045     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5046       continue;
5047
5048     if (BottomHalf == nullptr)
5049       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5050     else if (Cond->getOperand(i).getNode() != BottomHalf)
5051       return SDValue();
5052   }
5053
5054   // Do the same for the second half of the BuildVector
5055   ConstantSDNode *TopHalf = nullptr;
5056   for (int i = NumElems / 2; i < NumElems; ++i) {
5057     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5058       continue;
5059
5060     if (TopHalf == nullptr)
5061       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5062     else if (Cond->getOperand(i).getNode() != TopHalf)
5063       return SDValue();
5064   }
5065
5066   assert(TopHalf && BottomHalf &&
5067          "One half of the selector was all UNDEFs and the other was all the "
5068          "same value. This should have been addressed before this function.");
5069   return DAG.getNode(
5070       ISD::CONCAT_VECTORS, dl, VT,
5071       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5072       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5073 }
5074
5075 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5076
5077   if (Level >= AfterLegalizeTypes)
5078     return SDValue();
5079
5080   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5081   SDValue Mask = MST->getMask();
5082   SDValue Data  = MST->getValue();
5083   SDLoc DL(N);
5084
5085   // If the MSTORE data type requires splitting and the mask is provided by a
5086   // SETCC, then split both nodes and its operands before legalization. This
5087   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5088   // and enables future optimizations (e.g. min/max pattern matching on X86).
5089   if (Mask.getOpcode() == ISD::SETCC) {
5090
5091     // Check if any splitting is required.
5092     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5093         TargetLowering::TypeSplitVector)
5094       return SDValue();
5095
5096     SDValue MaskLo, MaskHi, Lo, Hi;
5097     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5098
5099     EVT LoVT, HiVT;
5100     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5101
5102     SDValue Chain = MST->getChain();
5103     SDValue Ptr   = MST->getBasePtr();
5104
5105     EVT MemoryVT = MST->getMemoryVT();
5106     unsigned Alignment = MST->getOriginalAlignment();
5107
5108     // if Alignment is equal to the vector size,
5109     // take the half of it for the second part
5110     unsigned SecondHalfAlignment =
5111       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5112          Alignment/2 : Alignment;
5113
5114     EVT LoMemVT, HiMemVT;
5115     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5116
5117     SDValue DataLo, DataHi;
5118     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5119
5120     MachineMemOperand *MMO = DAG.getMachineFunction().
5121       getMachineMemOperand(MST->getPointerInfo(),
5122                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5123                            Alignment, MST->getAAInfo(), MST->getRanges());
5124
5125     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5126                             MST->isTruncatingStore());
5127
5128     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5129     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5130                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5131
5132     MMO = DAG.getMachineFunction().
5133       getMachineMemOperand(MST->getPointerInfo(),
5134                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5135                            SecondHalfAlignment, MST->getAAInfo(),
5136                            MST->getRanges());
5137
5138     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5139                             MST->isTruncatingStore());
5140
5141     AddToWorklist(Lo.getNode());
5142     AddToWorklist(Hi.getNode());
5143
5144     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5145   }
5146   return SDValue();
5147 }
5148
5149 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5150
5151   if (Level >= AfterLegalizeTypes)
5152     return SDValue();
5153
5154   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5155   SDValue Mask = MLD->getMask();
5156   SDLoc DL(N);
5157
5158   // If the MLOAD result requires splitting and the mask is provided by a
5159   // SETCC, then split both nodes and its operands before legalization. This
5160   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5161   // and enables future optimizations (e.g. min/max pattern matching on X86).
5162
5163   if (Mask.getOpcode() == ISD::SETCC) {
5164     EVT VT = N->getValueType(0);
5165
5166     // Check if any splitting is required.
5167     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5168         TargetLowering::TypeSplitVector)
5169       return SDValue();
5170
5171     SDValue MaskLo, MaskHi, Lo, Hi;
5172     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5173
5174     SDValue Src0 = MLD->getSrc0();
5175     SDValue Src0Lo, Src0Hi;
5176     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5177
5178     EVT LoVT, HiVT;
5179     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5180
5181     SDValue Chain = MLD->getChain();
5182     SDValue Ptr   = MLD->getBasePtr();
5183     EVT MemoryVT = MLD->getMemoryVT();
5184     unsigned Alignment = MLD->getOriginalAlignment();
5185
5186     // if Alignment is equal to the vector size,
5187     // take the half of it for the second part
5188     unsigned SecondHalfAlignment =
5189       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5190          Alignment/2 : Alignment;
5191
5192     EVT LoMemVT, HiMemVT;
5193     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5194
5195     MachineMemOperand *MMO = DAG.getMachineFunction().
5196     getMachineMemOperand(MLD->getPointerInfo(),
5197                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5198                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5199
5200     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5201                            ISD::NON_EXTLOAD);
5202
5203     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5204     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5205                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5206
5207     MMO = DAG.getMachineFunction().
5208     getMachineMemOperand(MLD->getPointerInfo(),
5209                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5210                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5211
5212     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5213                            ISD::NON_EXTLOAD);
5214
5215     AddToWorklist(Lo.getNode());
5216     AddToWorklist(Hi.getNode());
5217
5218     // Build a factor node to remember that this load is independent of the
5219     // other one.
5220     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5221                         Hi.getValue(1));
5222
5223     // Legalized the chain result - switch anything that used the old chain to
5224     // use the new one.
5225     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5226
5227     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5228
5229     SDValue RetOps[] = { LoadRes, Chain };
5230     return DAG.getMergeValues(RetOps, DL);
5231   }
5232   return SDValue();
5233 }
5234
5235 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5236   SDValue N0 = N->getOperand(0);
5237   SDValue N1 = N->getOperand(1);
5238   SDValue N2 = N->getOperand(2);
5239   SDLoc DL(N);
5240
5241   // Canonicalize integer abs.
5242   // vselect (setg[te] X,  0),  X, -X ->
5243   // vselect (setgt    X, -1),  X, -X ->
5244   // vselect (setl[te] X,  0), -X,  X ->
5245   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5246   if (N0.getOpcode() == ISD::SETCC) {
5247     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5248     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5249     bool isAbs = false;
5250     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5251
5252     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5253          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5254         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5255       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5256     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5257              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5258       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5259
5260     if (isAbs) {
5261       EVT VT = LHS.getValueType();
5262       SDValue Shift = DAG.getNode(
5263           ISD::SRA, DL, VT, LHS,
5264           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5265       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5266       AddToWorklist(Shift.getNode());
5267       AddToWorklist(Add.getNode());
5268       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5269     }
5270   }
5271
5272   if (SimplifySelectOps(N, N1, N2))
5273     return SDValue(N, 0);  // Don't revisit N.
5274
5275   // If the VSELECT result requires splitting and the mask is provided by a
5276   // SETCC, then split both nodes and its operands before legalization. This
5277   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5278   // and enables future optimizations (e.g. min/max pattern matching on X86).
5279   if (N0.getOpcode() == ISD::SETCC) {
5280     EVT VT = N->getValueType(0);
5281
5282     // Check if any splitting is required.
5283     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5284         TargetLowering::TypeSplitVector)
5285       return SDValue();
5286
5287     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5288     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5289     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5290     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5291
5292     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5293     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5294
5295     // Add the new VSELECT nodes to the work list in case they need to be split
5296     // again.
5297     AddToWorklist(Lo.getNode());
5298     AddToWorklist(Hi.getNode());
5299
5300     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5301   }
5302
5303   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5304   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5305     return N1;
5306   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5307   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5308     return N2;
5309
5310   // The ConvertSelectToConcatVector function is assuming both the above
5311   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5312   // and addressed.
5313   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5314       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5315       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5316     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5317     if (CV.getNode())
5318       return CV;
5319   }
5320
5321   return SDValue();
5322 }
5323
5324 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5325   SDValue N0 = N->getOperand(0);
5326   SDValue N1 = N->getOperand(1);
5327   SDValue N2 = N->getOperand(2);
5328   SDValue N3 = N->getOperand(3);
5329   SDValue N4 = N->getOperand(4);
5330   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5331
5332   // fold select_cc lhs, rhs, x, x, cc -> x
5333   if (N2 == N3)
5334     return N2;
5335
5336   // Determine if the condition we're dealing with is constant
5337   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5338                               N0, N1, CC, SDLoc(N), false);
5339   if (SCC.getNode()) {
5340     AddToWorklist(SCC.getNode());
5341
5342     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5343       if (!SCCC->isNullValue())
5344         return N2;    // cond always true -> true val
5345       else
5346         return N3;    // cond always false -> false val
5347     } else if (SCC->getOpcode() == ISD::UNDEF) {
5348       // When the condition is UNDEF, just return the first operand. This is
5349       // coherent the DAG creation, no setcc node is created in this case
5350       return N2;
5351     } else if (SCC.getOpcode() == ISD::SETCC) {
5352       // Fold to a simpler select_cc
5353       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5354                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5355                          SCC.getOperand(2));
5356     }
5357   }
5358
5359   // If we can fold this based on the true/false value, do so.
5360   if (SimplifySelectOps(N, N2, N3))
5361     return SDValue(N, 0);  // Don't revisit N.
5362
5363   // fold select_cc into other things, such as min/max/abs
5364   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5365 }
5366
5367 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5368   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5369                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5370                        SDLoc(N));
5371 }
5372
5373 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5374 // dag node into a ConstantSDNode or a build_vector of constants.
5375 // This function is called by the DAGCombiner when visiting sext/zext/aext
5376 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5377 // Vector extends are not folded if operations are legal; this is to
5378 // avoid introducing illegal build_vector dag nodes.
5379 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5380                                          SelectionDAG &DAG, bool LegalTypes,
5381                                          bool LegalOperations) {
5382   unsigned Opcode = N->getOpcode();
5383   SDValue N0 = N->getOperand(0);
5384   EVT VT = N->getValueType(0);
5385
5386   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5387          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5388
5389   // fold (sext c1) -> c1
5390   // fold (zext c1) -> c1
5391   // fold (aext c1) -> c1
5392   if (isa<ConstantSDNode>(N0))
5393     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5394
5395   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5396   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5397   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5398   EVT SVT = VT.getScalarType();
5399   if (!(VT.isVector() &&
5400       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5401       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5402     return nullptr;
5403
5404   // We can fold this node into a build_vector.
5405   unsigned VTBits = SVT.getSizeInBits();
5406   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5407   unsigned ShAmt = VTBits - EVTBits;
5408   SmallVector<SDValue, 8> Elts;
5409   unsigned NumElts = N0->getNumOperands();
5410   SDLoc DL(N);
5411
5412   for (unsigned i=0; i != NumElts; ++i) {
5413     SDValue Op = N0->getOperand(i);
5414     if (Op->getOpcode() == ISD::UNDEF) {
5415       Elts.push_back(DAG.getUNDEF(SVT));
5416       continue;
5417     }
5418
5419     SDLoc DL(Op);
5420     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5421     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5422     if (Opcode == ISD::SIGN_EXTEND)
5423       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5424                                      DL, SVT));
5425     else
5426       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5427                                      DL, SVT));
5428   }
5429
5430   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5431 }
5432
5433 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5434 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5435 // transformation. Returns true if extension are possible and the above
5436 // mentioned transformation is profitable.
5437 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5438                                     unsigned ExtOpc,
5439                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5440                                     const TargetLowering &TLI) {
5441   bool HasCopyToRegUses = false;
5442   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5443   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5444                             UE = N0.getNode()->use_end();
5445        UI != UE; ++UI) {
5446     SDNode *User = *UI;
5447     if (User == N)
5448       continue;
5449     if (UI.getUse().getResNo() != N0.getResNo())
5450       continue;
5451     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5452     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5453       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5454       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5455         // Sign bits will be lost after a zext.
5456         return false;
5457       bool Add = false;
5458       for (unsigned i = 0; i != 2; ++i) {
5459         SDValue UseOp = User->getOperand(i);
5460         if (UseOp == N0)
5461           continue;
5462         if (!isa<ConstantSDNode>(UseOp))
5463           return false;
5464         Add = true;
5465       }
5466       if (Add)
5467         ExtendNodes.push_back(User);
5468       continue;
5469     }
5470     // If truncates aren't free and there are users we can't
5471     // extend, it isn't worthwhile.
5472     if (!isTruncFree)
5473       return false;
5474     // Remember if this value is live-out.
5475     if (User->getOpcode() == ISD::CopyToReg)
5476       HasCopyToRegUses = true;
5477   }
5478
5479   if (HasCopyToRegUses) {
5480     bool BothLiveOut = false;
5481     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5482          UI != UE; ++UI) {
5483       SDUse &Use = UI.getUse();
5484       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5485         BothLiveOut = true;
5486         break;
5487       }
5488     }
5489     if (BothLiveOut)
5490       // Both unextended and extended values are live out. There had better be
5491       // a good reason for the transformation.
5492       return ExtendNodes.size();
5493   }
5494   return true;
5495 }
5496
5497 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5498                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5499                                   ISD::NodeType ExtType) {
5500   // Extend SetCC uses if necessary.
5501   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5502     SDNode *SetCC = SetCCs[i];
5503     SmallVector<SDValue, 4> Ops;
5504
5505     for (unsigned j = 0; j != 2; ++j) {
5506       SDValue SOp = SetCC->getOperand(j);
5507       if (SOp == Trunc)
5508         Ops.push_back(ExtLoad);
5509       else
5510         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5511     }
5512
5513     Ops.push_back(SetCC->getOperand(2));
5514     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5515   }
5516 }
5517
5518 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5519 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5520   SDValue N0 = N->getOperand(0);
5521   EVT DstVT = N->getValueType(0);
5522   EVT SrcVT = N0.getValueType();
5523
5524   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5525           N->getOpcode() == ISD::ZERO_EXTEND) &&
5526          "Unexpected node type (not an extend)!");
5527
5528   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5529   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5530   //   (v8i32 (sext (v8i16 (load x))))
5531   // into:
5532   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5533   //                          (v4i32 (sextload (x + 16)))))
5534   // Where uses of the original load, i.e.:
5535   //   (v8i16 (load x))
5536   // are replaced with:
5537   //   (v8i16 (truncate
5538   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5539   //                            (v4i32 (sextload (x + 16)))))))
5540   //
5541   // This combine is only applicable to illegal, but splittable, vectors.
5542   // All legal types, and illegal non-vector types, are handled elsewhere.
5543   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5544   //
5545   if (N0->getOpcode() != ISD::LOAD)
5546     return SDValue();
5547
5548   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5549
5550   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5551       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5552       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5553     return SDValue();
5554
5555   SmallVector<SDNode *, 4> SetCCs;
5556   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5557     return SDValue();
5558
5559   ISD::LoadExtType ExtType =
5560       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5561
5562   // Try to split the vector types to get down to legal types.
5563   EVT SplitSrcVT = SrcVT;
5564   EVT SplitDstVT = DstVT;
5565   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5566          SplitSrcVT.getVectorNumElements() > 1) {
5567     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5568     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5569   }
5570
5571   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5572     return SDValue();
5573
5574   SDLoc DL(N);
5575   const unsigned NumSplits =
5576       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5577   const unsigned Stride = SplitSrcVT.getStoreSize();
5578   SmallVector<SDValue, 4> Loads;
5579   SmallVector<SDValue, 4> Chains;
5580
5581   SDValue BasePtr = LN0->getBasePtr();
5582   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5583     const unsigned Offset = Idx * Stride;
5584     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5585
5586     SDValue SplitLoad = DAG.getExtLoad(
5587         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5588         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5589         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5590         Align, LN0->getAAInfo());
5591
5592     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5593                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5594
5595     Loads.push_back(SplitLoad.getValue(0));
5596     Chains.push_back(SplitLoad.getValue(1));
5597   }
5598
5599   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5600   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5601
5602   CombineTo(N, NewValue);
5603
5604   // Replace uses of the original load (before extension)
5605   // with a truncate of the concatenated sextloaded vectors.
5606   SDValue Trunc =
5607       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5608   CombineTo(N0.getNode(), Trunc, NewChain);
5609   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5610                   (ISD::NodeType)N->getOpcode());
5611   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5612 }
5613
5614 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5615   SDValue N0 = N->getOperand(0);
5616   EVT VT = N->getValueType(0);
5617
5618   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5619                                               LegalOperations))
5620     return SDValue(Res, 0);
5621
5622   // fold (sext (sext x)) -> (sext x)
5623   // fold (sext (aext x)) -> (sext x)
5624   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5625     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5626                        N0.getOperand(0));
5627
5628   if (N0.getOpcode() == ISD::TRUNCATE) {
5629     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5630     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5631     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5632     if (NarrowLoad.getNode()) {
5633       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5634       if (NarrowLoad.getNode() != N0.getNode()) {
5635         CombineTo(N0.getNode(), NarrowLoad);
5636         // CombineTo deleted the truncate, if needed, but not what's under it.
5637         AddToWorklist(oye);
5638       }
5639       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5640     }
5641
5642     // See if the value being truncated is already sign extended.  If so, just
5643     // eliminate the trunc/sext pair.
5644     SDValue Op = N0.getOperand(0);
5645     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5646     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5647     unsigned DestBits = VT.getScalarType().getSizeInBits();
5648     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5649
5650     if (OpBits == DestBits) {
5651       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5652       // bits, it is already ready.
5653       if (NumSignBits > DestBits-MidBits)
5654         return Op;
5655     } else if (OpBits < DestBits) {
5656       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5657       // bits, just sext from i32.
5658       if (NumSignBits > OpBits-MidBits)
5659         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5660     } else {
5661       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5662       // bits, just truncate to i32.
5663       if (NumSignBits > OpBits-MidBits)
5664         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5665     }
5666
5667     // fold (sext (truncate x)) -> (sextinreg x).
5668     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5669                                                  N0.getValueType())) {
5670       if (OpBits < DestBits)
5671         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5672       else if (OpBits > DestBits)
5673         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5674       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5675                          DAG.getValueType(N0.getValueType()));
5676     }
5677   }
5678
5679   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5680   // Only generate vector extloads when 1) they're legal, and 2) they are
5681   // deemed desirable by the target.
5682   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5683       ((!LegalOperations && !VT.isVector() &&
5684         !cast<LoadSDNode>(N0)->isVolatile()) ||
5685        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5686     bool DoXform = true;
5687     SmallVector<SDNode*, 4> SetCCs;
5688     if (!N0.hasOneUse())
5689       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5690     if (VT.isVector())
5691       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5692     if (DoXform) {
5693       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5694       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5695                                        LN0->getChain(),
5696                                        LN0->getBasePtr(), N0.getValueType(),
5697                                        LN0->getMemOperand());
5698       CombineTo(N, ExtLoad);
5699       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5700                                   N0.getValueType(), ExtLoad);
5701       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5702       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5703                       ISD::SIGN_EXTEND);
5704       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5705     }
5706   }
5707
5708   // fold (sext (load x)) to multiple smaller sextloads.
5709   // Only on illegal but splittable vectors.
5710   if (SDValue ExtLoad = CombineExtLoad(N))
5711     return ExtLoad;
5712
5713   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5714   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5715   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5716       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5717     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5718     EVT MemVT = LN0->getMemoryVT();
5719     if ((!LegalOperations && !LN0->isVolatile()) ||
5720         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5721       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5722                                        LN0->getChain(),
5723                                        LN0->getBasePtr(), MemVT,
5724                                        LN0->getMemOperand());
5725       CombineTo(N, ExtLoad);
5726       CombineTo(N0.getNode(),
5727                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5728                             N0.getValueType(), ExtLoad),
5729                 ExtLoad.getValue(1));
5730       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5731     }
5732   }
5733
5734   // fold (sext (and/or/xor (load x), cst)) ->
5735   //      (and/or/xor (sextload x), (sext cst))
5736   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5737        N0.getOpcode() == ISD::XOR) &&
5738       isa<LoadSDNode>(N0.getOperand(0)) &&
5739       N0.getOperand(1).getOpcode() == ISD::Constant &&
5740       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5741       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5742     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5743     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5744       bool DoXform = true;
5745       SmallVector<SDNode*, 4> SetCCs;
5746       if (!N0.hasOneUse())
5747         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5748                                           SetCCs, TLI);
5749       if (DoXform) {
5750         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5751                                          LN0->getChain(), LN0->getBasePtr(),
5752                                          LN0->getMemoryVT(),
5753                                          LN0->getMemOperand());
5754         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5755         Mask = Mask.sext(VT.getSizeInBits());
5756         SDLoc DL(N);
5757         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5758                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5759         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5760                                     SDLoc(N0.getOperand(0)),
5761                                     N0.getOperand(0).getValueType(), ExtLoad);
5762         CombineTo(N, And);
5763         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5764         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5765                         ISD::SIGN_EXTEND);
5766         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5767       }
5768     }
5769   }
5770
5771   if (N0.getOpcode() == ISD::SETCC) {
5772     EVT N0VT = N0.getOperand(0).getValueType();
5773     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5774     // Only do this before legalize for now.
5775     if (VT.isVector() && !LegalOperations &&
5776         TLI.getBooleanContents(N0VT) ==
5777             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5778       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5779       // of the same size as the compared operands. Only optimize sext(setcc())
5780       // if this is the case.
5781       EVT SVT = getSetCCResultType(N0VT);
5782
5783       // We know that the # elements of the results is the same as the
5784       // # elements of the compare (and the # elements of the compare result
5785       // for that matter).  Check to see that they are the same size.  If so,
5786       // we know that the element size of the sext'd result matches the
5787       // element size of the compare operands.
5788       if (VT.getSizeInBits() == SVT.getSizeInBits())
5789         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5790                              N0.getOperand(1),
5791                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5792
5793       // If the desired elements are smaller or larger than the source
5794       // elements we can use a matching integer vector type and then
5795       // truncate/sign extend
5796       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5797       if (SVT == MatchingVectorType) {
5798         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5799                                N0.getOperand(0), N0.getOperand(1),
5800                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5801         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5802       }
5803     }
5804
5805     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5806     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5807     SDLoc DL(N);
5808     SDValue NegOne =
5809       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5810     SDValue SCC =
5811       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5812                        NegOne, DAG.getConstant(0, DL, VT),
5813                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5814     if (SCC.getNode()) return SCC;
5815
5816     if (!VT.isVector()) {
5817       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5818       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5819         SDLoc DL(N);
5820         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5821         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5822                                      N0.getOperand(0), N0.getOperand(1), CC);
5823         return DAG.getSelect(DL, VT, SetCC,
5824                              NegOne, DAG.getConstant(0, DL, VT));
5825       }
5826     }
5827   }
5828
5829   // fold (sext x) -> (zext x) if the sign bit is known zero.
5830   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5831       DAG.SignBitIsZero(N0))
5832     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5833
5834   return SDValue();
5835 }
5836
5837 // isTruncateOf - If N is a truncate of some other value, return true, record
5838 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5839 // This function computes KnownZero to avoid a duplicated call to
5840 // computeKnownBits in the caller.
5841 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5842                          APInt &KnownZero) {
5843   APInt KnownOne;
5844   if (N->getOpcode() == ISD::TRUNCATE) {
5845     Op = N->getOperand(0);
5846     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5847     return true;
5848   }
5849
5850   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5851       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5852     return false;
5853
5854   SDValue Op0 = N->getOperand(0);
5855   SDValue Op1 = N->getOperand(1);
5856   assert(Op0.getValueType() == Op1.getValueType());
5857
5858   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5859   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5860   if (COp0 && COp0->isNullValue())
5861     Op = Op1;
5862   else if (COp1 && COp1->isNullValue())
5863     Op = Op0;
5864   else
5865     return false;
5866
5867   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5868
5869   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5870     return false;
5871
5872   return true;
5873 }
5874
5875 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5876   SDValue N0 = N->getOperand(0);
5877   EVT VT = N->getValueType(0);
5878
5879   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5880                                               LegalOperations))
5881     return SDValue(Res, 0);
5882
5883   // fold (zext (zext x)) -> (zext x)
5884   // fold (zext (aext x)) -> (zext x)
5885   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5886     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5887                        N0.getOperand(0));
5888
5889   // fold (zext (truncate x)) -> (zext x) or
5890   //      (zext (truncate x)) -> (truncate x)
5891   // This is valid when the truncated bits of x are already zero.
5892   // FIXME: We should extend this to work for vectors too.
5893   SDValue Op;
5894   APInt KnownZero;
5895   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5896     APInt TruncatedBits =
5897       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5898       APInt(Op.getValueSizeInBits(), 0) :
5899       APInt::getBitsSet(Op.getValueSizeInBits(),
5900                         N0.getValueSizeInBits(),
5901                         std::min(Op.getValueSizeInBits(),
5902                                  VT.getSizeInBits()));
5903     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5904       if (VT.bitsGT(Op.getValueType()))
5905         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5906       if (VT.bitsLT(Op.getValueType()))
5907         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5908
5909       return Op;
5910     }
5911   }
5912
5913   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5914   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5915   if (N0.getOpcode() == ISD::TRUNCATE) {
5916     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5917     if (NarrowLoad.getNode()) {
5918       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5919       if (NarrowLoad.getNode() != N0.getNode()) {
5920         CombineTo(N0.getNode(), NarrowLoad);
5921         // CombineTo deleted the truncate, if needed, but not what's under it.
5922         AddToWorklist(oye);
5923       }
5924       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5925     }
5926   }
5927
5928   // fold (zext (truncate x)) -> (and x, mask)
5929   if (N0.getOpcode() == ISD::TRUNCATE &&
5930       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5931
5932     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5933     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5934     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5935     if (NarrowLoad.getNode()) {
5936       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5937       if (NarrowLoad.getNode() != N0.getNode()) {
5938         CombineTo(N0.getNode(), NarrowLoad);
5939         // CombineTo deleted the truncate, if needed, but not what's under it.
5940         AddToWorklist(oye);
5941       }
5942       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5943     }
5944
5945     SDValue Op = N0.getOperand(0);
5946     if (Op.getValueType().bitsLT(VT)) {
5947       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5948       AddToWorklist(Op.getNode());
5949     } else if (Op.getValueType().bitsGT(VT)) {
5950       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5951       AddToWorklist(Op.getNode());
5952     }
5953     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5954                                   N0.getValueType().getScalarType());
5955   }
5956
5957   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5958   // if either of the casts is not free.
5959   if (N0.getOpcode() == ISD::AND &&
5960       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5961       N0.getOperand(1).getOpcode() == ISD::Constant &&
5962       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5963                            N0.getValueType()) ||
5964        !TLI.isZExtFree(N0.getValueType(), VT))) {
5965     SDValue X = N0.getOperand(0).getOperand(0);
5966     if (X.getValueType().bitsLT(VT)) {
5967       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5968     } else if (X.getValueType().bitsGT(VT)) {
5969       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5970     }
5971     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5972     Mask = Mask.zext(VT.getSizeInBits());
5973     SDLoc DL(N);
5974     return DAG.getNode(ISD::AND, DL, VT,
5975                        X, DAG.getConstant(Mask, DL, VT));
5976   }
5977
5978   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5979   // Only generate vector extloads when 1) they're legal, and 2) they are
5980   // deemed desirable by the target.
5981   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5982       ((!LegalOperations && !VT.isVector() &&
5983         !cast<LoadSDNode>(N0)->isVolatile()) ||
5984        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5985     bool DoXform = true;
5986     SmallVector<SDNode*, 4> SetCCs;
5987     if (!N0.hasOneUse())
5988       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5989     if (VT.isVector())
5990       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5991     if (DoXform) {
5992       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5993       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5994                                        LN0->getChain(),
5995                                        LN0->getBasePtr(), N0.getValueType(),
5996                                        LN0->getMemOperand());
5997       CombineTo(N, ExtLoad);
5998       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5999                                   N0.getValueType(), ExtLoad);
6000       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6001
6002       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6003                       ISD::ZERO_EXTEND);
6004       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6005     }
6006   }
6007
6008   // fold (zext (load x)) to multiple smaller zextloads.
6009   // Only on illegal but splittable vectors.
6010   if (SDValue ExtLoad = CombineExtLoad(N))
6011     return ExtLoad;
6012
6013   // fold (zext (and/or/xor (load x), cst)) ->
6014   //      (and/or/xor (zextload x), (zext cst))
6015   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6016        N0.getOpcode() == ISD::XOR) &&
6017       isa<LoadSDNode>(N0.getOperand(0)) &&
6018       N0.getOperand(1).getOpcode() == ISD::Constant &&
6019       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6020       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6021     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6022     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6023       bool DoXform = true;
6024       SmallVector<SDNode*, 4> SetCCs;
6025       if (!N0.hasOneUse())
6026         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6027                                           SetCCs, TLI);
6028       if (DoXform) {
6029         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6030                                          LN0->getChain(), LN0->getBasePtr(),
6031                                          LN0->getMemoryVT(),
6032                                          LN0->getMemOperand());
6033         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6034         Mask = Mask.zext(VT.getSizeInBits());
6035         SDLoc DL(N);
6036         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6037                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6038         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6039                                     SDLoc(N0.getOperand(0)),
6040                                     N0.getOperand(0).getValueType(), ExtLoad);
6041         CombineTo(N, And);
6042         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6043         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6044                         ISD::ZERO_EXTEND);
6045         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6046       }
6047     }
6048   }
6049
6050   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6051   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6052   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6053       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6054     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6055     EVT MemVT = LN0->getMemoryVT();
6056     if ((!LegalOperations && !LN0->isVolatile()) ||
6057         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6058       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6059                                        LN0->getChain(),
6060                                        LN0->getBasePtr(), MemVT,
6061                                        LN0->getMemOperand());
6062       CombineTo(N, ExtLoad);
6063       CombineTo(N0.getNode(),
6064                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6065                             ExtLoad),
6066                 ExtLoad.getValue(1));
6067       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6068     }
6069   }
6070
6071   if (N0.getOpcode() == ISD::SETCC) {
6072     if (!LegalOperations && VT.isVector() &&
6073         N0.getValueType().getVectorElementType() == MVT::i1) {
6074       EVT N0VT = N0.getOperand(0).getValueType();
6075       if (getSetCCResultType(N0VT) == N0.getValueType())
6076         return SDValue();
6077
6078       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6079       // Only do this before legalize for now.
6080       EVT EltVT = VT.getVectorElementType();
6081       SDLoc DL(N);
6082       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6083                                     DAG.getConstant(1, DL, EltVT));
6084       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6085         // We know that the # elements of the results is the same as the
6086         // # elements of the compare (and the # elements of the compare result
6087         // for that matter).  Check to see that they are the same size.  If so,
6088         // we know that the element size of the sext'd result matches the
6089         // element size of the compare operands.
6090         return DAG.getNode(ISD::AND, DL, VT,
6091                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6092                                          N0.getOperand(1),
6093                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6094                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6095                                        OneOps));
6096
6097       // If the desired elements are smaller or larger than the source
6098       // elements we can use a matching integer vector type and then
6099       // truncate/sign extend
6100       EVT MatchingElementType =
6101         EVT::getIntegerVT(*DAG.getContext(),
6102                           N0VT.getScalarType().getSizeInBits());
6103       EVT MatchingVectorType =
6104         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6105                          N0VT.getVectorNumElements());
6106       SDValue VsetCC =
6107         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6108                       N0.getOperand(1),
6109                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6110       return DAG.getNode(ISD::AND, DL, VT,
6111                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6112                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6113     }
6114
6115     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6116     SDLoc DL(N);
6117     SDValue SCC =
6118       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6119                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6120                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6121     if (SCC.getNode()) return SCC;
6122   }
6123
6124   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6125   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6126       isa<ConstantSDNode>(N0.getOperand(1)) &&
6127       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6128       N0.hasOneUse()) {
6129     SDValue ShAmt = N0.getOperand(1);
6130     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6131     if (N0.getOpcode() == ISD::SHL) {
6132       SDValue InnerZExt = N0.getOperand(0);
6133       // If the original shl may be shifting out bits, do not perform this
6134       // transformation.
6135       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6136         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6137       if (ShAmtVal > KnownZeroBits)
6138         return SDValue();
6139     }
6140
6141     SDLoc DL(N);
6142
6143     // Ensure that the shift amount is wide enough for the shifted value.
6144     if (VT.getSizeInBits() >= 256)
6145       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6146
6147     return DAG.getNode(N0.getOpcode(), DL, VT,
6148                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6149                        ShAmt);
6150   }
6151
6152   return SDValue();
6153 }
6154
6155 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6156   SDValue N0 = N->getOperand(0);
6157   EVT VT = N->getValueType(0);
6158
6159   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6160                                               LegalOperations))
6161     return SDValue(Res, 0);
6162
6163   // fold (aext (aext x)) -> (aext x)
6164   // fold (aext (zext x)) -> (zext x)
6165   // fold (aext (sext x)) -> (sext x)
6166   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6167       N0.getOpcode() == ISD::ZERO_EXTEND ||
6168       N0.getOpcode() == ISD::SIGN_EXTEND)
6169     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6170
6171   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6172   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6173   if (N0.getOpcode() == ISD::TRUNCATE) {
6174     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6175     if (NarrowLoad.getNode()) {
6176       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6177       if (NarrowLoad.getNode() != N0.getNode()) {
6178         CombineTo(N0.getNode(), NarrowLoad);
6179         // CombineTo deleted the truncate, if needed, but not what's under it.
6180         AddToWorklist(oye);
6181       }
6182       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6183     }
6184   }
6185
6186   // fold (aext (truncate x))
6187   if (N0.getOpcode() == ISD::TRUNCATE) {
6188     SDValue TruncOp = N0.getOperand(0);
6189     if (TruncOp.getValueType() == VT)
6190       return TruncOp; // x iff x size == zext size.
6191     if (TruncOp.getValueType().bitsGT(VT))
6192       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6193     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6194   }
6195
6196   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6197   // if the trunc is not free.
6198   if (N0.getOpcode() == ISD::AND &&
6199       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6200       N0.getOperand(1).getOpcode() == ISD::Constant &&
6201       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6202                           N0.getValueType())) {
6203     SDValue X = N0.getOperand(0).getOperand(0);
6204     if (X.getValueType().bitsLT(VT)) {
6205       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6206     } else if (X.getValueType().bitsGT(VT)) {
6207       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6208     }
6209     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6210     Mask = Mask.zext(VT.getSizeInBits());
6211     SDLoc DL(N);
6212     return DAG.getNode(ISD::AND, DL, VT,
6213                        X, DAG.getConstant(Mask, DL, VT));
6214   }
6215
6216   // fold (aext (load x)) -> (aext (truncate (extload x)))
6217   // None of the supported targets knows how to perform load and any_ext
6218   // on vectors in one instruction.  We only perform this transformation on
6219   // scalars.
6220   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6221       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6222       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6223     bool DoXform = true;
6224     SmallVector<SDNode*, 4> SetCCs;
6225     if (!N0.hasOneUse())
6226       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6227     if (DoXform) {
6228       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6229       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6230                                        LN0->getChain(),
6231                                        LN0->getBasePtr(), N0.getValueType(),
6232                                        LN0->getMemOperand());
6233       CombineTo(N, ExtLoad);
6234       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6235                                   N0.getValueType(), ExtLoad);
6236       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6237       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6238                       ISD::ANY_EXTEND);
6239       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6240     }
6241   }
6242
6243   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6244   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6245   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6246   if (N0.getOpcode() == ISD::LOAD &&
6247       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6248       N0.hasOneUse()) {
6249     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6250     ISD::LoadExtType ExtType = LN0->getExtensionType();
6251     EVT MemVT = LN0->getMemoryVT();
6252     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6253       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6254                                        VT, LN0->getChain(), LN0->getBasePtr(),
6255                                        MemVT, LN0->getMemOperand());
6256       CombineTo(N, ExtLoad);
6257       CombineTo(N0.getNode(),
6258                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6259                             N0.getValueType(), ExtLoad),
6260                 ExtLoad.getValue(1));
6261       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6262     }
6263   }
6264
6265   if (N0.getOpcode() == ISD::SETCC) {
6266     // For vectors:
6267     // aext(setcc) -> vsetcc
6268     // aext(setcc) -> truncate(vsetcc)
6269     // aext(setcc) -> aext(vsetcc)
6270     // Only do this before legalize for now.
6271     if (VT.isVector() && !LegalOperations) {
6272       EVT N0VT = N0.getOperand(0).getValueType();
6273         // We know that the # elements of the results is the same as the
6274         // # elements of the compare (and the # elements of the compare result
6275         // for that matter).  Check to see that they are the same size.  If so,
6276         // we know that the element size of the sext'd result matches the
6277         // element size of the compare operands.
6278       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6279         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6280                              N0.getOperand(1),
6281                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6282       // If the desired elements are smaller or larger than the source
6283       // elements we can use a matching integer vector type and then
6284       // truncate/any extend
6285       else {
6286         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6287         SDValue VsetCC =
6288           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6289                         N0.getOperand(1),
6290                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6291         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6292       }
6293     }
6294
6295     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6296     SDLoc DL(N);
6297     SDValue SCC =
6298       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6299                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6300                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6301     if (SCC.getNode())
6302       return SCC;
6303   }
6304
6305   return SDValue();
6306 }
6307
6308 /// See if the specified operand can be simplified with the knowledge that only
6309 /// the bits specified by Mask are used.  If so, return the simpler operand,
6310 /// otherwise return a null SDValue.
6311 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6312   switch (V.getOpcode()) {
6313   default: break;
6314   case ISD::Constant: {
6315     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6316     assert(CV && "Const value should be ConstSDNode.");
6317     const APInt &CVal = CV->getAPIntValue();
6318     APInt NewVal = CVal & Mask;
6319     if (NewVal != CVal)
6320       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6321     break;
6322   }
6323   case ISD::OR:
6324   case ISD::XOR:
6325     // If the LHS or RHS don't contribute bits to the or, drop them.
6326     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6327       return V.getOperand(1);
6328     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6329       return V.getOperand(0);
6330     break;
6331   case ISD::SRL:
6332     // Only look at single-use SRLs.
6333     if (!V.getNode()->hasOneUse())
6334       break;
6335     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6336       // See if we can recursively simplify the LHS.
6337       unsigned Amt = RHSC->getZExtValue();
6338
6339       // Watch out for shift count overflow though.
6340       if (Amt >= Mask.getBitWidth()) break;
6341       APInt NewMask = Mask << Amt;
6342       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6343       if (SimplifyLHS.getNode())
6344         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6345                            SimplifyLHS, V.getOperand(1));
6346     }
6347   }
6348   return SDValue();
6349 }
6350
6351 /// If the result of a wider load is shifted to right of N  bits and then
6352 /// truncated to a narrower type and where N is a multiple of number of bits of
6353 /// the narrower type, transform it to a narrower load from address + N / num of
6354 /// bits of new type. If the result is to be extended, also fold the extension
6355 /// to form a extending load.
6356 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6357   unsigned Opc = N->getOpcode();
6358
6359   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6360   SDValue N0 = N->getOperand(0);
6361   EVT VT = N->getValueType(0);
6362   EVT ExtVT = VT;
6363
6364   // This transformation isn't valid for vector loads.
6365   if (VT.isVector())
6366     return SDValue();
6367
6368   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6369   // extended to VT.
6370   if (Opc == ISD::SIGN_EXTEND_INREG) {
6371     ExtType = ISD::SEXTLOAD;
6372     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6373   } else if (Opc == ISD::SRL) {
6374     // Another special-case: SRL is basically zero-extending a narrower value.
6375     ExtType = ISD::ZEXTLOAD;
6376     N0 = SDValue(N, 0);
6377     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6378     if (!N01) return SDValue();
6379     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6380                               VT.getSizeInBits() - N01->getZExtValue());
6381   }
6382   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6383     return SDValue();
6384
6385   unsigned EVTBits = ExtVT.getSizeInBits();
6386
6387   // Do not generate loads of non-round integer types since these can
6388   // be expensive (and would be wrong if the type is not byte sized).
6389   if (!ExtVT.isRound())
6390     return SDValue();
6391
6392   unsigned ShAmt = 0;
6393   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6394     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6395       ShAmt = N01->getZExtValue();
6396       // Is the shift amount a multiple of size of VT?
6397       if ((ShAmt & (EVTBits-1)) == 0) {
6398         N0 = N0.getOperand(0);
6399         // Is the load width a multiple of size of VT?
6400         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6401           return SDValue();
6402       }
6403
6404       // At this point, we must have a load or else we can't do the transform.
6405       if (!isa<LoadSDNode>(N0)) return SDValue();
6406
6407       // Because a SRL must be assumed to *need* to zero-extend the high bits
6408       // (as opposed to anyext the high bits), we can't combine the zextload
6409       // lowering of SRL and an sextload.
6410       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6411         return SDValue();
6412
6413       // If the shift amount is larger than the input type then we're not
6414       // accessing any of the loaded bytes.  If the load was a zextload/extload
6415       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6416       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6417         return SDValue();
6418     }
6419   }
6420
6421   // If the load is shifted left (and the result isn't shifted back right),
6422   // we can fold the truncate through the shift.
6423   unsigned ShLeftAmt = 0;
6424   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6425       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6426     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6427       ShLeftAmt = N01->getZExtValue();
6428       N0 = N0.getOperand(0);
6429     }
6430   }
6431
6432   // If we haven't found a load, we can't narrow it.  Don't transform one with
6433   // multiple uses, this would require adding a new load.
6434   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6435     return SDValue();
6436
6437   // Don't change the width of a volatile load.
6438   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6439   if (LN0->isVolatile())
6440     return SDValue();
6441
6442   // Verify that we are actually reducing a load width here.
6443   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6444     return SDValue();
6445
6446   // For the transform to be legal, the load must produce only two values
6447   // (the value loaded and the chain).  Don't transform a pre-increment
6448   // load, for example, which produces an extra value.  Otherwise the
6449   // transformation is not equivalent, and the downstream logic to replace
6450   // uses gets things wrong.
6451   if (LN0->getNumValues() > 2)
6452     return SDValue();
6453
6454   // If the load that we're shrinking is an extload and we're not just
6455   // discarding the extension we can't simply shrink the load. Bail.
6456   // TODO: It would be possible to merge the extensions in some cases.
6457   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6458       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6459     return SDValue();
6460
6461   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6462     return SDValue();
6463
6464   EVT PtrType = N0.getOperand(1).getValueType();
6465
6466   if (PtrType == MVT::Untyped || PtrType.isExtended())
6467     // It's not possible to generate a constant of extended or untyped type.
6468     return SDValue();
6469
6470   // For big endian targets, we need to adjust the offset to the pointer to
6471   // load the correct bytes.
6472   if (TLI.isBigEndian()) {
6473     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6474     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6475     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6476   }
6477
6478   uint64_t PtrOff = ShAmt / 8;
6479   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6480   SDLoc DL(LN0);
6481   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6482                                PtrType, LN0->getBasePtr(),
6483                                DAG.getConstant(PtrOff, DL, PtrType));
6484   AddToWorklist(NewPtr.getNode());
6485
6486   SDValue Load;
6487   if (ExtType == ISD::NON_EXTLOAD)
6488     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6489                         LN0->getPointerInfo().getWithOffset(PtrOff),
6490                         LN0->isVolatile(), LN0->isNonTemporal(),
6491                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6492   else
6493     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6494                           LN0->getPointerInfo().getWithOffset(PtrOff),
6495                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6496                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6497
6498   // Replace the old load's chain with the new load's chain.
6499   WorklistRemover DeadNodes(*this);
6500   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6501
6502   // Shift the result left, if we've swallowed a left shift.
6503   SDValue Result = Load;
6504   if (ShLeftAmt != 0) {
6505     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6506     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6507       ShImmTy = VT;
6508     // If the shift amount is as large as the result size (but, presumably,
6509     // no larger than the source) then the useful bits of the result are
6510     // zero; we can't simply return the shortened shift, because the result
6511     // of that operation is undefined.
6512     SDLoc DL(N0);
6513     if (ShLeftAmt >= VT.getSizeInBits())
6514       Result = DAG.getConstant(0, DL, VT);
6515     else
6516       Result = DAG.getNode(ISD::SHL, DL, VT,
6517                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6518   }
6519
6520   // Return the new loaded value.
6521   return Result;
6522 }
6523
6524 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6525   SDValue N0 = N->getOperand(0);
6526   SDValue N1 = N->getOperand(1);
6527   EVT VT = N->getValueType(0);
6528   EVT EVT = cast<VTSDNode>(N1)->getVT();
6529   unsigned VTBits = VT.getScalarType().getSizeInBits();
6530   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6531
6532   // fold (sext_in_reg c1) -> c1
6533   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6534     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6535
6536   // If the input is already sign extended, just drop the extension.
6537   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6538     return N0;
6539
6540   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6541   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6542       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6543     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6544                        N0.getOperand(0), N1);
6545
6546   // fold (sext_in_reg (sext x)) -> (sext x)
6547   // fold (sext_in_reg (aext x)) -> (sext x)
6548   // if x is small enough.
6549   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6550     SDValue N00 = N0.getOperand(0);
6551     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6552         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6553       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6554   }
6555
6556   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6557   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6558     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6559
6560   // fold operands of sext_in_reg based on knowledge that the top bits are not
6561   // demanded.
6562   if (SimplifyDemandedBits(SDValue(N, 0)))
6563     return SDValue(N, 0);
6564
6565   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6566   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6567   SDValue NarrowLoad = ReduceLoadWidth(N);
6568   if (NarrowLoad.getNode())
6569     return NarrowLoad;
6570
6571   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6572   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6573   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6574   if (N0.getOpcode() == ISD::SRL) {
6575     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6576       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6577         // We can turn this into an SRA iff the input to the SRL is already sign
6578         // extended enough.
6579         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6580         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6581           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6582                              N0.getOperand(0), N0.getOperand(1));
6583       }
6584   }
6585
6586   // fold (sext_inreg (extload x)) -> (sextload x)
6587   if (ISD::isEXTLoad(N0.getNode()) &&
6588       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6589       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6590       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6591        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6592     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6593     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6594                                      LN0->getChain(),
6595                                      LN0->getBasePtr(), EVT,
6596                                      LN0->getMemOperand());
6597     CombineTo(N, ExtLoad);
6598     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6599     AddToWorklist(ExtLoad.getNode());
6600     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6601   }
6602   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6603   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6604       N0.hasOneUse() &&
6605       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6606       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6607        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6608     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6609     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6610                                      LN0->getChain(),
6611                                      LN0->getBasePtr(), EVT,
6612                                      LN0->getMemOperand());
6613     CombineTo(N, ExtLoad);
6614     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6615     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6616   }
6617
6618   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6619   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6620     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6621                                        N0.getOperand(1), false);
6622     if (BSwap.getNode())
6623       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6624                          BSwap, N1);
6625   }
6626
6627   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6628   // into a build_vector.
6629   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6630     SmallVector<SDValue, 8> Elts;
6631     unsigned NumElts = N0->getNumOperands();
6632     unsigned ShAmt = VTBits - EVTBits;
6633
6634     for (unsigned i = 0; i != NumElts; ++i) {
6635       SDValue Op = N0->getOperand(i);
6636       if (Op->getOpcode() == ISD::UNDEF) {
6637         Elts.push_back(Op);
6638         continue;
6639       }
6640
6641       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6642       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6643       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6644                                      SDLoc(Op), Op.getValueType()));
6645     }
6646
6647     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6648   }
6649
6650   return SDValue();
6651 }
6652
6653 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6654   SDValue N0 = N->getOperand(0);
6655   EVT VT = N->getValueType(0);
6656   bool isLE = TLI.isLittleEndian();
6657
6658   // noop truncate
6659   if (N0.getValueType() == N->getValueType(0))
6660     return N0;
6661   // fold (truncate c1) -> c1
6662   if (isConstantIntBuildVectorOrConstantInt(N0))
6663     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6664   // fold (truncate (truncate x)) -> (truncate x)
6665   if (N0.getOpcode() == ISD::TRUNCATE)
6666     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6667   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6668   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6669       N0.getOpcode() == ISD::SIGN_EXTEND ||
6670       N0.getOpcode() == ISD::ANY_EXTEND) {
6671     if (N0.getOperand(0).getValueType().bitsLT(VT))
6672       // if the source is smaller than the dest, we still need an extend
6673       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6674                          N0.getOperand(0));
6675     if (N0.getOperand(0).getValueType().bitsGT(VT))
6676       // if the source is larger than the dest, than we just need the truncate
6677       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6678     // if the source and dest are the same type, we can drop both the extend
6679     // and the truncate.
6680     return N0.getOperand(0);
6681   }
6682
6683   // Fold extract-and-trunc into a narrow extract. For example:
6684   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6685   //   i32 y = TRUNCATE(i64 x)
6686   //        -- becomes --
6687   //   v16i8 b = BITCAST (v2i64 val)
6688   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6689   //
6690   // Note: We only run this optimization after type legalization (which often
6691   // creates this pattern) and before operation legalization after which
6692   // we need to be more careful about the vector instructions that we generate.
6693   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6694       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6695
6696     EVT VecTy = N0.getOperand(0).getValueType();
6697     EVT ExTy = N0.getValueType();
6698     EVT TrTy = N->getValueType(0);
6699
6700     unsigned NumElem = VecTy.getVectorNumElements();
6701     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6702
6703     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6704     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6705
6706     SDValue EltNo = N0->getOperand(1);
6707     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6708       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6709       EVT IndexTy = TLI.getVectorIdxTy();
6710       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6711
6712       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6713                               NVT, N0.getOperand(0));
6714
6715       SDLoc DL(N);
6716       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6717                          DL, TrTy, V,
6718                          DAG.getConstant(Index, DL, IndexTy));
6719     }
6720   }
6721
6722   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6723   if (N0.getOpcode() == ISD::SELECT) {
6724     EVT SrcVT = N0.getValueType();
6725     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6726         TLI.isTruncateFree(SrcVT, VT)) {
6727       SDLoc SL(N0);
6728       SDValue Cond = N0.getOperand(0);
6729       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6730       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6731       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6732     }
6733   }
6734
6735   // Fold a series of buildvector, bitcast, and truncate if possible.
6736   // For example fold
6737   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6738   //   (2xi32 (buildvector x, y)).
6739   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6740       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6741       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6742       N0.getOperand(0).hasOneUse()) {
6743
6744     SDValue BuildVect = N0.getOperand(0);
6745     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6746     EVT TruncVecEltTy = VT.getVectorElementType();
6747
6748     // Check that the element types match.
6749     if (BuildVectEltTy == TruncVecEltTy) {
6750       // Now we only need to compute the offset of the truncated elements.
6751       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6752       unsigned TruncVecNumElts = VT.getVectorNumElements();
6753       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6754
6755       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6756              "Invalid number of elements");
6757
6758       SmallVector<SDValue, 8> Opnds;
6759       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6760         Opnds.push_back(BuildVect.getOperand(i));
6761
6762       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6763     }
6764   }
6765
6766   // See if we can simplify the input to this truncate through knowledge that
6767   // only the low bits are being used.
6768   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6769   // Currently we only perform this optimization on scalars because vectors
6770   // may have different active low bits.
6771   if (!VT.isVector()) {
6772     SDValue Shorter =
6773       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6774                                                VT.getSizeInBits()));
6775     if (Shorter.getNode())
6776       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6777   }
6778   // fold (truncate (load x)) -> (smaller load x)
6779   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6780   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6781     SDValue Reduced = ReduceLoadWidth(N);
6782     if (Reduced.getNode())
6783       return Reduced;
6784     // Handle the case where the load remains an extending load even
6785     // after truncation.
6786     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6787       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6788       if (!LN0->isVolatile() &&
6789           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6790         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6791                                          VT, LN0->getChain(), LN0->getBasePtr(),
6792                                          LN0->getMemoryVT(),
6793                                          LN0->getMemOperand());
6794         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6795         return NewLoad;
6796       }
6797     }
6798   }
6799   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6800   // where ... are all 'undef'.
6801   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6802     SmallVector<EVT, 8> VTs;
6803     SDValue V;
6804     unsigned Idx = 0;
6805     unsigned NumDefs = 0;
6806
6807     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6808       SDValue X = N0.getOperand(i);
6809       if (X.getOpcode() != ISD::UNDEF) {
6810         V = X;
6811         Idx = i;
6812         NumDefs++;
6813       }
6814       // Stop if more than one members are non-undef.
6815       if (NumDefs > 1)
6816         break;
6817       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6818                                      VT.getVectorElementType(),
6819                                      X.getValueType().getVectorNumElements()));
6820     }
6821
6822     if (NumDefs == 0)
6823       return DAG.getUNDEF(VT);
6824
6825     if (NumDefs == 1) {
6826       assert(V.getNode() && "The single defined operand is empty!");
6827       SmallVector<SDValue, 8> Opnds;
6828       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6829         if (i != Idx) {
6830           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6831           continue;
6832         }
6833         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6834         AddToWorklist(NV.getNode());
6835         Opnds.push_back(NV);
6836       }
6837       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6838     }
6839   }
6840
6841   // Simplify the operands using demanded-bits information.
6842   if (!VT.isVector() &&
6843       SimplifyDemandedBits(SDValue(N, 0)))
6844     return SDValue(N, 0);
6845
6846   return SDValue();
6847 }
6848
6849 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6850   SDValue Elt = N->getOperand(i);
6851   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6852     return Elt.getNode();
6853   return Elt.getOperand(Elt.getResNo()).getNode();
6854 }
6855
6856 /// build_pair (load, load) -> load
6857 /// if load locations are consecutive.
6858 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6859   assert(N->getOpcode() == ISD::BUILD_PAIR);
6860
6861   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6862   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6863   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6864       LD1->getAddressSpace() != LD2->getAddressSpace())
6865     return SDValue();
6866   EVT LD1VT = LD1->getValueType(0);
6867
6868   if (ISD::isNON_EXTLoad(LD2) &&
6869       LD2->hasOneUse() &&
6870       // If both are volatile this would reduce the number of volatile loads.
6871       // If one is volatile it might be ok, but play conservative and bail out.
6872       !LD1->isVolatile() &&
6873       !LD2->isVolatile() &&
6874       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6875     unsigned Align = LD1->getAlignment();
6876     unsigned NewAlign = TLI.getDataLayout()->
6877       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6878
6879     if (NewAlign <= Align &&
6880         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6881       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6882                          LD1->getBasePtr(), LD1->getPointerInfo(),
6883                          false, false, false, Align);
6884   }
6885
6886   return SDValue();
6887 }
6888
6889 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6890   SDValue N0 = N->getOperand(0);
6891   EVT VT = N->getValueType(0);
6892
6893   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6894   // Only do this before legalize, since afterward the target may be depending
6895   // on the bitconvert.
6896   // First check to see if this is all constant.
6897   if (!LegalTypes &&
6898       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6899       VT.isVector()) {
6900     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6901
6902     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6903     assert(!DestEltVT.isVector() &&
6904            "Element type of vector ValueType must not be vector!");
6905     if (isSimple)
6906       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6907   }
6908
6909   // If the input is a constant, let getNode fold it.
6910   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6911     // If we can't allow illegal operations, we need to check that this is just
6912     // a fp -> int or int -> conversion and that the resulting operation will
6913     // be legal.
6914     if (!LegalOperations ||
6915         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6916          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6917         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6918          TLI.isOperationLegal(ISD::Constant, VT)))
6919       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6920   }
6921
6922   // (conv (conv x, t1), t2) -> (conv x, t2)
6923   if (N0.getOpcode() == ISD::BITCAST)
6924     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6925                        N0.getOperand(0));
6926
6927   // fold (conv (load x)) -> (load (conv*)x)
6928   // If the resultant load doesn't need a higher alignment than the original!
6929   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6930       // Do not change the width of a volatile load.
6931       !cast<LoadSDNode>(N0)->isVolatile() &&
6932       // Do not remove the cast if the types differ in endian layout.
6933       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6934       TLI.hasBigEndianPartOrdering(VT) &&
6935       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6936       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6937     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6938     unsigned Align = TLI.getDataLayout()->
6939       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6940     unsigned OrigAlign = LN0->getAlignment();
6941
6942     if (Align <= OrigAlign) {
6943       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6944                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6945                                  LN0->isVolatile(), LN0->isNonTemporal(),
6946                                  LN0->isInvariant(), OrigAlign,
6947                                  LN0->getAAInfo());
6948       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6949       return Load;
6950     }
6951   }
6952
6953   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6954   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6955   // This often reduces constant pool loads.
6956   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6957        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6958       N0.getNode()->hasOneUse() && VT.isInteger() &&
6959       !VT.isVector() && !N0.getValueType().isVector()) {
6960     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6961                                   N0.getOperand(0));
6962     AddToWorklist(NewConv.getNode());
6963
6964     SDLoc DL(N);
6965     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6966     if (N0.getOpcode() == ISD::FNEG)
6967       return DAG.getNode(ISD::XOR, DL, VT,
6968                          NewConv, DAG.getConstant(SignBit, DL, VT));
6969     assert(N0.getOpcode() == ISD::FABS);
6970     return DAG.getNode(ISD::AND, DL, VT,
6971                        NewConv, DAG.getConstant(~SignBit, DL, VT));
6972   }
6973
6974   // fold (bitconvert (fcopysign cst, x)) ->
6975   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6976   // Note that we don't handle (copysign x, cst) because this can always be
6977   // folded to an fneg or fabs.
6978   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6979       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6980       VT.isInteger() && !VT.isVector()) {
6981     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6982     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6983     if (isTypeLegal(IntXVT)) {
6984       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6985                               IntXVT, N0.getOperand(1));
6986       AddToWorklist(X.getNode());
6987
6988       // If X has a different width than the result/lhs, sext it or truncate it.
6989       unsigned VTWidth = VT.getSizeInBits();
6990       if (OrigXWidth < VTWidth) {
6991         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6992         AddToWorklist(X.getNode());
6993       } else if (OrigXWidth > VTWidth) {
6994         // To get the sign bit in the right place, we have to shift it right
6995         // before truncating.
6996         SDLoc DL(X);
6997         X = DAG.getNode(ISD::SRL, DL,
6998                         X.getValueType(), X,
6999                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7000                                         X.getValueType()));
7001         AddToWorklist(X.getNode());
7002         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7003         AddToWorklist(X.getNode());
7004       }
7005
7006       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7007       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7008                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7009       AddToWorklist(X.getNode());
7010
7011       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7012                                 VT, N0.getOperand(0));
7013       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7014                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7015       AddToWorklist(Cst.getNode());
7016
7017       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7018     }
7019   }
7020
7021   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7022   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7023     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7024     if (CombineLD.getNode())
7025       return CombineLD;
7026   }
7027
7028   // Remove double bitcasts from shuffles - this is often a legacy of
7029   // XformToShuffleWithZero being used to combine bitmaskings (of
7030   // float vectors bitcast to integer vectors) into shuffles.
7031   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7032   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7033       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7034       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7035       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7036     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7037
7038     // If operands are a bitcast, peek through if it casts the original VT.
7039     // If operands are a UNDEF or constant, just bitcast back to original VT.
7040     auto PeekThroughBitcast = [&](SDValue Op) {
7041       if (Op.getOpcode() == ISD::BITCAST &&
7042           Op.getOperand(0)->getValueType(0) == VT)
7043         return SDValue(Op.getOperand(0));
7044       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7045           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7046         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7047       return SDValue();
7048     };
7049
7050     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7051     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7052     if (!(SV0 && SV1))
7053       return SDValue();
7054
7055     int MaskScale =
7056         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7057     SmallVector<int, 8> NewMask;
7058     for (int M : SVN->getMask())
7059       for (int i = 0; i != MaskScale; ++i)
7060         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7061
7062     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7063     if (!LegalMask) {
7064       std::swap(SV0, SV1);
7065       ShuffleVectorSDNode::commuteMask(NewMask);
7066       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7067     }
7068
7069     if (LegalMask)
7070       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7071   }
7072
7073   return SDValue();
7074 }
7075
7076 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7077   EVT VT = N->getValueType(0);
7078   return CombineConsecutiveLoads(N, VT);
7079 }
7080
7081 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7082 /// operands. DstEltVT indicates the destination element value type.
7083 SDValue DAGCombiner::
7084 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7085   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7086
7087   // If this is already the right type, we're done.
7088   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7089
7090   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7091   unsigned DstBitSize = DstEltVT.getSizeInBits();
7092
7093   // If this is a conversion of N elements of one type to N elements of another
7094   // type, convert each element.  This handles FP<->INT cases.
7095   if (SrcBitSize == DstBitSize) {
7096     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7097                               BV->getValueType(0).getVectorNumElements());
7098
7099     // Due to the FP element handling below calling this routine recursively,
7100     // we can end up with a scalar-to-vector node here.
7101     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7102       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7103                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7104                                      DstEltVT, BV->getOperand(0)));
7105
7106     SmallVector<SDValue, 8> Ops;
7107     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7108       SDValue Op = BV->getOperand(i);
7109       // If the vector element type is not legal, the BUILD_VECTOR operands
7110       // are promoted and implicitly truncated.  Make that explicit here.
7111       if (Op.getValueType() != SrcEltVT)
7112         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7113       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7114                                 DstEltVT, Op));
7115       AddToWorklist(Ops.back().getNode());
7116     }
7117     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7118   }
7119
7120   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7121   // handle annoying details of growing/shrinking FP values, we convert them to
7122   // int first.
7123   if (SrcEltVT.isFloatingPoint()) {
7124     // Convert the input float vector to a int vector where the elements are the
7125     // same sizes.
7126     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7127     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7128     SrcEltVT = IntVT;
7129   }
7130
7131   // Now we know the input is an integer vector.  If the output is a FP type,
7132   // convert to integer first, then to FP of the right size.
7133   if (DstEltVT.isFloatingPoint()) {
7134     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7135     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7136
7137     // Next, convert to FP elements of the same size.
7138     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7139   }
7140
7141   SDLoc DL(BV);
7142
7143   // Okay, we know the src/dst types are both integers of differing types.
7144   // Handling growing first.
7145   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7146   if (SrcBitSize < DstBitSize) {
7147     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7148
7149     SmallVector<SDValue, 8> Ops;
7150     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7151          i += NumInputsPerOutput) {
7152       bool isLE = TLI.isLittleEndian();
7153       APInt NewBits = APInt(DstBitSize, 0);
7154       bool EltIsUndef = true;
7155       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7156         // Shift the previously computed bits over.
7157         NewBits <<= SrcBitSize;
7158         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7159         if (Op.getOpcode() == ISD::UNDEF) continue;
7160         EltIsUndef = false;
7161
7162         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7163                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7164       }
7165
7166       if (EltIsUndef)
7167         Ops.push_back(DAG.getUNDEF(DstEltVT));
7168       else
7169         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7170     }
7171
7172     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7173     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7174   }
7175
7176   // Finally, this must be the case where we are shrinking elements: each input
7177   // turns into multiple outputs.
7178   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7179   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7180                             NumOutputsPerInput*BV->getNumOperands());
7181   SmallVector<SDValue, 8> Ops;
7182
7183   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7184     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7185       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7186       continue;
7187     }
7188
7189     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7190                   getAPIntValue().zextOrTrunc(SrcBitSize);
7191
7192     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7193       APInt ThisVal = OpVal.trunc(DstBitSize);
7194       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7195       OpVal = OpVal.lshr(DstBitSize);
7196     }
7197
7198     // For big endian targets, swap the order of the pieces of each element.
7199     if (TLI.isBigEndian())
7200       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7201   }
7202
7203   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7204 }
7205
7206 /// Try to perform FMA combining on a given FADD node.
7207 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7208
7209
7210
7211
7212   SDValue N0 = N->getOperand(0);
7213   SDValue N1 = N->getOperand(1);
7214   EVT VT = N->getValueType(0);
7215   SDLoc SL(N);
7216
7217   const TargetOptions &Options = DAG.getTarget().Options;
7218   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7219                        Options.UnsafeFPMath);
7220
7221   // Floating-point multiply-add with intermediate rounding.
7222   bool HasFMAD = (LegalOperations &&
7223                   TLI.isOperationLegal(ISD::FMAD, VT));
7224
7225   // Floating-point multiply-add without intermediate rounding.
7226   bool HasFMA = ((!LegalOperations ||
7227                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7228                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7229                  UnsafeFPMath);
7230
7231   // No valid opcode, do not combine.
7232   if (!HasFMAD && !HasFMA)
7233     return SDValue();
7234
7235   // Always prefer FMAD to FMA for precision.
7236   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7237   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7238   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7239
7240   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7241   if (N0.getOpcode() == ISD::FMUL &&
7242       (Aggressive || N0->hasOneUse())) {
7243     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7244                        N0.getOperand(0), N0.getOperand(1), N1);
7245   }
7246
7247   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7248   // Note: Commutes FADD operands.
7249   if (N1.getOpcode() == ISD::FMUL &&
7250       (Aggressive || N1->hasOneUse())) {
7251     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7252                        N1.getOperand(0), N1.getOperand(1), N0);
7253   }
7254
7255   // Look through FP_EXTEND nodes to do more combining.
7256   if (UnsafeFPMath && LookThroughFPExt) {
7257     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7258     if (N0.getOpcode() == ISD::FP_EXTEND) {
7259       SDValue N00 = N0.getOperand(0);
7260       if (N00.getOpcode() == ISD::FMUL)
7261         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7262                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7263                                        N00.getOperand(0)),
7264                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7265                                        N00.getOperand(1)), N1);
7266     }
7267
7268     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7269     // Note: Commutes FADD operands.
7270     if (N1.getOpcode() == ISD::FP_EXTEND) {
7271       SDValue N10 = N1.getOperand(0);
7272       if (N10.getOpcode() == ISD::FMUL)
7273         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7274                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7275                                        N10.getOperand(0)),
7276                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7277                                        N10.getOperand(1)), N0);
7278     }
7279   }
7280
7281   // More folding opportunities when target permits.
7282   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7283     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7284     if (N0.getOpcode() == PreferredFusedOpcode &&
7285         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7286       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7287                          N0.getOperand(0), N0.getOperand(1),
7288                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7289                                      N0.getOperand(2).getOperand(0),
7290                                      N0.getOperand(2).getOperand(1),
7291                                      N1));
7292     }
7293
7294     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7295     if (N1->getOpcode() == PreferredFusedOpcode &&
7296         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7297       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7298                          N1.getOperand(0), N1.getOperand(1),
7299                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7300                                      N1.getOperand(2).getOperand(0),
7301                                      N1.getOperand(2).getOperand(1),
7302                                      N0));
7303     }
7304
7305     if (UnsafeFPMath && LookThroughFPExt) {
7306       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7307       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7308       auto FoldFAddFMAFPExtFMul = [&] (
7309           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7310         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7311                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7312                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7313                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7314                                        Z));
7315       };
7316       if (N0.getOpcode() == PreferredFusedOpcode) {
7317         SDValue N02 = N0.getOperand(2);
7318         if (N02.getOpcode() == ISD::FP_EXTEND) {
7319           SDValue N020 = N02.getOperand(0);
7320           if (N020.getOpcode() == ISD::FMUL)
7321             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7322                                         N020.getOperand(0), N020.getOperand(1),
7323                                         N1);
7324         }
7325       }
7326
7327       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7328       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7329       // FIXME: This turns two single-precision and one double-precision
7330       // operation into two double-precision operations, which might not be
7331       // interesting for all targets, especially GPUs.
7332       auto FoldFAddFPExtFMAFMul = [&] (
7333           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7334         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7335                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7336                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7337                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7338                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7339                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7340                                        Z));
7341       };
7342       if (N0.getOpcode() == ISD::FP_EXTEND) {
7343         SDValue N00 = N0.getOperand(0);
7344         if (N00.getOpcode() == PreferredFusedOpcode) {
7345           SDValue N002 = N00.getOperand(2);
7346           if (N002.getOpcode() == ISD::FMUL)
7347             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7348                                         N002.getOperand(0), N002.getOperand(1),
7349                                         N1);
7350         }
7351       }
7352
7353       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7354       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7355       if (N1.getOpcode() == PreferredFusedOpcode) {
7356         SDValue N12 = N1.getOperand(2);
7357         if (N12.getOpcode() == ISD::FP_EXTEND) {
7358           SDValue N120 = N12.getOperand(0);
7359           if (N120.getOpcode() == ISD::FMUL)
7360             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7361                                         N120.getOperand(0), N120.getOperand(1),
7362                                         N0);
7363         }
7364       }
7365
7366       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7367       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7368       // FIXME: This turns two single-precision and one double-precision
7369       // operation into two double-precision operations, which might not be
7370       // interesting for all targets, especially GPUs.
7371       if (N1.getOpcode() == ISD::FP_EXTEND) {
7372         SDValue N10 = N1.getOperand(0);
7373         if (N10.getOpcode() == PreferredFusedOpcode) {
7374           SDValue N102 = N10.getOperand(2);
7375           if (N102.getOpcode() == ISD::FMUL)
7376             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7377                                         N102.getOperand(0), N102.getOperand(1),
7378                                         N0);
7379         }
7380       }
7381     }
7382   }
7383
7384   return SDValue();
7385 }
7386
7387 /// Try to perform FMA combining on a given FSUB node.
7388 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7389
7390
7391
7392   SDValue N0 = N->getOperand(0);
7393   SDValue N1 = N->getOperand(1);
7394   EVT VT = N->getValueType(0);
7395
7396   SDLoc SL(N);
7397
7398   const TargetOptions &Options = DAG.getTarget().Options;
7399   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7400                        Options.UnsafeFPMath);
7401
7402   // Floating-point multiply-add with intermediate rounding.
7403   bool HasFMAD = (LegalOperations &&
7404                   TLI.isOperationLegal(ISD::FMAD, VT));
7405
7406   // Floating-point multiply-add without intermediate rounding.
7407   bool HasFMA = ((!LegalOperations ||
7408                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7409                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7410                  UnsafeFPMath);
7411
7412   // No valid opcode, do not combine.
7413   if (!HasFMAD && !HasFMA)
7414     return SDValue();
7415
7416   // Always prefer FMAD to FMA for precision.
7417   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7418   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7419   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7420
7421   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7422   if (N0.getOpcode() == ISD::FMUL &&
7423       (Aggressive || N0->hasOneUse())) {
7424     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7425                        N0.getOperand(0), N0.getOperand(1),
7426                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7427   }
7428
7429   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7430   // Note: Commutes FSUB operands.
7431   if (N1.getOpcode() == ISD::FMUL &&
7432       (Aggressive || N1->hasOneUse()))
7433     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7434                        DAG.getNode(ISD::FNEG, SL, VT,
7435                                    N1.getOperand(0)),
7436                        N1.getOperand(1), N0);
7437
7438   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7439   if (N0.getOpcode() == ISD::FNEG &&
7440       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7441       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7442     SDValue N00 = N0.getOperand(0).getOperand(0);
7443     SDValue N01 = N0.getOperand(0).getOperand(1);
7444     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7445                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7446                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7447   }
7448
7449   // Look through FP_EXTEND nodes to do more combining.
7450   if (UnsafeFPMath && LookThroughFPExt) {
7451     // fold (fsub (fpext (fmul x, y)), z)
7452     //   -> (fma (fpext x), (fpext y), (fneg z))
7453     if (N0.getOpcode() == ISD::FP_EXTEND) {
7454       SDValue N00 = N0.getOperand(0);
7455       if (N00.getOpcode() == ISD::FMUL)
7456         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7457                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7458                                        N00.getOperand(0)),
7459                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7460                                        N00.getOperand(1)),
7461                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7462     }
7463
7464     // fold (fsub x, (fpext (fmul y, z)))
7465     //   -> (fma (fneg (fpext y)), (fpext z), x)
7466     // Note: Commutes FSUB operands.
7467     if (N1.getOpcode() == ISD::FP_EXTEND) {
7468       SDValue N10 = N1.getOperand(0);
7469       if (N10.getOpcode() == ISD::FMUL)
7470         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7471                            DAG.getNode(ISD::FNEG, SL, VT,
7472                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7473                                                    N10.getOperand(0))),
7474                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7475                                        N10.getOperand(1)),
7476                            N0);
7477     }
7478
7479     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7480     //   -> (fneg (fma (fpext x), (fpext y), z))
7481     // Note: This could be removed with appropriate canonicalization of the
7482     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7483     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7484     // from implementing the canonicalization in visitFSUB.
7485     if (N0.getOpcode() == ISD::FP_EXTEND) {
7486       SDValue N00 = N0.getOperand(0);
7487       if (N00.getOpcode() == ISD::FNEG) {
7488         SDValue N000 = N00.getOperand(0);
7489         if (N000.getOpcode() == ISD::FMUL) {
7490           return DAG.getNode(ISD::FNEG, SL, VT,
7491                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7492                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7493                                                      N000.getOperand(0)),
7494                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7495                                                      N000.getOperand(1)),
7496                                          N1));
7497         }
7498       }
7499     }
7500
7501     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7502     //   -> (fneg (fma (fpext x)), (fpext y), z)
7503     // Note: This could be removed with appropriate canonicalization of the
7504     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7505     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7506     // from implementing the canonicalization in visitFSUB.
7507     if (N0.getOpcode() == ISD::FNEG) {
7508       SDValue N00 = N0.getOperand(0);
7509       if (N00.getOpcode() == ISD::FP_EXTEND) {
7510         SDValue N000 = N00.getOperand(0);
7511         if (N000.getOpcode() == ISD::FMUL) {
7512           return DAG.getNode(ISD::FNEG, SL, VT,
7513                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7514                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7515                                                      N000.getOperand(0)),
7516                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7517                                                      N000.getOperand(1)),
7518                                          N1));
7519         }
7520       }
7521     }
7522
7523   }
7524
7525   // More folding opportunities when target permits.
7526   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7527     // fold (fsub (fma x, y, (fmul u, v)), z)
7528     //   -> (fma x, y (fma u, v, (fneg z)))
7529     if (N0.getOpcode() == PreferredFusedOpcode &&
7530         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7531       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7532                          N0.getOperand(0), N0.getOperand(1),
7533                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7534                                      N0.getOperand(2).getOperand(0),
7535                                      N0.getOperand(2).getOperand(1),
7536                                      DAG.getNode(ISD::FNEG, SL, VT,
7537                                                  N1)));
7538     }
7539
7540     // fold (fsub x, (fma y, z, (fmul u, v)))
7541     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7542     if (N1.getOpcode() == PreferredFusedOpcode &&
7543         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7544       SDValue N20 = N1.getOperand(2).getOperand(0);
7545       SDValue N21 = N1.getOperand(2).getOperand(1);
7546       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7547                          DAG.getNode(ISD::FNEG, SL, VT,
7548                                      N1.getOperand(0)),
7549                          N1.getOperand(1),
7550                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7551                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7552
7553                                      N21, N0));
7554     }
7555
7556     if (UnsafeFPMath && LookThroughFPExt) {
7557       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7558       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7559       if (N0.getOpcode() == PreferredFusedOpcode) {
7560         SDValue N02 = N0.getOperand(2);
7561         if (N02.getOpcode() == ISD::FP_EXTEND) {
7562           SDValue N020 = N02.getOperand(0);
7563           if (N020.getOpcode() == ISD::FMUL)
7564             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7565                                N0.getOperand(0), N0.getOperand(1),
7566                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7567                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7568                                                        N020.getOperand(0)),
7569                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7570                                                        N020.getOperand(1)),
7571                                            DAG.getNode(ISD::FNEG, SL, VT,
7572                                                        N1)));
7573         }
7574       }
7575
7576       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7577       //   -> (fma (fpext x), (fpext y),
7578       //           (fma (fpext u), (fpext v), (fneg z)))
7579       // FIXME: This turns two single-precision and one double-precision
7580       // operation into two double-precision operations, which might not be
7581       // interesting for all targets, especially GPUs.
7582       if (N0.getOpcode() == ISD::FP_EXTEND) {
7583         SDValue N00 = N0.getOperand(0);
7584         if (N00.getOpcode() == PreferredFusedOpcode) {
7585           SDValue N002 = N00.getOperand(2);
7586           if (N002.getOpcode() == ISD::FMUL)
7587             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7588                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7589                                            N00.getOperand(0)),
7590                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7591                                            N00.getOperand(1)),
7592                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7593                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7594                                                        N002.getOperand(0)),
7595                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7596                                                        N002.getOperand(1)),
7597                                            DAG.getNode(ISD::FNEG, SL, VT,
7598                                                        N1)));
7599         }
7600       }
7601
7602       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7603       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7604       if (N1.getOpcode() == PreferredFusedOpcode &&
7605         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7606         SDValue N120 = N1.getOperand(2).getOperand(0);
7607         if (N120.getOpcode() == ISD::FMUL) {
7608           SDValue N1200 = N120.getOperand(0);
7609           SDValue N1201 = N120.getOperand(1);
7610           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7611                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7612                              N1.getOperand(1),
7613                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7614                                          DAG.getNode(ISD::FNEG, SL, VT,
7615                                              DAG.getNode(ISD::FP_EXTEND, SL,
7616                                                          VT, N1200)),
7617                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7618                                                      N1201),
7619                                          N0));
7620         }
7621       }
7622
7623       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7624       //   -> (fma (fneg (fpext y)), (fpext z),
7625       //           (fma (fneg (fpext u)), (fpext v), x))
7626       // FIXME: This turns two single-precision and one double-precision
7627       // operation into two double-precision operations, which might not be
7628       // interesting for all targets, especially GPUs.
7629       if (N1.getOpcode() == ISD::FP_EXTEND &&
7630         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7631         SDValue N100 = N1.getOperand(0).getOperand(0);
7632         SDValue N101 = N1.getOperand(0).getOperand(1);
7633         SDValue N102 = N1.getOperand(0).getOperand(2);
7634         if (N102.getOpcode() == ISD::FMUL) {
7635           SDValue N1020 = N102.getOperand(0);
7636           SDValue N1021 = N102.getOperand(1);
7637           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7638                              DAG.getNode(ISD::FNEG, SL, VT,
7639                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7640                                                      N100)),
7641                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7642                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7643                                          DAG.getNode(ISD::FNEG, SL, VT,
7644                                              DAG.getNode(ISD::FP_EXTEND, SL,
7645                                                          VT, N1020)),
7646                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7647                                                      N1021),
7648                                          N0));
7649         }
7650       }
7651     }
7652   }
7653
7654   return SDValue();
7655 }
7656
7657 SDValue DAGCombiner::visitFADD(SDNode *N) {
7658   SDValue N0 = N->getOperand(0);
7659   SDValue N1 = N->getOperand(1);
7660   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7661   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7662   EVT VT = N->getValueType(0);
7663   const TargetOptions &Options = DAG.getTarget().Options;
7664
7665   // fold vector ops
7666   if (VT.isVector())
7667     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7668       return FoldedVOp;
7669
7670   // fold (fadd c1, c2) -> c1 + c2
7671   if (N0CFP && N1CFP)
7672     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7673
7674   // canonicalize constant to RHS
7675   if (N0CFP && !N1CFP)
7676     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7677
7678   // fold (fadd A, (fneg B)) -> (fsub A, B)
7679   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7680       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7681     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7682                        GetNegatedExpression(N1, DAG, LegalOperations));
7683
7684   // fold (fadd (fneg A), B) -> (fsub B, A)
7685   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7686       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7687     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7688                        GetNegatedExpression(N0, DAG, LegalOperations));
7689
7690   // If 'unsafe math' is enabled, fold lots of things.
7691   if (Options.UnsafeFPMath) {
7692     // No FP constant should be created after legalization as Instruction
7693     // Selection pass has a hard time dealing with FP constants.
7694     bool AllowNewConst = (Level < AfterLegalizeDAG);
7695
7696     // fold (fadd A, 0) -> A
7697     if (N1CFP && N1CFP->getValueAPF().isZero())
7698       return N0;
7699
7700     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7701     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7702         isa<ConstantFPSDNode>(N0.getOperand(1)))
7703       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7704                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
7705                                      N0.getOperand(1), N1));
7706
7707     // If allowed, fold (fadd (fneg x), x) -> 0.0
7708     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7709       return DAG.getConstantFP(0.0, SDLoc(N), VT);
7710
7711     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7712     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7713       return DAG.getConstantFP(0.0, SDLoc(N), VT);
7714
7715     // We can fold chains of FADD's of the same value into multiplications.
7716     // This transform is not safe in general because we are reducing the number
7717     // of rounding steps.
7718     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7719       if (N0.getOpcode() == ISD::FMUL) {
7720         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7721         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7722
7723         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7724         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7725           SDLoc DL(N);
7726           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7727                                        SDValue(CFP01, 0),
7728                                        DAG.getConstantFP(1.0, DL, VT));
7729           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7730         }
7731
7732         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7733         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7734             N1.getOperand(0) == N1.getOperand(1) &&
7735             N0.getOperand(0) == N1.getOperand(0)) {
7736           SDLoc DL(N);
7737           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7738                                        SDValue(CFP01, 0),
7739                                        DAG.getConstantFP(2.0, DL, VT));
7740           return DAG.getNode(ISD::FMUL, DL, VT,
7741                              N0.getOperand(0), NewCFP);
7742         }
7743       }
7744
7745       if (N1.getOpcode() == ISD::FMUL) {
7746         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7747         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7748
7749         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7750         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7751           SDLoc DL(N);
7752           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7753                                        SDValue(CFP11, 0),
7754                                        DAG.getConstantFP(1.0, DL, VT));
7755           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7756         }
7757
7758         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7759         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7760             N0.getOperand(0) == N0.getOperand(1) &&
7761             N1.getOperand(0) == N0.getOperand(0)) {
7762           SDLoc DL(N);
7763           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7764                                        SDValue(CFP11, 0),
7765                                        DAG.getConstantFP(2.0, DL, VT));
7766           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7767         }
7768       }
7769
7770       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7771         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7772         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7773         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7774             (N0.getOperand(0) == N1)) {
7775           SDLoc DL(N);
7776           return DAG.getNode(ISD::FMUL, DL, VT,
7777                              N1, DAG.getConstantFP(3.0, DL, VT));
7778         }
7779       }
7780
7781       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7782         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7783         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7784         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7785             N1.getOperand(0) == N0) {
7786           SDLoc DL(N);
7787           return DAG.getNode(ISD::FMUL, DL, VT,
7788                              N0, DAG.getConstantFP(3.0, DL, VT));
7789         }
7790       }
7791
7792       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7793       if (AllowNewConst &&
7794           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7795           N0.getOperand(0) == N0.getOperand(1) &&
7796           N1.getOperand(0) == N1.getOperand(1) &&
7797           N0.getOperand(0) == N1.getOperand(0)) {
7798         SDLoc DL(N);
7799         return DAG.getNode(ISD::FMUL, DL, VT,
7800                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7801       }
7802     }
7803   } // enable-unsafe-fp-math
7804
7805   // FADD -> FMA combines:
7806   SDValue Fused = visitFADDForFMACombine(N);
7807   if (Fused) {
7808     AddToWorklist(Fused.getNode());
7809     return Fused;
7810   }
7811
7812   return SDValue();
7813 }
7814
7815 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7816   SDValue N0 = N->getOperand(0);
7817   SDValue N1 = N->getOperand(1);
7818   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7819   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7820   EVT VT = N->getValueType(0);
7821   SDLoc dl(N);
7822   const TargetOptions &Options = DAG.getTarget().Options;
7823
7824   // fold vector ops
7825   if (VT.isVector())
7826     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7827       return FoldedVOp;
7828
7829   // fold (fsub c1, c2) -> c1-c2
7830   if (N0CFP && N1CFP)
7831     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7832
7833   // fold (fsub A, (fneg B)) -> (fadd A, B)
7834   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7835     return DAG.getNode(ISD::FADD, dl, VT, N0,
7836                        GetNegatedExpression(N1, DAG, LegalOperations));
7837
7838   // If 'unsafe math' is enabled, fold lots of things.
7839   if (Options.UnsafeFPMath) {
7840     // (fsub A, 0) -> A
7841     if (N1CFP && N1CFP->getValueAPF().isZero())
7842       return N0;
7843
7844     // (fsub 0, B) -> -B
7845     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7846       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7847         return GetNegatedExpression(N1, DAG, LegalOperations);
7848       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7849         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7850     }
7851
7852     // (fsub x, x) -> 0.0
7853     if (N0 == N1)
7854       return DAG.getConstantFP(0.0f, dl, VT);
7855
7856     // (fsub x, (fadd x, y)) -> (fneg y)
7857     // (fsub x, (fadd y, x)) -> (fneg y)
7858     if (N1.getOpcode() == ISD::FADD) {
7859       SDValue N10 = N1->getOperand(0);
7860       SDValue N11 = N1->getOperand(1);
7861
7862       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7863         return GetNegatedExpression(N11, DAG, LegalOperations);
7864
7865       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7866         return GetNegatedExpression(N10, DAG, LegalOperations);
7867     }
7868   }
7869
7870   // FSUB -> FMA combines:
7871   SDValue Fused = visitFSUBForFMACombine(N);
7872   if (Fused) {
7873     AddToWorklist(Fused.getNode());
7874     return Fused;
7875   }
7876
7877   return SDValue();
7878 }
7879
7880 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7881   SDValue N0 = N->getOperand(0);
7882   SDValue N1 = N->getOperand(1);
7883   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7884   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7885   EVT VT = N->getValueType(0);
7886   const TargetOptions &Options = DAG.getTarget().Options;
7887
7888   // fold vector ops
7889   if (VT.isVector()) {
7890     // This just handles C1 * C2 for vectors. Other vector folds are below.
7891     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7892       return FoldedVOp;
7893   }
7894
7895   // fold (fmul c1, c2) -> c1*c2
7896   if (N0CFP && N1CFP)
7897     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7898
7899   // canonicalize constant to RHS
7900   if (isConstantFPBuildVectorOrConstantFP(N0) &&
7901      !isConstantFPBuildVectorOrConstantFP(N1))
7902     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7903
7904   // fold (fmul A, 1.0) -> A
7905   if (N1CFP && N1CFP->isExactlyValue(1.0))
7906     return N0;
7907
7908   if (Options.UnsafeFPMath) {
7909     // fold (fmul A, 0) -> 0
7910     if (N1CFP && N1CFP->getValueAPF().isZero())
7911       return N1;
7912
7913     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7914     if (N0.getOpcode() == ISD::FMUL) {
7915       // Fold scalars or any vector constants (not just splats).
7916       // This fold is done in general by InstCombine, but extra fmul insts
7917       // may have been generated during lowering.
7918       SDValue N00 = N0.getOperand(0);
7919       SDValue N01 = N0.getOperand(1);
7920       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7921       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7922       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7923       
7924       // Check 1: Make sure that the first operand of the inner multiply is NOT
7925       // a constant. Otherwise, we may induce infinite looping.
7926       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7927         // Check 2: Make sure that the second operand of the inner multiply and
7928         // the second operand of the outer multiply are constants.
7929         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7930             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7931           SDLoc SL(N);
7932           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7933           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7934         }
7935       }
7936     }
7937
7938     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7939     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7940     // during an early run of DAGCombiner can prevent folding with fmuls
7941     // inserted during lowering.
7942     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7943       SDLoc SL(N);
7944       const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7945       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7946       return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7947     }
7948   }
7949
7950   // fold (fmul X, 2.0) -> (fadd X, X)
7951   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7952     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7953
7954   // fold (fmul X, -1.0) -> (fneg X)
7955   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7956     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7957       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7958
7959   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7960   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7961     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7962       // Both can be negated for free, check to see if at least one is cheaper
7963       // negated.
7964       if (LHSNeg == 2 || RHSNeg == 2)
7965         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7966                            GetNegatedExpression(N0, DAG, LegalOperations),
7967                            GetNegatedExpression(N1, DAG, LegalOperations));
7968     }
7969   }
7970
7971   return SDValue();
7972 }
7973
7974 SDValue DAGCombiner::visitFMA(SDNode *N) {
7975   SDValue N0 = N->getOperand(0);
7976   SDValue N1 = N->getOperand(1);
7977   SDValue N2 = N->getOperand(2);
7978   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7979   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7980   EVT VT = N->getValueType(0);
7981   SDLoc dl(N);
7982   const TargetOptions &Options = DAG.getTarget().Options;
7983
7984   // Constant fold FMA.
7985   if (isa<ConstantFPSDNode>(N0) &&
7986       isa<ConstantFPSDNode>(N1) &&
7987       isa<ConstantFPSDNode>(N2)) {
7988     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7989   }
7990
7991   if (Options.UnsafeFPMath) {
7992     if (N0CFP && N0CFP->isZero())
7993       return N2;
7994     if (N1CFP && N1CFP->isZero())
7995       return N2;
7996   }
7997   if (N0CFP && N0CFP->isExactlyValue(1.0))
7998     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7999   if (N1CFP && N1CFP->isExactlyValue(1.0))
8000     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8001
8002   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8003   if (N0CFP && !N1CFP)
8004     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8005
8006   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8007   if (Options.UnsafeFPMath && N1CFP &&
8008       N2.getOpcode() == ISD::FMUL &&
8009       N0 == N2.getOperand(0) &&
8010       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8011     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8012                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8013   }
8014
8015
8016   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8017   if (Options.UnsafeFPMath &&
8018       N0.getOpcode() == ISD::FMUL && N1CFP &&
8019       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8020     return DAG.getNode(ISD::FMA, dl, VT,
8021                        N0.getOperand(0),
8022                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8023                        N2);
8024   }
8025
8026   // (fma x, 1, y) -> (fadd x, y)
8027   // (fma x, -1, y) -> (fadd (fneg x), y)
8028   if (N1CFP) {
8029     if (N1CFP->isExactlyValue(1.0))
8030       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8031
8032     if (N1CFP->isExactlyValue(-1.0) &&
8033         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8034       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8035       AddToWorklist(RHSNeg.getNode());
8036       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8037     }
8038   }
8039
8040   // (fma x, c, x) -> (fmul x, (c+1))
8041   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8042     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8043                        DAG.getNode(ISD::FADD, dl, VT,
8044                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8045
8046   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8047   if (Options.UnsafeFPMath && N1CFP &&
8048       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8049     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8050                        DAG.getNode(ISD::FADD, dl, VT,
8051                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8052
8053
8054   return SDValue();
8055 }
8056
8057 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8058   SDValue N0 = N->getOperand(0);
8059   SDValue N1 = N->getOperand(1);
8060   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8061   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8062   EVT VT = N->getValueType(0);
8063   SDLoc DL(N);
8064   const TargetOptions &Options = DAG.getTarget().Options;
8065
8066   // fold vector ops
8067   if (VT.isVector())
8068     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8069       return FoldedVOp;
8070
8071   // fold (fdiv c1, c2) -> c1/c2
8072   if (N0CFP && N1CFP)
8073     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8074
8075   if (Options.UnsafeFPMath) {
8076     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8077     if (N1CFP) {
8078       // Compute the reciprocal 1.0 / c2.
8079       APFloat N1APF = N1CFP->getValueAPF();
8080       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8081       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8082       // Only do the transform if the reciprocal is a legal fp immediate that
8083       // isn't too nasty (eg NaN, denormal, ...).
8084       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8085           (!LegalOperations ||
8086            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8087            // backend)... we should handle this gracefully after Legalize.
8088            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8089            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8090            TLI.isFPImmLegal(Recip, VT)))
8091         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8092                            DAG.getConstantFP(Recip, DL, VT));
8093     }
8094
8095     // If this FDIV is part of a reciprocal square root, it may be folded
8096     // into a target-specific square root estimate instruction.
8097     if (N1.getOpcode() == ISD::FSQRT) {
8098       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8099         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8100       }
8101     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8102                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8103       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8104         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8105         AddToWorklist(RV.getNode());
8106         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8107       }
8108     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8109                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8110       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8111         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8112         AddToWorklist(RV.getNode());
8113         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8114       }
8115     } else if (N1.getOpcode() == ISD::FMUL) {
8116       // Look through an FMUL. Even though this won't remove the FDIV directly,
8117       // it's still worthwhile to get rid of the FSQRT if possible.
8118       SDValue SqrtOp;
8119       SDValue OtherOp;
8120       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8121         SqrtOp = N1.getOperand(0);
8122         OtherOp = N1.getOperand(1);
8123       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8124         SqrtOp = N1.getOperand(1);
8125         OtherOp = N1.getOperand(0);
8126       }
8127       if (SqrtOp.getNode()) {
8128         // We found a FSQRT, so try to make this fold:
8129         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8130         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8131           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8132           AddToWorklist(RV.getNode());
8133           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8134         }
8135       }
8136     }
8137
8138     // Fold into a reciprocal estimate and multiply instead of a real divide.
8139     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8140       AddToWorklist(RV.getNode());
8141       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8142     }
8143   }
8144
8145   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8146   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8147     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8148       // Both can be negated for free, check to see if at least one is cheaper
8149       // negated.
8150       if (LHSNeg == 2 || RHSNeg == 2)
8151         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8152                            GetNegatedExpression(N0, DAG, LegalOperations),
8153                            GetNegatedExpression(N1, DAG, LegalOperations));
8154     }
8155   }
8156
8157   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8158   // reciprocal.
8159   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8160   // Notice that this is not always beneficial. One reason is different target
8161   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8162   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8163   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8164   if (Options.UnsafeFPMath) {
8165     // Skip if current node is a reciprocal.
8166     if (N0CFP && N0CFP->isExactlyValue(1.0))
8167       return SDValue();
8168
8169     SmallVector<SDNode *, 4> Users;
8170     // Find all FDIV users of the same divisor.
8171     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8172                               UE = N1.getNode()->use_end();
8173          UI != UE; ++UI) {
8174       SDNode *User = UI.getUse().getUser();
8175       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8176         Users.push_back(User);
8177     }
8178
8179     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8180       SDLoc DL(N);
8181       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8182       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8183
8184       // Dividend / Divisor -> Dividend * Reciprocal
8185       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8186         if ((*I)->getOperand(0) != FPOne) {
8187           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8188                                         (*I)->getOperand(0), Reciprocal);
8189           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8190         }
8191       }
8192       return SDValue();
8193     }
8194   }
8195
8196   return SDValue();
8197 }
8198
8199 SDValue DAGCombiner::visitFREM(SDNode *N) {
8200   SDValue N0 = N->getOperand(0);
8201   SDValue N1 = N->getOperand(1);
8202   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8203   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8204   EVT VT = N->getValueType(0);
8205
8206   // fold (frem c1, c2) -> fmod(c1,c2)
8207   if (N0CFP && N1CFP)
8208     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8209
8210   return SDValue();
8211 }
8212
8213 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8214   if (DAG.getTarget().Options.UnsafeFPMath &&
8215       !TLI.isFsqrtCheap()) {
8216     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8217     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8218       EVT VT = RV.getValueType();
8219       SDLoc DL(N);
8220       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8221       AddToWorklist(RV.getNode());
8222
8223       // Unfortunately, RV is now NaN if the input was exactly 0.
8224       // Select out this case and force the answer to 0.
8225       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8226       SDValue ZeroCmp =
8227         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8228                      N->getOperand(0), Zero, ISD::SETEQ);
8229       AddToWorklist(ZeroCmp.getNode());
8230       AddToWorklist(RV.getNode());
8231
8232       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8233                        DL, VT, ZeroCmp, Zero, RV);
8234       return RV;
8235     }
8236   }
8237   return SDValue();
8238 }
8239
8240 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8241   SDValue N0 = N->getOperand(0);
8242   SDValue N1 = N->getOperand(1);
8243   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8244   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8245   EVT VT = N->getValueType(0);
8246
8247   if (N0CFP && N1CFP)  // Constant fold
8248     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8249
8250   if (N1CFP) {
8251     const APFloat& V = N1CFP->getValueAPF();
8252     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8253     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8254     if (!V.isNegative()) {
8255       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8256         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8257     } else {
8258       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8259         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8260                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8261     }
8262   }
8263
8264   // copysign(fabs(x), y) -> copysign(x, y)
8265   // copysign(fneg(x), y) -> copysign(x, y)
8266   // copysign(copysign(x,z), y) -> copysign(x, y)
8267   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8268       N0.getOpcode() == ISD::FCOPYSIGN)
8269     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8270                        N0.getOperand(0), N1);
8271
8272   // copysign(x, abs(y)) -> abs(x)
8273   if (N1.getOpcode() == ISD::FABS)
8274     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8275
8276   // copysign(x, copysign(y,z)) -> copysign(x, z)
8277   if (N1.getOpcode() == ISD::FCOPYSIGN)
8278     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8279                        N0, N1.getOperand(1));
8280
8281   // copysign(x, fp_extend(y)) -> copysign(x, y)
8282   // copysign(x, fp_round(y)) -> copysign(x, y)
8283   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8284     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8285                        N0, N1.getOperand(0));
8286
8287   return SDValue();
8288 }
8289
8290 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8291   SDValue N0 = N->getOperand(0);
8292   EVT VT = N->getValueType(0);
8293   EVT OpVT = N0.getValueType();
8294
8295   // fold (sint_to_fp c1) -> c1fp
8296   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8297       // ...but only if the target supports immediate floating-point values
8298       (!LegalOperations ||
8299        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8300     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8301
8302   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8303   // but UINT_TO_FP is legal on this target, try to convert.
8304   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8305       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8306     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8307     if (DAG.SignBitIsZero(N0))
8308       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8309   }
8310
8311   // The next optimizations are desirable only if SELECT_CC can be lowered.
8312   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8313     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8314     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8315         !VT.isVector() &&
8316         (!LegalOperations ||
8317          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8318       SDLoc DL(N);
8319       SDValue Ops[] =
8320         { N0.getOperand(0), N0.getOperand(1),
8321           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8322           N0.getOperand(2) };
8323       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8324     }
8325
8326     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8327     //      (select_cc x, y, 1.0, 0.0,, cc)
8328     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8329         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8330         (!LegalOperations ||
8331          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8332       SDLoc DL(N);
8333       SDValue Ops[] =
8334         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8335           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8336           N0.getOperand(0).getOperand(2) };
8337       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8338     }
8339   }
8340
8341   return SDValue();
8342 }
8343
8344 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8345   SDValue N0 = N->getOperand(0);
8346   EVT VT = N->getValueType(0);
8347   EVT OpVT = N0.getValueType();
8348
8349   // fold (uint_to_fp c1) -> c1fp
8350   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8351       // ...but only if the target supports immediate floating-point values
8352       (!LegalOperations ||
8353        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8354     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8355
8356   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8357   // but SINT_TO_FP is legal on this target, try to convert.
8358   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8359       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8360     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8361     if (DAG.SignBitIsZero(N0))
8362       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8363   }
8364
8365   // The next optimizations are desirable only if SELECT_CC can be lowered.
8366   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8367     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8368
8369     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8370         (!LegalOperations ||
8371          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8372       SDLoc DL(N);
8373       SDValue Ops[] =
8374         { N0.getOperand(0), N0.getOperand(1),
8375           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8376           N0.getOperand(2) };
8377       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8378     }
8379   }
8380
8381   return SDValue();
8382 }
8383
8384 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8385 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8386   SDValue N0 = N->getOperand(0);
8387   EVT VT = N->getValueType(0);
8388
8389   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8390     return SDValue();
8391
8392   SDValue Src = N0.getOperand(0);
8393   EVT SrcVT = Src.getValueType();
8394   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8395   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8396
8397   // We can safely assume the conversion won't overflow the output range,
8398   // because (for example) (uint8_t)18293.f is undefined behavior.
8399
8400   // Since we can assume the conversion won't overflow, our decision as to
8401   // whether the input will fit in the float should depend on the minimum
8402   // of the input range and output range.
8403
8404   // This means this is also safe for a signed input and unsigned output, since
8405   // a negative input would lead to undefined behavior.
8406   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8407   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8408   unsigned ActualSize = std::min(InputSize, OutputSize);
8409   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8410
8411   // We can only fold away the float conversion if the input range can be
8412   // represented exactly in the float range.
8413   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8414     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8415       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8416                                                        : ISD::ZERO_EXTEND;
8417       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8418     }
8419     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8420       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8421     if (SrcVT == VT)
8422       return Src;
8423     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8424   }
8425   return SDValue();
8426 }
8427
8428 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8429   SDValue N0 = N->getOperand(0);
8430   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8431   EVT VT = N->getValueType(0);
8432
8433   // fold (fp_to_sint c1fp) -> c1
8434   if (N0CFP)
8435     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8436
8437   return FoldIntToFPToInt(N, DAG);
8438 }
8439
8440 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8441   SDValue N0 = N->getOperand(0);
8442   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8443   EVT VT = N->getValueType(0);
8444
8445   // fold (fp_to_uint c1fp) -> c1
8446   if (N0CFP)
8447     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8448
8449   return FoldIntToFPToInt(N, DAG);
8450 }
8451
8452 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8453   SDValue N0 = N->getOperand(0);
8454   SDValue N1 = N->getOperand(1);
8455   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8456   EVT VT = N->getValueType(0);
8457
8458   // fold (fp_round c1fp) -> c1fp
8459   if (N0CFP)
8460     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8461
8462   // fold (fp_round (fp_extend x)) -> x
8463   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8464     return N0.getOperand(0);
8465
8466   // fold (fp_round (fp_round x)) -> (fp_round x)
8467   if (N0.getOpcode() == ISD::FP_ROUND) {
8468     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8469     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8470     // If the first fp_round isn't a value preserving truncation, it might
8471     // introduce a tie in the second fp_round, that wouldn't occur in the
8472     // single-step fp_round we want to fold to.
8473     // In other words, double rounding isn't the same as rounding.
8474     // Also, this is a value preserving truncation iff both fp_round's are.
8475     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8476       SDLoc DL(N);
8477       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8478                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8479     }
8480   }
8481
8482   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8483   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8484     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8485                               N0.getOperand(0), N1);
8486     AddToWorklist(Tmp.getNode());
8487     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8488                        Tmp, N0.getOperand(1));
8489   }
8490
8491   return SDValue();
8492 }
8493
8494 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8495   SDValue N0 = N->getOperand(0);
8496   EVT VT = N->getValueType(0);
8497   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8498   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8499
8500   // fold (fp_round_inreg c1fp) -> c1fp
8501   if (N0CFP && isTypeLegal(EVT)) {
8502     SDLoc DL(N);
8503     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8504     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8505   }
8506
8507   return SDValue();
8508 }
8509
8510 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8511   SDValue N0 = N->getOperand(0);
8512   EVT VT = N->getValueType(0);
8513
8514   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8515   if (N->hasOneUse() &&
8516       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8517     return SDValue();
8518
8519   // fold (fp_extend c1fp) -> c1fp
8520   if (isConstantFPBuildVectorOrConstantFP(N0))
8521     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8522
8523   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8524   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8525       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8526     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8527
8528   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8529   // value of X.
8530   if (N0.getOpcode() == ISD::FP_ROUND
8531       && N0.getNode()->getConstantOperandVal(1) == 1) {
8532     SDValue In = N0.getOperand(0);
8533     if (In.getValueType() == VT) return In;
8534     if (VT.bitsLT(In.getValueType()))
8535       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8536                          In, N0.getOperand(1));
8537     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8538   }
8539
8540   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8541   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8542        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8543     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8544     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8545                                      LN0->getChain(),
8546                                      LN0->getBasePtr(), N0.getValueType(),
8547                                      LN0->getMemOperand());
8548     CombineTo(N, ExtLoad);
8549     CombineTo(N0.getNode(),
8550               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8551                           N0.getValueType(), ExtLoad,
8552                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8553               ExtLoad.getValue(1));
8554     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8555   }
8556
8557   return SDValue();
8558 }
8559
8560 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8561   SDValue N0 = N->getOperand(0);
8562   EVT VT = N->getValueType(0);
8563
8564   // fold (fceil c1) -> fceil(c1)
8565   if (isConstantFPBuildVectorOrConstantFP(N0))
8566     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8567
8568   return SDValue();
8569 }
8570
8571 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8572   SDValue N0 = N->getOperand(0);
8573   EVT VT = N->getValueType(0);
8574
8575   // fold (ftrunc c1) -> ftrunc(c1)
8576   if (isConstantFPBuildVectorOrConstantFP(N0))
8577     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8578
8579   return SDValue();
8580 }
8581
8582 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8583   SDValue N0 = N->getOperand(0);
8584   EVT VT = N->getValueType(0);
8585
8586   // fold (ffloor c1) -> ffloor(c1)
8587   if (isConstantFPBuildVectorOrConstantFP(N0))
8588     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8589
8590   return SDValue();
8591 }
8592
8593 // FIXME: FNEG and FABS have a lot in common; refactor.
8594 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8595   SDValue N0 = N->getOperand(0);
8596   EVT VT = N->getValueType(0);
8597
8598   // Constant fold FNEG.
8599   if (isConstantFPBuildVectorOrConstantFP(N0))
8600     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8601
8602   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8603                          &DAG.getTarget().Options))
8604     return GetNegatedExpression(N0, DAG, LegalOperations);
8605
8606   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8607   // constant pool values.
8608   if (!TLI.isFNegFree(VT) &&
8609       N0.getOpcode() == ISD::BITCAST &&
8610       N0.getNode()->hasOneUse()) {
8611     SDValue Int = N0.getOperand(0);
8612     EVT IntVT = Int.getValueType();
8613     if (IntVT.isInteger() && !IntVT.isVector()) {
8614       APInt SignMask;
8615       if (N0.getValueType().isVector()) {
8616         // For a vector, get a mask such as 0x80... per scalar element
8617         // and splat it.
8618         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8619         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8620       } else {
8621         // For a scalar, just generate 0x80...
8622         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8623       }
8624       SDLoc DL0(N0);
8625       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8626                         DAG.getConstant(SignMask, DL0, IntVT));
8627       AddToWorklist(Int.getNode());
8628       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8629     }
8630   }
8631
8632   // (fneg (fmul c, x)) -> (fmul -c, x)
8633   if (N0.getOpcode() == ISD::FMUL) {
8634     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8635     if (CFP1) {
8636       APFloat CVal = CFP1->getValueAPF();
8637       CVal.changeSign();
8638       if (Level >= AfterLegalizeDAG &&
8639           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8640            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8641         return DAG.getNode(
8642             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8643             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8644     }
8645   }
8646
8647   return SDValue();
8648 }
8649
8650 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8651   SDValue N0 = N->getOperand(0);
8652   SDValue N1 = N->getOperand(1);
8653   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8654   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8655
8656   if (N0CFP && N1CFP) {
8657     const APFloat &C0 = N0CFP->getValueAPF();
8658     const APFloat &C1 = N1CFP->getValueAPF();
8659     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8660   }
8661
8662   if (N0CFP) {
8663     EVT VT = N->getValueType(0);
8664     // Canonicalize to constant on RHS.
8665     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8666   }
8667
8668   return SDValue();
8669 }
8670
8671 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8672   SDValue N0 = N->getOperand(0);
8673   SDValue N1 = N->getOperand(1);
8674   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8675   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8676
8677   if (N0CFP && N1CFP) {
8678     const APFloat &C0 = N0CFP->getValueAPF();
8679     const APFloat &C1 = N1CFP->getValueAPF();
8680     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8681   }
8682
8683   if (N0CFP) {
8684     EVT VT = N->getValueType(0);
8685     // Canonicalize to constant on RHS.
8686     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8687   }
8688
8689   return SDValue();
8690 }
8691
8692 SDValue DAGCombiner::visitFABS(SDNode *N) {
8693   SDValue N0 = N->getOperand(0);
8694   EVT VT = N->getValueType(0);
8695
8696   // fold (fabs c1) -> fabs(c1)
8697   if (isConstantFPBuildVectorOrConstantFP(N0))
8698     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8699
8700   // fold (fabs (fabs x)) -> (fabs x)
8701   if (N0.getOpcode() == ISD::FABS)
8702     return N->getOperand(0);
8703
8704   // fold (fabs (fneg x)) -> (fabs x)
8705   // fold (fabs (fcopysign x, y)) -> (fabs x)
8706   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8707     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8708
8709   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8710   // constant pool values.
8711   if (!TLI.isFAbsFree(VT) &&
8712       N0.getOpcode() == ISD::BITCAST &&
8713       N0.getNode()->hasOneUse()) {
8714     SDValue Int = N0.getOperand(0);
8715     EVT IntVT = Int.getValueType();
8716     if (IntVT.isInteger() && !IntVT.isVector()) {
8717       APInt SignMask;
8718       if (N0.getValueType().isVector()) {
8719         // For a vector, get a mask such as 0x7f... per scalar element
8720         // and splat it.
8721         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8722         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8723       } else {
8724         // For a scalar, just generate 0x7f...
8725         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8726       }
8727       SDLoc DL(N0);
8728       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8729                         DAG.getConstant(SignMask, DL, IntVT));
8730       AddToWorklist(Int.getNode());
8731       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8732     }
8733   }
8734
8735   return SDValue();
8736 }
8737
8738 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8739   SDValue Chain = N->getOperand(0);
8740   SDValue N1 = N->getOperand(1);
8741   SDValue N2 = N->getOperand(2);
8742
8743   // If N is a constant we could fold this into a fallthrough or unconditional
8744   // branch. However that doesn't happen very often in normal code, because
8745   // Instcombine/SimplifyCFG should have handled the available opportunities.
8746   // If we did this folding here, it would be necessary to update the
8747   // MachineBasicBlock CFG, which is awkward.
8748
8749   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8750   // on the target.
8751   if (N1.getOpcode() == ISD::SETCC &&
8752       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8753                                    N1.getOperand(0).getValueType())) {
8754     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8755                        Chain, N1.getOperand(2),
8756                        N1.getOperand(0), N1.getOperand(1), N2);
8757   }
8758
8759   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8760       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8761        (N1.getOperand(0).hasOneUse() &&
8762         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8763     SDNode *Trunc = nullptr;
8764     if (N1.getOpcode() == ISD::TRUNCATE) {
8765       // Look pass the truncate.
8766       Trunc = N1.getNode();
8767       N1 = N1.getOperand(0);
8768     }
8769
8770     // Match this pattern so that we can generate simpler code:
8771     //
8772     //   %a = ...
8773     //   %b = and i32 %a, 2
8774     //   %c = srl i32 %b, 1
8775     //   brcond i32 %c ...
8776     //
8777     // into
8778     //
8779     //   %a = ...
8780     //   %b = and i32 %a, 2
8781     //   %c = setcc eq %b, 0
8782     //   brcond %c ...
8783     //
8784     // This applies only when the AND constant value has one bit set and the
8785     // SRL constant is equal to the log2 of the AND constant. The back-end is
8786     // smart enough to convert the result into a TEST/JMP sequence.
8787     SDValue Op0 = N1.getOperand(0);
8788     SDValue Op1 = N1.getOperand(1);
8789
8790     if (Op0.getOpcode() == ISD::AND &&
8791         Op1.getOpcode() == ISD::Constant) {
8792       SDValue AndOp1 = Op0.getOperand(1);
8793
8794       if (AndOp1.getOpcode() == ISD::Constant) {
8795         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8796
8797         if (AndConst.isPowerOf2() &&
8798             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8799           SDLoc DL(N);
8800           SDValue SetCC =
8801             DAG.getSetCC(DL,
8802                          getSetCCResultType(Op0.getValueType()),
8803                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8804                          ISD::SETNE);
8805
8806           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8807                                           MVT::Other, Chain, SetCC, N2);
8808           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8809           // will convert it back to (X & C1) >> C2.
8810           CombineTo(N, NewBRCond, false);
8811           // Truncate is dead.
8812           if (Trunc)
8813             deleteAndRecombine(Trunc);
8814           // Replace the uses of SRL with SETCC
8815           WorklistRemover DeadNodes(*this);
8816           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8817           deleteAndRecombine(N1.getNode());
8818           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8819         }
8820       }
8821     }
8822
8823     if (Trunc)
8824       // Restore N1 if the above transformation doesn't match.
8825       N1 = N->getOperand(1);
8826   }
8827
8828   // Transform br(xor(x, y)) -> br(x != y)
8829   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8830   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8831     SDNode *TheXor = N1.getNode();
8832     SDValue Op0 = TheXor->getOperand(0);
8833     SDValue Op1 = TheXor->getOperand(1);
8834     if (Op0.getOpcode() == Op1.getOpcode()) {
8835       // Avoid missing important xor optimizations.
8836       SDValue Tmp = visitXOR(TheXor);
8837       if (Tmp.getNode()) {
8838         if (Tmp.getNode() != TheXor) {
8839           DEBUG(dbgs() << "\nReplacing.8 ";
8840                 TheXor->dump(&DAG);
8841                 dbgs() << "\nWith: ";
8842                 Tmp.getNode()->dump(&DAG);
8843                 dbgs() << '\n');
8844           WorklistRemover DeadNodes(*this);
8845           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8846           deleteAndRecombine(TheXor);
8847           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8848                              MVT::Other, Chain, Tmp, N2);
8849         }
8850
8851         // visitXOR has changed XOR's operands or replaced the XOR completely,
8852         // bail out.
8853         return SDValue(N, 0);
8854       }
8855     }
8856
8857     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8858       bool Equal = false;
8859       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8860         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8861             Op0.getOpcode() == ISD::XOR) {
8862           TheXor = Op0.getNode();
8863           Equal = true;
8864         }
8865
8866       EVT SetCCVT = N1.getValueType();
8867       if (LegalTypes)
8868         SetCCVT = getSetCCResultType(SetCCVT);
8869       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8870                                    SetCCVT,
8871                                    Op0, Op1,
8872                                    Equal ? ISD::SETEQ : ISD::SETNE);
8873       // Replace the uses of XOR with SETCC
8874       WorklistRemover DeadNodes(*this);
8875       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8876       deleteAndRecombine(N1.getNode());
8877       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8878                          MVT::Other, Chain, SetCC, N2);
8879     }
8880   }
8881
8882   return SDValue();
8883 }
8884
8885 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8886 //
8887 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8888   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8889   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8890
8891   // If N is a constant we could fold this into a fallthrough or unconditional
8892   // branch. However that doesn't happen very often in normal code, because
8893   // Instcombine/SimplifyCFG should have handled the available opportunities.
8894   // If we did this folding here, it would be necessary to update the
8895   // MachineBasicBlock CFG, which is awkward.
8896
8897   // Use SimplifySetCC to simplify SETCC's.
8898   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8899                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8900                                false);
8901   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8902
8903   // fold to a simpler setcc
8904   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8905     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8906                        N->getOperand(0), Simp.getOperand(2),
8907                        Simp.getOperand(0), Simp.getOperand(1),
8908                        N->getOperand(4));
8909
8910   return SDValue();
8911 }
8912
8913 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8914 /// and that N may be folded in the load / store addressing mode.
8915 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8916                                     SelectionDAG &DAG,
8917                                     const TargetLowering &TLI) {
8918   EVT VT;
8919   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8920     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8921       return false;
8922     VT = LD->getMemoryVT();
8923   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8924     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8925       return false;
8926     VT = ST->getMemoryVT();
8927   } else
8928     return false;
8929
8930   TargetLowering::AddrMode AM;
8931   if (N->getOpcode() == ISD::ADD) {
8932     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8933     if (Offset)
8934       // [reg +/- imm]
8935       AM.BaseOffs = Offset->getSExtValue();
8936     else
8937       // [reg +/- reg]
8938       AM.Scale = 1;
8939   } else if (N->getOpcode() == ISD::SUB) {
8940     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8941     if (Offset)
8942       // [reg +/- imm]
8943       AM.BaseOffs = -Offset->getSExtValue();
8944     else
8945       // [reg +/- reg]
8946       AM.Scale = 1;
8947   } else
8948     return false;
8949
8950   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8951 }
8952
8953 /// Try turning a load/store into a pre-indexed load/store when the base
8954 /// pointer is an add or subtract and it has other uses besides the load/store.
8955 /// After the transformation, the new indexed load/store has effectively folded
8956 /// the add/subtract in and all of its other uses are redirected to the
8957 /// new load/store.
8958 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8959   if (Level < AfterLegalizeDAG)
8960     return false;
8961
8962   bool isLoad = true;
8963   SDValue Ptr;
8964   EVT VT;
8965   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8966     if (LD->isIndexed())
8967       return false;
8968     VT = LD->getMemoryVT();
8969     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8970         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8971       return false;
8972     Ptr = LD->getBasePtr();
8973   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8974     if (ST->isIndexed())
8975       return false;
8976     VT = ST->getMemoryVT();
8977     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8978         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8979       return false;
8980     Ptr = ST->getBasePtr();
8981     isLoad = false;
8982   } else {
8983     return false;
8984   }
8985
8986   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8987   // out.  There is no reason to make this a preinc/predec.
8988   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8989       Ptr.getNode()->hasOneUse())
8990     return false;
8991
8992   // Ask the target to do addressing mode selection.
8993   SDValue BasePtr;
8994   SDValue Offset;
8995   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8996   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8997     return false;
8998
8999   // Backends without true r+i pre-indexed forms may need to pass a
9000   // constant base with a variable offset so that constant coercion
9001   // will work with the patterns in canonical form.
9002   bool Swapped = false;
9003   if (isa<ConstantSDNode>(BasePtr)) {
9004     std::swap(BasePtr, Offset);
9005     Swapped = true;
9006   }
9007
9008   // Don't create a indexed load / store with zero offset.
9009   if (isa<ConstantSDNode>(Offset) &&
9010       cast<ConstantSDNode>(Offset)->isNullValue())
9011     return false;
9012
9013   // Try turning it into a pre-indexed load / store except when:
9014   // 1) The new base ptr is a frame index.
9015   // 2) If N is a store and the new base ptr is either the same as or is a
9016   //    predecessor of the value being stored.
9017   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9018   //    that would create a cycle.
9019   // 4) All uses are load / store ops that use it as old base ptr.
9020
9021   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9022   // (plus the implicit offset) to a register to preinc anyway.
9023   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9024     return false;
9025
9026   // Check #2.
9027   if (!isLoad) {
9028     SDValue Val = cast<StoreSDNode>(N)->getValue();
9029     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9030       return false;
9031   }
9032
9033   // If the offset is a constant, there may be other adds of constants that
9034   // can be folded with this one. We should do this to avoid having to keep
9035   // a copy of the original base pointer.
9036   SmallVector<SDNode *, 16> OtherUses;
9037   if (isa<ConstantSDNode>(Offset))
9038     for (SDNode *Use : BasePtr.getNode()->uses()) {
9039       if (Use == Ptr.getNode())
9040         continue;
9041
9042       if (Use->isPredecessorOf(N))
9043         continue;
9044
9045       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
9046         OtherUses.clear();
9047         break;
9048       }
9049
9050       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
9051       if (Op1.getNode() == BasePtr.getNode())
9052         std::swap(Op0, Op1);
9053       assert(Op0.getNode() == BasePtr.getNode() &&
9054              "Use of ADD/SUB but not an operand");
9055
9056       if (!isa<ConstantSDNode>(Op1)) {
9057         OtherUses.clear();
9058         break;
9059       }
9060
9061       // FIXME: In some cases, we can be smarter about this.
9062       if (Op1.getValueType() != Offset.getValueType()) {
9063         OtherUses.clear();
9064         break;
9065       }
9066
9067       OtherUses.push_back(Use);
9068     }
9069
9070   if (Swapped)
9071     std::swap(BasePtr, Offset);
9072
9073   // Now check for #3 and #4.
9074   bool RealUse = false;
9075
9076   // Caches for hasPredecessorHelper
9077   SmallPtrSet<const SDNode *, 32> Visited;
9078   SmallVector<const SDNode *, 16> Worklist;
9079
9080   for (SDNode *Use : Ptr.getNode()->uses()) {
9081     if (Use == N)
9082       continue;
9083     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9084       return false;
9085
9086     // If Ptr may be folded in addressing mode of other use, then it's
9087     // not profitable to do this transformation.
9088     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9089       RealUse = true;
9090   }
9091
9092   if (!RealUse)
9093     return false;
9094
9095   SDValue Result;
9096   if (isLoad)
9097     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9098                                 BasePtr, Offset, AM);
9099   else
9100     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9101                                  BasePtr, Offset, AM);
9102   ++PreIndexedNodes;
9103   ++NodesCombined;
9104   DEBUG(dbgs() << "\nReplacing.4 ";
9105         N->dump(&DAG);
9106         dbgs() << "\nWith: ";
9107         Result.getNode()->dump(&DAG);
9108         dbgs() << '\n');
9109   WorklistRemover DeadNodes(*this);
9110   if (isLoad) {
9111     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9112     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9113   } else {
9114     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9115   }
9116
9117   // Finally, since the node is now dead, remove it from the graph.
9118   deleteAndRecombine(N);
9119
9120   if (Swapped)
9121     std::swap(BasePtr, Offset);
9122
9123   // Replace other uses of BasePtr that can be updated to use Ptr
9124   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9125     unsigned OffsetIdx = 1;
9126     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9127       OffsetIdx = 0;
9128     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9129            BasePtr.getNode() && "Expected BasePtr operand");
9130
9131     // We need to replace ptr0 in the following expression:
9132     //   x0 * offset0 + y0 * ptr0 = t0
9133     // knowing that
9134     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9135     //
9136     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9137     // indexed load/store and the expresion that needs to be re-written.
9138     //
9139     // Therefore, we have:
9140     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9141
9142     ConstantSDNode *CN =
9143       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9144     int X0, X1, Y0, Y1;
9145     APInt Offset0 = CN->getAPIntValue();
9146     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9147
9148     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9149     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9150     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9151     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9152
9153     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9154
9155     APInt CNV = Offset0;
9156     if (X0 < 0) CNV = -CNV;
9157     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9158     else CNV = CNV - Offset1;
9159
9160     SDLoc DL(OtherUses[i]);
9161
9162     // We can now generate the new expression.
9163     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9164     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9165
9166     SDValue NewUse = DAG.getNode(Opcode,
9167                                  DL,
9168                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9169     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9170     deleteAndRecombine(OtherUses[i]);
9171   }
9172
9173   // Replace the uses of Ptr with uses of the updated base value.
9174   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9175   deleteAndRecombine(Ptr.getNode());
9176
9177   return true;
9178 }
9179
9180 /// Try to combine a load/store with a add/sub of the base pointer node into a
9181 /// post-indexed load/store. The transformation folded the add/subtract into the
9182 /// new indexed load/store effectively and all of its uses are redirected to the
9183 /// new load/store.
9184 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9185   if (Level < AfterLegalizeDAG)
9186     return false;
9187
9188   bool isLoad = true;
9189   SDValue Ptr;
9190   EVT VT;
9191   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9192     if (LD->isIndexed())
9193       return false;
9194     VT = LD->getMemoryVT();
9195     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9196         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9197       return false;
9198     Ptr = LD->getBasePtr();
9199   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9200     if (ST->isIndexed())
9201       return false;
9202     VT = ST->getMemoryVT();
9203     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9204         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9205       return false;
9206     Ptr = ST->getBasePtr();
9207     isLoad = false;
9208   } else {
9209     return false;
9210   }
9211
9212   if (Ptr.getNode()->hasOneUse())
9213     return false;
9214
9215   for (SDNode *Op : Ptr.getNode()->uses()) {
9216     if (Op == N ||
9217         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9218       continue;
9219
9220     SDValue BasePtr;
9221     SDValue Offset;
9222     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9223     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9224       // Don't create a indexed load / store with zero offset.
9225       if (isa<ConstantSDNode>(Offset) &&
9226           cast<ConstantSDNode>(Offset)->isNullValue())
9227         continue;
9228
9229       // Try turning it into a post-indexed load / store except when
9230       // 1) All uses are load / store ops that use it as base ptr (and
9231       //    it may be folded as addressing mmode).
9232       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9233       //    nor a successor of N. Otherwise, if Op is folded that would
9234       //    create a cycle.
9235
9236       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9237         continue;
9238
9239       // Check for #1.
9240       bool TryNext = false;
9241       for (SDNode *Use : BasePtr.getNode()->uses()) {
9242         if (Use == Ptr.getNode())
9243           continue;
9244
9245         // If all the uses are load / store addresses, then don't do the
9246         // transformation.
9247         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9248           bool RealUse = false;
9249           for (SDNode *UseUse : Use->uses()) {
9250             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9251               RealUse = true;
9252           }
9253
9254           if (!RealUse) {
9255             TryNext = true;
9256             break;
9257           }
9258         }
9259       }
9260
9261       if (TryNext)
9262         continue;
9263
9264       // Check for #2
9265       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9266         SDValue Result = isLoad
9267           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9268                                BasePtr, Offset, AM)
9269           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9270                                 BasePtr, Offset, AM);
9271         ++PostIndexedNodes;
9272         ++NodesCombined;
9273         DEBUG(dbgs() << "\nReplacing.5 ";
9274               N->dump(&DAG);
9275               dbgs() << "\nWith: ";
9276               Result.getNode()->dump(&DAG);
9277               dbgs() << '\n');
9278         WorklistRemover DeadNodes(*this);
9279         if (isLoad) {
9280           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9281           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9282         } else {
9283           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9284         }
9285
9286         // Finally, since the node is now dead, remove it from the graph.
9287         deleteAndRecombine(N);
9288
9289         // Replace the uses of Use with uses of the updated base value.
9290         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9291                                       Result.getValue(isLoad ? 1 : 0));
9292         deleteAndRecombine(Op);
9293         return true;
9294       }
9295     }
9296   }
9297
9298   return false;
9299 }
9300
9301 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9302 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9303   ISD::MemIndexedMode AM = LD->getAddressingMode();
9304   assert(AM != ISD::UNINDEXED);
9305   SDValue BP = LD->getOperand(1);
9306   SDValue Inc = LD->getOperand(2);
9307
9308   // Some backends use TargetConstants for load offsets, but don't expect
9309   // TargetConstants in general ADD nodes. We can convert these constants into
9310   // regular Constants (if the constant is not opaque).
9311   assert((Inc.getOpcode() != ISD::TargetConstant ||
9312           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9313          "Cannot split out indexing using opaque target constants");
9314   if (Inc.getOpcode() == ISD::TargetConstant) {
9315     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9316     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9317                           ConstInc->getValueType(0));
9318   }
9319
9320   unsigned Opc =
9321       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9322   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9323 }
9324
9325 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9326   LoadSDNode *LD  = cast<LoadSDNode>(N);
9327   SDValue Chain = LD->getChain();
9328   SDValue Ptr   = LD->getBasePtr();
9329
9330   // If load is not volatile and there are no uses of the loaded value (and
9331   // the updated indexed value in case of indexed loads), change uses of the
9332   // chain value into uses of the chain input (i.e. delete the dead load).
9333   if (!LD->isVolatile()) {
9334     if (N->getValueType(1) == MVT::Other) {
9335       // Unindexed loads.
9336       if (!N->hasAnyUseOfValue(0)) {
9337         // It's not safe to use the two value CombineTo variant here. e.g.
9338         // v1, chain2 = load chain1, loc
9339         // v2, chain3 = load chain2, loc
9340         // v3         = add v2, c
9341         // Now we replace use of chain2 with chain1.  This makes the second load
9342         // isomorphic to the one we are deleting, and thus makes this load live.
9343         DEBUG(dbgs() << "\nReplacing.6 ";
9344               N->dump(&DAG);
9345               dbgs() << "\nWith chain: ";
9346               Chain.getNode()->dump(&DAG);
9347               dbgs() << "\n");
9348         WorklistRemover DeadNodes(*this);
9349         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9350
9351         if (N->use_empty())
9352           deleteAndRecombine(N);
9353
9354         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9355       }
9356     } else {
9357       // Indexed loads.
9358       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9359
9360       // If this load has an opaque TargetConstant offset, then we cannot split
9361       // the indexing into an add/sub directly (that TargetConstant may not be
9362       // valid for a different type of node, and we cannot convert an opaque
9363       // target constant into a regular constant).
9364       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9365                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9366
9367       if (!N->hasAnyUseOfValue(0) &&
9368           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9369         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9370         SDValue Index;
9371         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9372           Index = SplitIndexingFromLoad(LD);
9373           // Try to fold the base pointer arithmetic into subsequent loads and
9374           // stores.
9375           AddUsersToWorklist(N);
9376         } else
9377           Index = DAG.getUNDEF(N->getValueType(1));
9378         DEBUG(dbgs() << "\nReplacing.7 ";
9379               N->dump(&DAG);
9380               dbgs() << "\nWith: ";
9381               Undef.getNode()->dump(&DAG);
9382               dbgs() << " and 2 other values\n");
9383         WorklistRemover DeadNodes(*this);
9384         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9385         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9386         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9387         deleteAndRecombine(N);
9388         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9389       }
9390     }
9391   }
9392
9393   // If this load is directly stored, replace the load value with the stored
9394   // value.
9395   // TODO: Handle store large -> read small portion.
9396   // TODO: Handle TRUNCSTORE/LOADEXT
9397   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9398     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9399       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9400       if (PrevST->getBasePtr() == Ptr &&
9401           PrevST->getValue().getValueType() == N->getValueType(0))
9402       return CombineTo(N, Chain.getOperand(1), Chain);
9403     }
9404   }
9405
9406   // Try to infer better alignment information than the load already has.
9407   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9408     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9409       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9410         SDValue NewLoad =
9411                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9412                               LD->getValueType(0),
9413                               Chain, Ptr, LD->getPointerInfo(),
9414                               LD->getMemoryVT(),
9415                               LD->isVolatile(), LD->isNonTemporal(),
9416                               LD->isInvariant(), Align, LD->getAAInfo());
9417         if (NewLoad.getNode() != N)
9418           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9419       }
9420     }
9421   }
9422
9423   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9424                                                   : DAG.getSubtarget().useAA();
9425 #ifndef NDEBUG
9426   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9427       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9428     UseAA = false;
9429 #endif
9430   if (UseAA && LD->isUnindexed()) {
9431     // Walk up chain skipping non-aliasing memory nodes.
9432     SDValue BetterChain = FindBetterChain(N, Chain);
9433
9434     // If there is a better chain.
9435     if (Chain != BetterChain) {
9436       SDValue ReplLoad;
9437
9438       // Replace the chain to void dependency.
9439       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9440         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9441                                BetterChain, Ptr, LD->getMemOperand());
9442       } else {
9443         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9444                                   LD->getValueType(0),
9445                                   BetterChain, Ptr, LD->getMemoryVT(),
9446                                   LD->getMemOperand());
9447       }
9448
9449       // Create token factor to keep old chain connected.
9450       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9451                                   MVT::Other, Chain, ReplLoad.getValue(1));
9452
9453       // Make sure the new and old chains are cleaned up.
9454       AddToWorklist(Token.getNode());
9455
9456       // Replace uses with load result and token factor. Don't add users
9457       // to work list.
9458       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9459     }
9460   }
9461
9462   // Try transforming N to an indexed load.
9463   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9464     return SDValue(N, 0);
9465
9466   // Try to slice up N to more direct loads if the slices are mapped to
9467   // different register banks or pairing can take place.
9468   if (SliceUpLoad(N))
9469     return SDValue(N, 0);
9470
9471   return SDValue();
9472 }
9473
9474 namespace {
9475 /// \brief Helper structure used to slice a load in smaller loads.
9476 /// Basically a slice is obtained from the following sequence:
9477 /// Origin = load Ty1, Base
9478 /// Shift = srl Ty1 Origin, CstTy Amount
9479 /// Inst = trunc Shift to Ty2
9480 ///
9481 /// Then, it will be rewriten into:
9482 /// Slice = load SliceTy, Base + SliceOffset
9483 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9484 ///
9485 /// SliceTy is deduced from the number of bits that are actually used to
9486 /// build Inst.
9487 struct LoadedSlice {
9488   /// \brief Helper structure used to compute the cost of a slice.
9489   struct Cost {
9490     /// Are we optimizing for code size.
9491     bool ForCodeSize;
9492     /// Various cost.
9493     unsigned Loads;
9494     unsigned Truncates;
9495     unsigned CrossRegisterBanksCopies;
9496     unsigned ZExts;
9497     unsigned Shift;
9498
9499     Cost(bool ForCodeSize = false)
9500         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9501           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9502
9503     /// \brief Get the cost of one isolated slice.
9504     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9505         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9506           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9507       EVT TruncType = LS.Inst->getValueType(0);
9508       EVT LoadedType = LS.getLoadedType();
9509       if (TruncType != LoadedType &&
9510           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9511         ZExts = 1;
9512     }
9513
9514     /// \brief Account for slicing gain in the current cost.
9515     /// Slicing provide a few gains like removing a shift or a
9516     /// truncate. This method allows to grow the cost of the original
9517     /// load with the gain from this slice.
9518     void addSliceGain(const LoadedSlice &LS) {
9519       // Each slice saves a truncate.
9520       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9521       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9522                               LS.Inst->getOperand(0).getValueType()))
9523         ++Truncates;
9524       // If there is a shift amount, this slice gets rid of it.
9525       if (LS.Shift)
9526         ++Shift;
9527       // If this slice can merge a cross register bank copy, account for it.
9528       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9529         ++CrossRegisterBanksCopies;
9530     }
9531
9532     Cost &operator+=(const Cost &RHS) {
9533       Loads += RHS.Loads;
9534       Truncates += RHS.Truncates;
9535       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9536       ZExts += RHS.ZExts;
9537       Shift += RHS.Shift;
9538       return *this;
9539     }
9540
9541     bool operator==(const Cost &RHS) const {
9542       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9543              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9544              ZExts == RHS.ZExts && Shift == RHS.Shift;
9545     }
9546
9547     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9548
9549     bool operator<(const Cost &RHS) const {
9550       // Assume cross register banks copies are as expensive as loads.
9551       // FIXME: Do we want some more target hooks?
9552       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9553       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9554       // Unless we are optimizing for code size, consider the
9555       // expensive operation first.
9556       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9557         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9558       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9559              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9560     }
9561
9562     bool operator>(const Cost &RHS) const { return RHS < *this; }
9563
9564     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9565
9566     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9567   };
9568   // The last instruction that represent the slice. This should be a
9569   // truncate instruction.
9570   SDNode *Inst;
9571   // The original load instruction.
9572   LoadSDNode *Origin;
9573   // The right shift amount in bits from the original load.
9574   unsigned Shift;
9575   // The DAG from which Origin came from.
9576   // This is used to get some contextual information about legal types, etc.
9577   SelectionDAG *DAG;
9578
9579   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9580               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9581       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9582
9583   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9584   /// \return Result is \p BitWidth and has used bits set to 1 and
9585   ///         not used bits set to 0.
9586   APInt getUsedBits() const {
9587     // Reproduce the trunc(lshr) sequence:
9588     // - Start from the truncated value.
9589     // - Zero extend to the desired bit width.
9590     // - Shift left.
9591     assert(Origin && "No original load to compare against.");
9592     unsigned BitWidth = Origin->getValueSizeInBits(0);
9593     assert(Inst && "This slice is not bound to an instruction");
9594     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9595            "Extracted slice is bigger than the whole type!");
9596     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9597     UsedBits.setAllBits();
9598     UsedBits = UsedBits.zext(BitWidth);
9599     UsedBits <<= Shift;
9600     return UsedBits;
9601   }
9602
9603   /// \brief Get the size of the slice to be loaded in bytes.
9604   unsigned getLoadedSize() const {
9605     unsigned SliceSize = getUsedBits().countPopulation();
9606     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9607     return SliceSize / 8;
9608   }
9609
9610   /// \brief Get the type that will be loaded for this slice.
9611   /// Note: This may not be the final type for the slice.
9612   EVT getLoadedType() const {
9613     assert(DAG && "Missing context");
9614     LLVMContext &Ctxt = *DAG->getContext();
9615     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9616   }
9617
9618   /// \brief Get the alignment of the load used for this slice.
9619   unsigned getAlignment() const {
9620     unsigned Alignment = Origin->getAlignment();
9621     unsigned Offset = getOffsetFromBase();
9622     if (Offset != 0)
9623       Alignment = MinAlign(Alignment, Alignment + Offset);
9624     return Alignment;
9625   }
9626
9627   /// \brief Check if this slice can be rewritten with legal operations.
9628   bool isLegal() const {
9629     // An invalid slice is not legal.
9630     if (!Origin || !Inst || !DAG)
9631       return false;
9632
9633     // Offsets are for indexed load only, we do not handle that.
9634     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9635       return false;
9636
9637     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9638
9639     // Check that the type is legal.
9640     EVT SliceType = getLoadedType();
9641     if (!TLI.isTypeLegal(SliceType))
9642       return false;
9643
9644     // Check that the load is legal for this type.
9645     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9646       return false;
9647
9648     // Check that the offset can be computed.
9649     // 1. Check its type.
9650     EVT PtrType = Origin->getBasePtr().getValueType();
9651     if (PtrType == MVT::Untyped || PtrType.isExtended())
9652       return false;
9653
9654     // 2. Check that it fits in the immediate.
9655     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9656       return false;
9657
9658     // 3. Check that the computation is legal.
9659     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9660       return false;
9661
9662     // Check that the zext is legal if it needs one.
9663     EVT TruncateType = Inst->getValueType(0);
9664     if (TruncateType != SliceType &&
9665         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9666       return false;
9667
9668     return true;
9669   }
9670
9671   /// \brief Get the offset in bytes of this slice in the original chunk of
9672   /// bits.
9673   /// \pre DAG != nullptr.
9674   uint64_t getOffsetFromBase() const {
9675     assert(DAG && "Missing context.");
9676     bool IsBigEndian =
9677         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9678     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9679     uint64_t Offset = Shift / 8;
9680     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9681     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9682            "The size of the original loaded type is not a multiple of a"
9683            " byte.");
9684     // If Offset is bigger than TySizeInBytes, it means we are loading all
9685     // zeros. This should have been optimized before in the process.
9686     assert(TySizeInBytes > Offset &&
9687            "Invalid shift amount for given loaded size");
9688     if (IsBigEndian)
9689       Offset = TySizeInBytes - Offset - getLoadedSize();
9690     return Offset;
9691   }
9692
9693   /// \brief Generate the sequence of instructions to load the slice
9694   /// represented by this object and redirect the uses of this slice to
9695   /// this new sequence of instructions.
9696   /// \pre this->Inst && this->Origin are valid Instructions and this
9697   /// object passed the legal check: LoadedSlice::isLegal returned true.
9698   /// \return The last instruction of the sequence used to load the slice.
9699   SDValue loadSlice() const {
9700     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9701     const SDValue &OldBaseAddr = Origin->getBasePtr();
9702     SDValue BaseAddr = OldBaseAddr;
9703     // Get the offset in that chunk of bytes w.r.t. the endianess.
9704     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9705     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9706     if (Offset) {
9707       // BaseAddr = BaseAddr + Offset.
9708       EVT ArithType = BaseAddr.getValueType();
9709       SDLoc DL(Origin);
9710       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9711                               DAG->getConstant(Offset, DL, ArithType));
9712     }
9713
9714     // Create the type of the loaded slice according to its size.
9715     EVT SliceType = getLoadedType();
9716
9717     // Create the load for the slice.
9718     SDValue LastInst = DAG->getLoad(
9719         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9720         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9721         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9722     // If the final type is not the same as the loaded type, this means that
9723     // we have to pad with zero. Create a zero extend for that.
9724     EVT FinalType = Inst->getValueType(0);
9725     if (SliceType != FinalType)
9726       LastInst =
9727           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9728     return LastInst;
9729   }
9730
9731   /// \brief Check if this slice can be merged with an expensive cross register
9732   /// bank copy. E.g.,
9733   /// i = load i32
9734   /// f = bitcast i32 i to float
9735   bool canMergeExpensiveCrossRegisterBankCopy() const {
9736     if (!Inst || !Inst->hasOneUse())
9737       return false;
9738     SDNode *Use = *Inst->use_begin();
9739     if (Use->getOpcode() != ISD::BITCAST)
9740       return false;
9741     assert(DAG && "Missing context");
9742     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9743     EVT ResVT = Use->getValueType(0);
9744     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9745     const TargetRegisterClass *ArgRC =
9746         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9747     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9748       return false;
9749
9750     // At this point, we know that we perform a cross-register-bank copy.
9751     // Check if it is expensive.
9752     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9753     // Assume bitcasts are cheap, unless both register classes do not
9754     // explicitly share a common sub class.
9755     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9756       return false;
9757
9758     // Check if it will be merged with the load.
9759     // 1. Check the alignment constraint.
9760     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9761         ResVT.getTypeForEVT(*DAG->getContext()));
9762
9763     if (RequiredAlignment > getAlignment())
9764       return false;
9765
9766     // 2. Check that the load is a legal operation for that type.
9767     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9768       return false;
9769
9770     // 3. Check that we do not have a zext in the way.
9771     if (Inst->getValueType(0) != getLoadedType())
9772       return false;
9773
9774     return true;
9775   }
9776 };
9777 }
9778
9779 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9780 /// \p UsedBits looks like 0..0 1..1 0..0.
9781 static bool areUsedBitsDense(const APInt &UsedBits) {
9782   // If all the bits are one, this is dense!
9783   if (UsedBits.isAllOnesValue())
9784     return true;
9785
9786   // Get rid of the unused bits on the right.
9787   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9788   // Get rid of the unused bits on the left.
9789   if (NarrowedUsedBits.countLeadingZeros())
9790     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9791   // Check that the chunk of bits is completely used.
9792   return NarrowedUsedBits.isAllOnesValue();
9793 }
9794
9795 /// \brief Check whether or not \p First and \p Second are next to each other
9796 /// in memory. This means that there is no hole between the bits loaded
9797 /// by \p First and the bits loaded by \p Second.
9798 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9799                                      const LoadedSlice &Second) {
9800   assert(First.Origin == Second.Origin && First.Origin &&
9801          "Unable to match different memory origins.");
9802   APInt UsedBits = First.getUsedBits();
9803   assert((UsedBits & Second.getUsedBits()) == 0 &&
9804          "Slices are not supposed to overlap.");
9805   UsedBits |= Second.getUsedBits();
9806   return areUsedBitsDense(UsedBits);
9807 }
9808
9809 /// \brief Adjust the \p GlobalLSCost according to the target
9810 /// paring capabilities and the layout of the slices.
9811 /// \pre \p GlobalLSCost should account for at least as many loads as
9812 /// there is in the slices in \p LoadedSlices.
9813 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9814                                  LoadedSlice::Cost &GlobalLSCost) {
9815   unsigned NumberOfSlices = LoadedSlices.size();
9816   // If there is less than 2 elements, no pairing is possible.
9817   if (NumberOfSlices < 2)
9818     return;
9819
9820   // Sort the slices so that elements that are likely to be next to each
9821   // other in memory are next to each other in the list.
9822   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9823             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9824     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9825     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9826   });
9827   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9828   // First (resp. Second) is the first (resp. Second) potentially candidate
9829   // to be placed in a paired load.
9830   const LoadedSlice *First = nullptr;
9831   const LoadedSlice *Second = nullptr;
9832   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9833                 // Set the beginning of the pair.
9834                                                            First = Second) {
9835
9836     Second = &LoadedSlices[CurrSlice];
9837
9838     // If First is NULL, it means we start a new pair.
9839     // Get to the next slice.
9840     if (!First)
9841       continue;
9842
9843     EVT LoadedType = First->getLoadedType();
9844
9845     // If the types of the slices are different, we cannot pair them.
9846     if (LoadedType != Second->getLoadedType())
9847       continue;
9848
9849     // Check if the target supplies paired loads for this type.
9850     unsigned RequiredAlignment = 0;
9851     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9852       // move to the next pair, this type is hopeless.
9853       Second = nullptr;
9854       continue;
9855     }
9856     // Check if we meet the alignment requirement.
9857     if (RequiredAlignment > First->getAlignment())
9858       continue;
9859
9860     // Check that both loads are next to each other in memory.
9861     if (!areSlicesNextToEachOther(*First, *Second))
9862       continue;
9863
9864     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9865     --GlobalLSCost.Loads;
9866     // Move to the next pair.
9867     Second = nullptr;
9868   }
9869 }
9870
9871 /// \brief Check the profitability of all involved LoadedSlice.
9872 /// Currently, it is considered profitable if there is exactly two
9873 /// involved slices (1) which are (2) next to each other in memory, and
9874 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9875 ///
9876 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9877 /// the elements themselves.
9878 ///
9879 /// FIXME: When the cost model will be mature enough, we can relax
9880 /// constraints (1) and (2).
9881 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9882                                 const APInt &UsedBits, bool ForCodeSize) {
9883   unsigned NumberOfSlices = LoadedSlices.size();
9884   if (StressLoadSlicing)
9885     return NumberOfSlices > 1;
9886
9887   // Check (1).
9888   if (NumberOfSlices != 2)
9889     return false;
9890
9891   // Check (2).
9892   if (!areUsedBitsDense(UsedBits))
9893     return false;
9894
9895   // Check (3).
9896   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9897   // The original code has one big load.
9898   OrigCost.Loads = 1;
9899   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9900     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9901     // Accumulate the cost of all the slices.
9902     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9903     GlobalSlicingCost += SliceCost;
9904
9905     // Account as cost in the original configuration the gain obtained
9906     // with the current slices.
9907     OrigCost.addSliceGain(LS);
9908   }
9909
9910   // If the target supports paired load, adjust the cost accordingly.
9911   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9912   return OrigCost > GlobalSlicingCost;
9913 }
9914
9915 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9916 /// operations, split it in the various pieces being extracted.
9917 ///
9918 /// This sort of thing is introduced by SROA.
9919 /// This slicing takes care not to insert overlapping loads.
9920 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9921 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9922   if (Level < AfterLegalizeDAG)
9923     return false;
9924
9925   LoadSDNode *LD = cast<LoadSDNode>(N);
9926   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9927       !LD->getValueType(0).isInteger())
9928     return false;
9929
9930   // Keep track of already used bits to detect overlapping values.
9931   // In that case, we will just abort the transformation.
9932   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9933
9934   SmallVector<LoadedSlice, 4> LoadedSlices;
9935
9936   // Check if this load is used as several smaller chunks of bits.
9937   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9938   // of computation for each trunc.
9939   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9940        UI != UIEnd; ++UI) {
9941     // Skip the uses of the chain.
9942     if (UI.getUse().getResNo() != 0)
9943       continue;
9944
9945     SDNode *User = *UI;
9946     unsigned Shift = 0;
9947
9948     // Check if this is a trunc(lshr).
9949     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9950         isa<ConstantSDNode>(User->getOperand(1))) {
9951       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9952       User = *User->use_begin();
9953     }
9954
9955     // At this point, User is a Truncate, iff we encountered, trunc or
9956     // trunc(lshr).
9957     if (User->getOpcode() != ISD::TRUNCATE)
9958       return false;
9959
9960     // The width of the type must be a power of 2 and greater than 8-bits.
9961     // Otherwise the load cannot be represented in LLVM IR.
9962     // Moreover, if we shifted with a non-8-bits multiple, the slice
9963     // will be across several bytes. We do not support that.
9964     unsigned Width = User->getValueSizeInBits(0);
9965     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9966       return 0;
9967
9968     // Build the slice for this chain of computations.
9969     LoadedSlice LS(User, LD, Shift, &DAG);
9970     APInt CurrentUsedBits = LS.getUsedBits();
9971
9972     // Check if this slice overlaps with another.
9973     if ((CurrentUsedBits & UsedBits) != 0)
9974       return false;
9975     // Update the bits used globally.
9976     UsedBits |= CurrentUsedBits;
9977
9978     // Check if the new slice would be legal.
9979     if (!LS.isLegal())
9980       return false;
9981
9982     // Record the slice.
9983     LoadedSlices.push_back(LS);
9984   }
9985
9986   // Abort slicing if it does not seem to be profitable.
9987   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9988     return false;
9989
9990   ++SlicedLoads;
9991
9992   // Rewrite each chain to use an independent load.
9993   // By construction, each chain can be represented by a unique load.
9994
9995   // Prepare the argument for the new token factor for all the slices.
9996   SmallVector<SDValue, 8> ArgChains;
9997   for (SmallVectorImpl<LoadedSlice>::const_iterator
9998            LSIt = LoadedSlices.begin(),
9999            LSItEnd = LoadedSlices.end();
10000        LSIt != LSItEnd; ++LSIt) {
10001     SDValue SliceInst = LSIt->loadSlice();
10002     CombineTo(LSIt->Inst, SliceInst, true);
10003     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10004       SliceInst = SliceInst.getOperand(0);
10005     assert(SliceInst->getOpcode() == ISD::LOAD &&
10006            "It takes more than a zext to get to the loaded slice!!");
10007     ArgChains.push_back(SliceInst.getValue(1));
10008   }
10009
10010   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10011                               ArgChains);
10012   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10013   return true;
10014 }
10015
10016 /// Check to see if V is (and load (ptr), imm), where the load is having
10017 /// specific bytes cleared out.  If so, return the byte size being masked out
10018 /// and the shift amount.
10019 static std::pair<unsigned, unsigned>
10020 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10021   std::pair<unsigned, unsigned> Result(0, 0);
10022
10023   // Check for the structure we're looking for.
10024   if (V->getOpcode() != ISD::AND ||
10025       !isa<ConstantSDNode>(V->getOperand(1)) ||
10026       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10027     return Result;
10028
10029   // Check the chain and pointer.
10030   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10031   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10032
10033   // The store should be chained directly to the load or be an operand of a
10034   // tokenfactor.
10035   if (LD == Chain.getNode())
10036     ; // ok.
10037   else if (Chain->getOpcode() != ISD::TokenFactor)
10038     return Result; // Fail.
10039   else {
10040     bool isOk = false;
10041     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10042       if (Chain->getOperand(i).getNode() == LD) {
10043         isOk = true;
10044         break;
10045       }
10046     if (!isOk) return Result;
10047   }
10048
10049   // This only handles simple types.
10050   if (V.getValueType() != MVT::i16 &&
10051       V.getValueType() != MVT::i32 &&
10052       V.getValueType() != MVT::i64)
10053     return Result;
10054
10055   // Check the constant mask.  Invert it so that the bits being masked out are
10056   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10057   // follow the sign bit for uniformity.
10058   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10059   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10060   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10061   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10062   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10063   if (NotMaskLZ == 64) return Result;  // All zero mask.
10064
10065   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10066   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10067     return Result;
10068
10069   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10070   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10071     NotMaskLZ -= 64-V.getValueSizeInBits();
10072
10073   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10074   switch (MaskedBytes) {
10075   case 1:
10076   case 2:
10077   case 4: break;
10078   default: return Result; // All one mask, or 5-byte mask.
10079   }
10080
10081   // Verify that the first bit starts at a multiple of mask so that the access
10082   // is aligned the same as the access width.
10083   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10084
10085   Result.first = MaskedBytes;
10086   Result.second = NotMaskTZ/8;
10087   return Result;
10088 }
10089
10090
10091 /// Check to see if IVal is something that provides a value as specified by
10092 /// MaskInfo. If so, replace the specified store with a narrower store of
10093 /// truncated IVal.
10094 static SDNode *
10095 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10096                                 SDValue IVal, StoreSDNode *St,
10097                                 DAGCombiner *DC) {
10098   unsigned NumBytes = MaskInfo.first;
10099   unsigned ByteShift = MaskInfo.second;
10100   SelectionDAG &DAG = DC->getDAG();
10101
10102   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10103   // that uses this.  If not, this is not a replacement.
10104   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10105                                   ByteShift*8, (ByteShift+NumBytes)*8);
10106   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10107
10108   // Check that it is legal on the target to do this.  It is legal if the new
10109   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10110   // legalization.
10111   MVT VT = MVT::getIntegerVT(NumBytes*8);
10112   if (!DC->isTypeLegal(VT))
10113     return nullptr;
10114
10115   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10116   // shifted by ByteShift and truncated down to NumBytes.
10117   if (ByteShift) {
10118     SDLoc DL(IVal);
10119     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10120                        DAG.getConstant(ByteShift*8, DL,
10121                                     DC->getShiftAmountTy(IVal.getValueType())));
10122   }
10123
10124   // Figure out the offset for the store and the alignment of the access.
10125   unsigned StOffset;
10126   unsigned NewAlign = St->getAlignment();
10127
10128   if (DAG.getTargetLoweringInfo().isLittleEndian())
10129     StOffset = ByteShift;
10130   else
10131     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10132
10133   SDValue Ptr = St->getBasePtr();
10134   if (StOffset) {
10135     SDLoc DL(IVal);
10136     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10137                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10138     NewAlign = MinAlign(NewAlign, StOffset);
10139   }
10140
10141   // Truncate down to the new size.
10142   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10143
10144   ++OpsNarrowed;
10145   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10146                       St->getPointerInfo().getWithOffset(StOffset),
10147                       false, false, NewAlign).getNode();
10148 }
10149
10150
10151 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10152 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10153 /// narrowing the load and store if it would end up being a win for performance
10154 /// or code size.
10155 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10156   StoreSDNode *ST  = cast<StoreSDNode>(N);
10157   if (ST->isVolatile())
10158     return SDValue();
10159
10160   SDValue Chain = ST->getChain();
10161   SDValue Value = ST->getValue();
10162   SDValue Ptr   = ST->getBasePtr();
10163   EVT VT = Value.getValueType();
10164
10165   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10166     return SDValue();
10167
10168   unsigned Opc = Value.getOpcode();
10169
10170   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10171   // is a byte mask indicating a consecutive number of bytes, check to see if
10172   // Y is known to provide just those bytes.  If so, we try to replace the
10173   // load + replace + store sequence with a single (narrower) store, which makes
10174   // the load dead.
10175   if (Opc == ISD::OR) {
10176     std::pair<unsigned, unsigned> MaskedLoad;
10177     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10178     if (MaskedLoad.first)
10179       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10180                                                   Value.getOperand(1), ST,this))
10181         return SDValue(NewST, 0);
10182
10183     // Or is commutative, so try swapping X and Y.
10184     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10185     if (MaskedLoad.first)
10186       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10187                                                   Value.getOperand(0), ST,this))
10188         return SDValue(NewST, 0);
10189   }
10190
10191   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10192       Value.getOperand(1).getOpcode() != ISD::Constant)
10193     return SDValue();
10194
10195   SDValue N0 = Value.getOperand(0);
10196   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10197       Chain == SDValue(N0.getNode(), 1)) {
10198     LoadSDNode *LD = cast<LoadSDNode>(N0);
10199     if (LD->getBasePtr() != Ptr ||
10200         LD->getPointerInfo().getAddrSpace() !=
10201         ST->getPointerInfo().getAddrSpace())
10202       return SDValue();
10203
10204     // Find the type to narrow it the load / op / store to.
10205     SDValue N1 = Value.getOperand(1);
10206     unsigned BitWidth = N1.getValueSizeInBits();
10207     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10208     if (Opc == ISD::AND)
10209       Imm ^= APInt::getAllOnesValue(BitWidth);
10210     if (Imm == 0 || Imm.isAllOnesValue())
10211       return SDValue();
10212     unsigned ShAmt = Imm.countTrailingZeros();
10213     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10214     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10215     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10216     // The narrowing should be profitable, the load/store operation should be
10217     // legal (or custom) and the store size should be equal to the NewVT width.
10218     while (NewBW < BitWidth &&
10219            (NewVT.getStoreSizeInBits() != NewBW ||
10220             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10221             !TLI.isNarrowingProfitable(VT, NewVT))) {
10222       NewBW = NextPowerOf2(NewBW);
10223       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10224     }
10225     if (NewBW >= BitWidth)
10226       return SDValue();
10227
10228     // If the lsb changed does not start at the type bitwidth boundary,
10229     // start at the previous one.
10230     if (ShAmt % NewBW)
10231       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10232     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10233                                    std::min(BitWidth, ShAmt + NewBW));
10234     if ((Imm & Mask) == Imm) {
10235       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10236       if (Opc == ISD::AND)
10237         NewImm ^= APInt::getAllOnesValue(NewBW);
10238       uint64_t PtrOff = ShAmt / 8;
10239       // For big endian targets, we need to adjust the offset to the pointer to
10240       // load the correct bytes.
10241       if (TLI.isBigEndian())
10242         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10243
10244       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10245       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10246       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10247         return SDValue();
10248
10249       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10250                                    Ptr.getValueType(), Ptr,
10251                                    DAG.getConstant(PtrOff, SDLoc(LD),
10252                                                    Ptr.getValueType()));
10253       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10254                                   LD->getChain(), NewPtr,
10255                                   LD->getPointerInfo().getWithOffset(PtrOff),
10256                                   LD->isVolatile(), LD->isNonTemporal(),
10257                                   LD->isInvariant(), NewAlign,
10258                                   LD->getAAInfo());
10259       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10260                                    DAG.getConstant(NewImm, SDLoc(Value),
10261                                                    NewVT));
10262       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10263                                    NewVal, NewPtr,
10264                                    ST->getPointerInfo().getWithOffset(PtrOff),
10265                                    false, false, NewAlign);
10266
10267       AddToWorklist(NewPtr.getNode());
10268       AddToWorklist(NewLD.getNode());
10269       AddToWorklist(NewVal.getNode());
10270       WorklistRemover DeadNodes(*this);
10271       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10272       ++OpsNarrowed;
10273       return NewST;
10274     }
10275   }
10276
10277   return SDValue();
10278 }
10279
10280 /// For a given floating point load / store pair, if the load value isn't used
10281 /// by any other operations, then consider transforming the pair to integer
10282 /// load / store operations if the target deems the transformation profitable.
10283 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10284   StoreSDNode *ST  = cast<StoreSDNode>(N);
10285   SDValue Chain = ST->getChain();
10286   SDValue Value = ST->getValue();
10287   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10288       Value.hasOneUse() &&
10289       Chain == SDValue(Value.getNode(), 1)) {
10290     LoadSDNode *LD = cast<LoadSDNode>(Value);
10291     EVT VT = LD->getMemoryVT();
10292     if (!VT.isFloatingPoint() ||
10293         VT != ST->getMemoryVT() ||
10294         LD->isNonTemporal() ||
10295         ST->isNonTemporal() ||
10296         LD->getPointerInfo().getAddrSpace() != 0 ||
10297         ST->getPointerInfo().getAddrSpace() != 0)
10298       return SDValue();
10299
10300     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10301     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10302         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10303         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10304         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10305       return SDValue();
10306
10307     unsigned LDAlign = LD->getAlignment();
10308     unsigned STAlign = ST->getAlignment();
10309     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10310     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10311     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10312       return SDValue();
10313
10314     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10315                                 LD->getChain(), LD->getBasePtr(),
10316                                 LD->getPointerInfo(),
10317                                 false, false, false, LDAlign);
10318
10319     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10320                                  NewLD, ST->getBasePtr(),
10321                                  ST->getPointerInfo(),
10322                                  false, false, STAlign);
10323
10324     AddToWorklist(NewLD.getNode());
10325     AddToWorklist(NewST.getNode());
10326     WorklistRemover DeadNodes(*this);
10327     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10328     ++LdStFP2Int;
10329     return NewST;
10330   }
10331
10332   return SDValue();
10333 }
10334
10335 namespace {
10336 /// Helper struct to parse and store a memory address as base + index + offset.
10337 /// We ignore sign extensions when it is safe to do so.
10338 /// The following two expressions are not equivalent. To differentiate we need
10339 /// to store whether there was a sign extension involved in the index
10340 /// computation.
10341 ///  (load (i64 add (i64 copyfromreg %c)
10342 ///                 (i64 signextend (add (i8 load %index)
10343 ///                                      (i8 1))))
10344 /// vs
10345 ///
10346 /// (load (i64 add (i64 copyfromreg %c)
10347 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10348 ///                                         (i32 1)))))
10349 struct BaseIndexOffset {
10350   SDValue Base;
10351   SDValue Index;
10352   int64_t Offset;
10353   bool IsIndexSignExt;
10354
10355   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10356
10357   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10358                   bool IsIndexSignExt) :
10359     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10360
10361   bool equalBaseIndex(const BaseIndexOffset &Other) {
10362     return Other.Base == Base && Other.Index == Index &&
10363       Other.IsIndexSignExt == IsIndexSignExt;
10364   }
10365
10366   /// Parses tree in Ptr for base, index, offset addresses.
10367   static BaseIndexOffset match(SDValue Ptr) {
10368     bool IsIndexSignExt = false;
10369
10370     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10371     // instruction, then it could be just the BASE or everything else we don't
10372     // know how to handle. Just use Ptr as BASE and give up.
10373     if (Ptr->getOpcode() != ISD::ADD)
10374       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10375
10376     // We know that we have at least an ADD instruction. Try to pattern match
10377     // the simple case of BASE + OFFSET.
10378     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10379       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10380       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10381                               IsIndexSignExt);
10382     }
10383
10384     // Inside a loop the current BASE pointer is calculated using an ADD and a
10385     // MUL instruction. In this case Ptr is the actual BASE pointer.
10386     // (i64 add (i64 %array_ptr)
10387     //          (i64 mul (i64 %induction_var)
10388     //                   (i64 %element_size)))
10389     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10390       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10391
10392     // Look at Base + Index + Offset cases.
10393     SDValue Base = Ptr->getOperand(0);
10394     SDValue IndexOffset = Ptr->getOperand(1);
10395
10396     // Skip signextends.
10397     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10398       IndexOffset = IndexOffset->getOperand(0);
10399       IsIndexSignExt = true;
10400     }
10401
10402     // Either the case of Base + Index (no offset) or something else.
10403     if (IndexOffset->getOpcode() != ISD::ADD)
10404       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10405
10406     // Now we have the case of Base + Index + offset.
10407     SDValue Index = IndexOffset->getOperand(0);
10408     SDValue Offset = IndexOffset->getOperand(1);
10409
10410     if (!isa<ConstantSDNode>(Offset))
10411       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10412
10413     // Ignore signextends.
10414     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10415       Index = Index->getOperand(0);
10416       IsIndexSignExt = true;
10417     } else IsIndexSignExt = false;
10418
10419     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10420     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10421   }
10422 };
10423 } // namespace
10424
10425 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10426                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10427                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10428   // Make sure we have something to merge.
10429   if (NumElem < 2)
10430     return false;
10431
10432   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10433   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10434   unsigned LatestNodeUsed = 0;
10435
10436   for (unsigned i=0; i < NumElem; ++i) {
10437     // Find a chain for the new wide-store operand. Notice that some
10438     // of the store nodes that we found may not be selected for inclusion
10439     // in the wide store. The chain we use needs to be the chain of the
10440     // latest store node which is *used* and replaced by the wide store.
10441     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10442       LatestNodeUsed = i;
10443   }
10444
10445   // The latest Node in the DAG.
10446   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10447   SDLoc DL(StoreNodes[0].MemNode);
10448
10449   SDValue StoredVal;
10450   if (UseVector) {
10451     // Find a legal type for the vector store.
10452     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10453     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10454     if (IsConstantSrc) {
10455       // A vector store with a constant source implies that the constant is
10456       // zero; we only handle merging stores of constant zeros because the zero
10457       // can be materialized without a load.
10458       // It may be beneficial to loosen this restriction to allow non-zero
10459       // store merging.
10460       StoredVal = DAG.getConstant(0, DL, Ty);
10461     } else {
10462       SmallVector<SDValue, 8> Ops;
10463       for (unsigned i = 0; i < NumElem ; ++i) {
10464         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10465         SDValue Val = St->getValue();
10466         // All of the operands of a BUILD_VECTOR must have the same type.
10467         if (Val.getValueType() != MemVT)
10468           return false;
10469         Ops.push_back(Val);
10470       }
10471
10472       // Build the extracted vector elements back into a vector.
10473       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10474     }
10475   } else {
10476     // We should always use a vector store when merging extracted vector
10477     // elements, so this path implies a store of constants.
10478     assert(IsConstantSrc && "Merged vector elements should use vector store");
10479
10480     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10481     APInt StoreInt(StoreBW, 0);
10482
10483     // Construct a single integer constant which is made of the smaller
10484     // constant inputs.
10485     bool IsLE = TLI.isLittleEndian();
10486     for (unsigned i = 0; i < NumElem ; ++i) {
10487       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10488       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10489       SDValue Val = St->getValue();
10490       StoreInt <<= ElementSizeBytes*8;
10491       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10492         StoreInt |= C->getAPIntValue().zext(StoreBW);
10493       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10494         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10495       } else {
10496         llvm_unreachable("Invalid constant element type");
10497       }
10498     }
10499
10500     // Create the new Load and Store operations.
10501     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10502     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10503   }
10504
10505   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10506                                   FirstInChain->getBasePtr(),
10507                                   FirstInChain->getPointerInfo(),
10508                                   false, false,
10509                                   FirstInChain->getAlignment());
10510
10511   // Replace the last store with the new store
10512   CombineTo(LatestOp, NewStore);
10513   // Erase all other stores.
10514   for (unsigned i = 0; i < NumElem ; ++i) {
10515     if (StoreNodes[i].MemNode == LatestOp)
10516       continue;
10517     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10518     // ReplaceAllUsesWith will replace all uses that existed when it was
10519     // called, but graph optimizations may cause new ones to appear. For
10520     // example, the case in pr14333 looks like
10521     //
10522     //  St's chain -> St -> another store -> X
10523     //
10524     // And the only difference from St to the other store is the chain.
10525     // When we change it's chain to be St's chain they become identical,
10526     // get CSEed and the net result is that X is now a use of St.
10527     // Since we know that St is redundant, just iterate.
10528     while (!St->use_empty())
10529       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10530     deleteAndRecombine(St);
10531   }
10532
10533   return true;
10534 }
10535
10536 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10537   if (OptLevel == CodeGenOpt::None)
10538     return false;
10539
10540   EVT MemVT = St->getMemoryVT();
10541   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10542   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10543       Attribute::NoImplicitFloat);
10544
10545   // Don't merge vectors into wider inputs.
10546   if (MemVT.isVector() || !MemVT.isSimple())
10547     return false;
10548
10549   // Perform an early exit check. Do not bother looking at stored values that
10550   // are not constants, loads, or extracted vector elements.
10551   SDValue StoredVal = St->getValue();
10552   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10553   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10554                        isa<ConstantFPSDNode>(StoredVal);
10555   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10556
10557   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10558     return false;
10559
10560   // Only look at ends of store sequences.
10561   SDValue Chain = SDValue(St, 0);
10562   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10563     return false;
10564
10565   // This holds the base pointer, index, and the offset in bytes from the base
10566   // pointer.
10567   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10568
10569   // We must have a base and an offset.
10570   if (!BasePtr.Base.getNode())
10571     return false;
10572
10573   // Do not handle stores to undef base pointers.
10574   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10575     return false;
10576
10577   // Save the LoadSDNodes that we find in the chain.
10578   // We need to make sure that these nodes do not interfere with
10579   // any of the store nodes.
10580   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10581
10582   // Save the StoreSDNodes that we find in the chain.
10583   SmallVector<MemOpLink, 8> StoreNodes;
10584
10585   // Walk up the chain and look for nodes with offsets from the same
10586   // base pointer. Stop when reaching an instruction with a different kind
10587   // or instruction which has a different base pointer.
10588   unsigned Seq = 0;
10589   StoreSDNode *Index = St;
10590   while (Index) {
10591     // If the chain has more than one use, then we can't reorder the mem ops.
10592     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10593       break;
10594
10595     // Find the base pointer and offset for this memory node.
10596     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10597
10598     // Check that the base pointer is the same as the original one.
10599     if (!Ptr.equalBaseIndex(BasePtr))
10600       break;
10601
10602     // Check that the alignment is the same.
10603     if (Index->getAlignment() != St->getAlignment())
10604       break;
10605
10606     // The memory operands must not be volatile.
10607     if (Index->isVolatile() || Index->isIndexed())
10608       break;
10609
10610     // No truncation.
10611     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10612       if (St->isTruncatingStore())
10613         break;
10614
10615     // The stored memory type must be the same.
10616     if (Index->getMemoryVT() != MemVT)
10617       break;
10618
10619     // We do not allow unaligned stores because we want to prevent overriding
10620     // stores.
10621     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10622       break;
10623
10624     // We found a potential memory operand to merge.
10625     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10626
10627     // Find the next memory operand in the chain. If the next operand in the
10628     // chain is a store then move up and continue the scan with the next
10629     // memory operand. If the next operand is a load save it and use alias
10630     // information to check if it interferes with anything.
10631     SDNode *NextInChain = Index->getChain().getNode();
10632     while (1) {
10633       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10634         // We found a store node. Use it for the next iteration.
10635         Index = STn;
10636         break;
10637       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10638         if (Ldn->isVolatile()) {
10639           Index = nullptr;
10640           break;
10641         }
10642
10643         // Save the load node for later. Continue the scan.
10644         AliasLoadNodes.push_back(Ldn);
10645         NextInChain = Ldn->getChain().getNode();
10646         continue;
10647       } else {
10648         Index = nullptr;
10649         break;
10650       }
10651     }
10652   }
10653
10654   // Check if there is anything to merge.
10655   if (StoreNodes.size() < 2)
10656     return false;
10657
10658   // Sort the memory operands according to their distance from the base pointer.
10659   std::sort(StoreNodes.begin(), StoreNodes.end(),
10660             [](MemOpLink LHS, MemOpLink RHS) {
10661     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10662            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10663             LHS.SequenceNum > RHS.SequenceNum);
10664   });
10665
10666   // Scan the memory operations on the chain and find the first non-consecutive
10667   // store memory address.
10668   unsigned LastConsecutiveStore = 0;
10669   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10670   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10671
10672     // Check that the addresses are consecutive starting from the second
10673     // element in the list of stores.
10674     if (i > 0) {
10675       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10676       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10677         break;
10678     }
10679
10680     bool Alias = false;
10681     // Check if this store interferes with any of the loads that we found.
10682     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10683       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10684         Alias = true;
10685         break;
10686       }
10687     // We found a load that alias with this store. Stop the sequence.
10688     if (Alias)
10689       break;
10690
10691     // Mark this node as useful.
10692     LastConsecutiveStore = i;
10693   }
10694
10695   // The node with the lowest store address.
10696   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10697
10698   // Store the constants into memory as one consecutive store.
10699   if (IsConstantSrc) {
10700     unsigned LastLegalType = 0;
10701     unsigned LastLegalVectorType = 0;
10702     bool NonZero = false;
10703     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10704       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10705       SDValue StoredVal = St->getValue();
10706
10707       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10708         NonZero |= !C->isNullValue();
10709       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10710         NonZero |= !C->getConstantFPValue()->isNullValue();
10711       } else {
10712         // Non-constant.
10713         break;
10714       }
10715
10716       // Find a legal type for the constant store.
10717       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10718       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10719       if (TLI.isTypeLegal(StoreTy))
10720         LastLegalType = i+1;
10721       // Or check whether a truncstore is legal.
10722       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10723                TargetLowering::TypePromoteInteger) {
10724         EVT LegalizedStoredValueTy =
10725           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10726         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10727           LastLegalType = i+1;
10728       }
10729
10730       // Find a legal type for the vector store.
10731       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10732       if (TLI.isTypeLegal(Ty))
10733         LastLegalVectorType = i + 1;
10734     }
10735
10736     // We only use vectors if the constant is known to be zero and the
10737     // function is not marked with the noimplicitfloat attribute.
10738     if (NonZero || NoVectors)
10739       LastLegalVectorType = 0;
10740
10741     // Check if we found a legal integer type to store.
10742     if (LastLegalType == 0 && LastLegalVectorType == 0)
10743       return false;
10744
10745     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10746     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10747
10748     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10749                                            true, UseVector);
10750   }
10751
10752   // When extracting multiple vector elements, try to store them
10753   // in one vector store rather than a sequence of scalar stores.
10754   if (IsExtractVecEltSrc) {
10755     unsigned NumElem = 0;
10756     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10757       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10758       SDValue StoredVal = St->getValue();
10759       // This restriction could be loosened.
10760       // Bail out if any stored values are not elements extracted from a vector.
10761       // It should be possible to handle mixed sources, but load sources need
10762       // more careful handling (see the block of code below that handles
10763       // consecutive loads).
10764       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10765         return false;
10766
10767       // Find a legal type for the vector store.
10768       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10769       if (TLI.isTypeLegal(Ty))
10770         NumElem = i + 1;
10771     }
10772
10773     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10774                                            false, true);
10775   }
10776
10777   // Below we handle the case of multiple consecutive stores that
10778   // come from multiple consecutive loads. We merge them into a single
10779   // wide load and a single wide store.
10780
10781   // Look for load nodes which are used by the stored values.
10782   SmallVector<MemOpLink, 8> LoadNodes;
10783
10784   // Find acceptable loads. Loads need to have the same chain (token factor),
10785   // must not be zext, volatile, indexed, and they must be consecutive.
10786   BaseIndexOffset LdBasePtr;
10787   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10788     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10789     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10790     if (!Ld) break;
10791
10792     // Loads must only have one use.
10793     if (!Ld->hasNUsesOfValue(1, 0))
10794       break;
10795
10796     // Check that the alignment is the same as the stores.
10797     if (Ld->getAlignment() != St->getAlignment())
10798       break;
10799
10800     // The memory operands must not be volatile.
10801     if (Ld->isVolatile() || Ld->isIndexed())
10802       break;
10803
10804     // We do not accept ext loads.
10805     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10806       break;
10807
10808     // The stored memory type must be the same.
10809     if (Ld->getMemoryVT() != MemVT)
10810       break;
10811
10812     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10813     // If this is not the first ptr that we check.
10814     if (LdBasePtr.Base.getNode()) {
10815       // The base ptr must be the same.
10816       if (!LdPtr.equalBaseIndex(LdBasePtr))
10817         break;
10818     } else {
10819       // Check that all other base pointers are the same as this one.
10820       LdBasePtr = LdPtr;
10821     }
10822
10823     // We found a potential memory operand to merge.
10824     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10825   }
10826
10827   if (LoadNodes.size() < 2)
10828     return false;
10829
10830   // If we have load/store pair instructions and we only have two values,
10831   // don't bother.
10832   unsigned RequiredAlignment;
10833   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10834       St->getAlignment() >= RequiredAlignment)
10835     return false;
10836
10837   // Scan the memory operations on the chain and find the first non-consecutive
10838   // load memory address. These variables hold the index in the store node
10839   // array.
10840   unsigned LastConsecutiveLoad = 0;
10841   // This variable refers to the size and not index in the array.
10842   unsigned LastLegalVectorType = 0;
10843   unsigned LastLegalIntegerType = 0;
10844   StartAddress = LoadNodes[0].OffsetFromBase;
10845   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10846   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10847     // All loads much share the same chain.
10848     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10849       break;
10850
10851     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10852     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10853       break;
10854     LastConsecutiveLoad = i;
10855
10856     // Find a legal type for the vector store.
10857     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10858     if (TLI.isTypeLegal(StoreTy))
10859       LastLegalVectorType = i + 1;
10860
10861     // Find a legal type for the integer store.
10862     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10863     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10864     if (TLI.isTypeLegal(StoreTy))
10865       LastLegalIntegerType = i + 1;
10866     // Or check whether a truncstore and extload is legal.
10867     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10868              TargetLowering::TypePromoteInteger) {
10869       EVT LegalizedStoredValueTy =
10870         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10871       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10872           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10873           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10874           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10875         LastLegalIntegerType = i+1;
10876     }
10877   }
10878
10879   // Only use vector types if the vector type is larger than the integer type.
10880   // If they are the same, use integers.
10881   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10882   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10883
10884   // We add +1 here because the LastXXX variables refer to location while
10885   // the NumElem refers to array/index size.
10886   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10887   NumElem = std::min(LastLegalType, NumElem);
10888
10889   if (NumElem < 2)
10890     return false;
10891
10892   // The latest Node in the DAG.
10893   unsigned LatestNodeUsed = 0;
10894   for (unsigned i=1; i<NumElem; ++i) {
10895     // Find a chain for the new wide-store operand. Notice that some
10896     // of the store nodes that we found may not be selected for inclusion
10897     // in the wide store. The chain we use needs to be the chain of the
10898     // latest store node which is *used* and replaced by the wide store.
10899     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10900       LatestNodeUsed = i;
10901   }
10902
10903   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10904
10905   // Find if it is better to use vectors or integers to load and store
10906   // to memory.
10907   EVT JointMemOpVT;
10908   if (UseVectorTy) {
10909     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10910   } else {
10911     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10912     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10913   }
10914
10915   SDLoc LoadDL(LoadNodes[0].MemNode);
10916   SDLoc StoreDL(StoreNodes[0].MemNode);
10917
10918   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10919   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10920                                 FirstLoad->getChain(),
10921                                 FirstLoad->getBasePtr(),
10922                                 FirstLoad->getPointerInfo(),
10923                                 false, false, false,
10924                                 FirstLoad->getAlignment());
10925
10926   SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
10927                                   FirstInChain->getBasePtr(),
10928                                   FirstInChain->getPointerInfo(), false, false,
10929                                   FirstInChain->getAlignment());
10930
10931   // Replace one of the loads with the new load.
10932   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10933   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10934                                 SDValue(NewLoad.getNode(), 1));
10935
10936   // Remove the rest of the load chains.
10937   for (unsigned i = 1; i < NumElem ; ++i) {
10938     // Replace all chain users of the old load nodes with the chain of the new
10939     // load node.
10940     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10941     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10942   }
10943
10944   // Replace the last store with the new store.
10945   CombineTo(LatestOp, NewStore);
10946   // Erase all other stores.
10947   for (unsigned i = 0; i < NumElem ; ++i) {
10948     // Remove all Store nodes.
10949     if (StoreNodes[i].MemNode == LatestOp)
10950       continue;
10951     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10952     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10953     deleteAndRecombine(St);
10954   }
10955
10956   return true;
10957 }
10958
10959 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10960   StoreSDNode *ST  = cast<StoreSDNode>(N);
10961   SDValue Chain = ST->getChain();
10962   SDValue Value = ST->getValue();
10963   SDValue Ptr   = ST->getBasePtr();
10964
10965   // If this is a store of a bit convert, store the input value if the
10966   // resultant store does not need a higher alignment than the original.
10967   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10968       ST->isUnindexed()) {
10969     unsigned OrigAlign = ST->getAlignment();
10970     EVT SVT = Value.getOperand(0).getValueType();
10971     unsigned Align = TLI.getDataLayout()->
10972       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10973     if (Align <= OrigAlign &&
10974         ((!LegalOperations && !ST->isVolatile()) ||
10975          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10976       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10977                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10978                           ST->isNonTemporal(), OrigAlign,
10979                           ST->getAAInfo());
10980   }
10981
10982   // Turn 'store undef, Ptr' -> nothing.
10983   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10984     return Chain;
10985
10986   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10987   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10988     // NOTE: If the original store is volatile, this transform must not increase
10989     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10990     // processor operation but an i64 (which is not legal) requires two.  So the
10991     // transform should not be done in this case.
10992     if (Value.getOpcode() != ISD::TargetConstantFP) {
10993       SDValue Tmp;
10994       switch (CFP->getSimpleValueType(0).SimpleTy) {
10995       default: llvm_unreachable("Unknown FP type");
10996       case MVT::f16:    // We don't do this for these yet.
10997       case MVT::f80:
10998       case MVT::f128:
10999       case MVT::ppcf128:
11000         break;
11001       case MVT::f32:
11002         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11003             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11004           ;
11005           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11006                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11007                               MVT::i32);
11008           return DAG.getStore(Chain, SDLoc(N), Tmp,
11009                               Ptr, ST->getMemOperand());
11010         }
11011         break;
11012       case MVT::f64:
11013         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11014              !ST->isVolatile()) ||
11015             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11016           ;
11017           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11018                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11019           return DAG.getStore(Chain, SDLoc(N), Tmp,
11020                               Ptr, ST->getMemOperand());
11021         }
11022
11023         if (!ST->isVolatile() &&
11024             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11025           // Many FP stores are not made apparent until after legalize, e.g. for
11026           // argument passing.  Since this is so common, custom legalize the
11027           // 64-bit integer store into two 32-bit stores.
11028           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11029           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11030           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11031           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11032
11033           unsigned Alignment = ST->getAlignment();
11034           bool isVolatile = ST->isVolatile();
11035           bool isNonTemporal = ST->isNonTemporal();
11036           AAMDNodes AAInfo = ST->getAAInfo();
11037
11038           SDLoc DL(N);
11039
11040           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11041                                      Ptr, ST->getPointerInfo(),
11042                                      isVolatile, isNonTemporal,
11043                                      ST->getAlignment(), AAInfo);
11044           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11045                             DAG.getConstant(4, DL, Ptr.getValueType()));
11046           Alignment = MinAlign(Alignment, 4U);
11047           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11048                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11049                                      isVolatile, isNonTemporal,
11050                                      Alignment, AAInfo);
11051           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11052                              St0, St1);
11053         }
11054
11055         break;
11056       }
11057     }
11058   }
11059
11060   // Try to infer better alignment information than the store already has.
11061   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11062     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11063       if (Align > ST->getAlignment()) {
11064         SDValue NewStore =
11065                DAG.getTruncStore(Chain, SDLoc(N), Value,
11066                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11067                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11068                                  ST->getAAInfo());
11069         if (NewStore.getNode() != N)
11070           return CombineTo(ST, NewStore, true);
11071       }
11072     }
11073   }
11074
11075   // Try transforming a pair floating point load / store ops to integer
11076   // load / store ops.
11077   SDValue NewST = TransformFPLoadStorePair(N);
11078   if (NewST.getNode())
11079     return NewST;
11080
11081   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11082                                                   : DAG.getSubtarget().useAA();
11083 #ifndef NDEBUG
11084   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11085       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11086     UseAA = false;
11087 #endif
11088   if (UseAA && ST->isUnindexed()) {
11089     // Walk up chain skipping non-aliasing memory nodes.
11090     SDValue BetterChain = FindBetterChain(N, Chain);
11091
11092     // If there is a better chain.
11093     if (Chain != BetterChain) {
11094       SDValue ReplStore;
11095
11096       // Replace the chain to avoid dependency.
11097       if (ST->isTruncatingStore()) {
11098         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11099                                       ST->getMemoryVT(), ST->getMemOperand());
11100       } else {
11101         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11102                                  ST->getMemOperand());
11103       }
11104
11105       // Create token to keep both nodes around.
11106       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11107                                   MVT::Other, Chain, ReplStore);
11108
11109       // Make sure the new and old chains are cleaned up.
11110       AddToWorklist(Token.getNode());
11111
11112       // Don't add users to work list.
11113       return CombineTo(N, Token, false);
11114     }
11115   }
11116
11117   // Try transforming N to an indexed store.
11118   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11119     return SDValue(N, 0);
11120
11121   // FIXME: is there such a thing as a truncating indexed store?
11122   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11123       Value.getValueType().isInteger()) {
11124     // See if we can simplify the input to this truncstore with knowledge that
11125     // only the low bits are being used.  For example:
11126     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11127     SDValue Shorter =
11128       GetDemandedBits(Value,
11129                       APInt::getLowBitsSet(
11130                         Value.getValueType().getScalarType().getSizeInBits(),
11131                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11132     AddToWorklist(Value.getNode());
11133     if (Shorter.getNode())
11134       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11135                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11136
11137     // Otherwise, see if we can simplify the operation with
11138     // SimplifyDemandedBits, which only works if the value has a single use.
11139     if (SimplifyDemandedBits(Value,
11140                         APInt::getLowBitsSet(
11141                           Value.getValueType().getScalarType().getSizeInBits(),
11142                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11143       return SDValue(N, 0);
11144   }
11145
11146   // If this is a load followed by a store to the same location, then the store
11147   // is dead/noop.
11148   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11149     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11150         ST->isUnindexed() && !ST->isVolatile() &&
11151         // There can't be any side effects between the load and store, such as
11152         // a call or store.
11153         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11154       // The store is dead, remove it.
11155       return Chain;
11156     }
11157   }
11158
11159   // If this is a store followed by a store with the same value to the same
11160   // location, then the store is dead/noop.
11161   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11162     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11163         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11164         ST1->isUnindexed() && !ST1->isVolatile()) {
11165       // The store is dead, remove it.
11166       return Chain;
11167     }
11168   }
11169
11170   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11171   // truncating store.  We can do this even if this is already a truncstore.
11172   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11173       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11174       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11175                             ST->getMemoryVT())) {
11176     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11177                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11178   }
11179
11180   // Only perform this optimization before the types are legal, because we
11181   // don't want to perform this optimization on every DAGCombine invocation.
11182   if (!LegalTypes) {
11183     bool EverChanged = false;
11184
11185     do {
11186       // There can be multiple store sequences on the same chain.
11187       // Keep trying to merge store sequences until we are unable to do so
11188       // or until we merge the last store on the chain.
11189       bool Changed = MergeConsecutiveStores(ST);
11190       EverChanged |= Changed;
11191       if (!Changed) break;
11192     } while (ST->getOpcode() != ISD::DELETED_NODE);
11193
11194     if (EverChanged)
11195       return SDValue(N, 0);
11196   }
11197
11198   return ReduceLoadOpStoreWidth(N);
11199 }
11200
11201 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11202   SDValue InVec = N->getOperand(0);
11203   SDValue InVal = N->getOperand(1);
11204   SDValue EltNo = N->getOperand(2);
11205   SDLoc dl(N);
11206
11207   // If the inserted element is an UNDEF, just use the input vector.
11208   if (InVal.getOpcode() == ISD::UNDEF)
11209     return InVec;
11210
11211   EVT VT = InVec.getValueType();
11212
11213   // If we can't generate a legal BUILD_VECTOR, exit
11214   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11215     return SDValue();
11216
11217   // Check that we know which element is being inserted
11218   if (!isa<ConstantSDNode>(EltNo))
11219     return SDValue();
11220   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11221
11222   // Canonicalize insert_vector_elt dag nodes.
11223   // Example:
11224   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11225   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11226   //
11227   // Do this only if the child insert_vector node has one use; also
11228   // do this only if indices are both constants and Idx1 < Idx0.
11229   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11230       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11231     unsigned OtherElt =
11232       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11233     if (Elt < OtherElt) {
11234       // Swap nodes.
11235       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11236                                   InVec.getOperand(0), InVal, EltNo);
11237       AddToWorklist(NewOp.getNode());
11238       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11239                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11240     }
11241   }
11242
11243   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11244   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11245   // vector elements.
11246   SmallVector<SDValue, 8> Ops;
11247   // Do not combine these two vectors if the output vector will not replace
11248   // the input vector.
11249   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11250     Ops.append(InVec.getNode()->op_begin(),
11251                InVec.getNode()->op_end());
11252   } else if (InVec.getOpcode() == ISD::UNDEF) {
11253     unsigned NElts = VT.getVectorNumElements();
11254     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11255   } else {
11256     return SDValue();
11257   }
11258
11259   // Insert the element
11260   if (Elt < Ops.size()) {
11261     // All the operands of BUILD_VECTOR must have the same type;
11262     // we enforce that here.
11263     EVT OpVT = Ops[0].getValueType();
11264     if (InVal.getValueType() != OpVT)
11265       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11266                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11267                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11268     Ops[Elt] = InVal;
11269   }
11270
11271   // Return the new vector
11272   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11273 }
11274
11275 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11276     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11277   EVT ResultVT = EVE->getValueType(0);
11278   EVT VecEltVT = InVecVT.getVectorElementType();
11279   unsigned Align = OriginalLoad->getAlignment();
11280   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11281       VecEltVT.getTypeForEVT(*DAG.getContext()));
11282
11283   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11284     return SDValue();
11285
11286   Align = NewAlign;
11287
11288   SDValue NewPtr = OriginalLoad->getBasePtr();
11289   SDValue Offset;
11290   EVT PtrType = NewPtr.getValueType();
11291   MachinePointerInfo MPI;
11292   SDLoc DL(EVE);
11293   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11294     int Elt = ConstEltNo->getZExtValue();
11295     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11296     if (TLI.isBigEndian())
11297       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11298     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11299     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11300   } else {
11301     Offset = DAG.getNode(
11302         ISD::MUL, DL, EltNo.getValueType(), EltNo,
11303         DAG.getConstant(VecEltVT.getStoreSize(), DL, EltNo.getValueType()));
11304     if (TLI.isBigEndian())
11305       Offset = DAG.getNode(
11306           ISD::SUB, DL, EltNo.getValueType(),
11307           DAG.getConstant(InVecVT.getStoreSize(), DL, EltNo.getValueType()),
11308           Offset);
11309     MPI = OriginalLoad->getPointerInfo();
11310   }
11311   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11312
11313   // The replacement we need to do here is a little tricky: we need to
11314   // replace an extractelement of a load with a load.
11315   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11316   // Note that this replacement assumes that the extractvalue is the only
11317   // use of the load; that's okay because we don't want to perform this
11318   // transformation in other cases anyway.
11319   SDValue Load;
11320   SDValue Chain;
11321   if (ResultVT.bitsGT(VecEltVT)) {
11322     // If the result type of vextract is wider than the load, then issue an
11323     // extending load instead.
11324     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11325                                                   VecEltVT)
11326                                    ? ISD::ZEXTLOAD
11327                                    : ISD::EXTLOAD;
11328     Load = DAG.getExtLoad(
11329         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11330         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11331         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11332     Chain = Load.getValue(1);
11333   } else {
11334     Load = DAG.getLoad(
11335         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11336         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11337         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11338     Chain = Load.getValue(1);
11339     if (ResultVT.bitsLT(VecEltVT))
11340       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11341     else
11342       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11343   }
11344   WorklistRemover DeadNodes(*this);
11345   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11346   SDValue To[] = { Load, Chain };
11347   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11348   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11349   // worklist explicitly as well.
11350   AddToWorklist(Load.getNode());
11351   AddUsersToWorklist(Load.getNode()); // Add users too
11352   // Make sure to revisit this node to clean it up; it will usually be dead.
11353   AddToWorklist(EVE);
11354   ++OpsNarrowed;
11355   return SDValue(EVE, 0);
11356 }
11357
11358 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11359   // (vextract (scalar_to_vector val, 0) -> val
11360   SDValue InVec = N->getOperand(0);
11361   EVT VT = InVec.getValueType();
11362   EVT NVT = N->getValueType(0);
11363
11364   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11365     // Check if the result type doesn't match the inserted element type. A
11366     // SCALAR_TO_VECTOR may truncate the inserted element and the
11367     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11368     SDValue InOp = InVec.getOperand(0);
11369     if (InOp.getValueType() != NVT) {
11370       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11371       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11372     }
11373     return InOp;
11374   }
11375
11376   SDValue EltNo = N->getOperand(1);
11377   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11378
11379   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11380   // We only perform this optimization before the op legalization phase because
11381   // we may introduce new vector instructions which are not backed by TD
11382   // patterns. For example on AVX, extracting elements from a wide vector
11383   // without using extract_subvector. However, if we can find an underlying
11384   // scalar value, then we can always use that.
11385   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11386       && ConstEltNo) {
11387     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11388     int NumElem = VT.getVectorNumElements();
11389     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11390     // Find the new index to extract from.
11391     int OrigElt = SVOp->getMaskElt(Elt);
11392
11393     // Extracting an undef index is undef.
11394     if (OrigElt == -1)
11395       return DAG.getUNDEF(NVT);
11396
11397     // Select the right vector half to extract from.
11398     SDValue SVInVec;
11399     if (OrigElt < NumElem) {
11400       SVInVec = InVec->getOperand(0);
11401     } else {
11402       SVInVec = InVec->getOperand(1);
11403       OrigElt -= NumElem;
11404     }
11405
11406     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11407       SDValue InOp = SVInVec.getOperand(OrigElt);
11408       if (InOp.getValueType() != NVT) {
11409         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11410         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11411       }
11412
11413       return InOp;
11414     }
11415
11416     // FIXME: We should handle recursing on other vector shuffles and
11417     // scalar_to_vector here as well.
11418
11419     if (!LegalOperations) {
11420       EVT IndexTy = TLI.getVectorIdxTy();
11421       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11422                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11423     }
11424   }
11425
11426   bool BCNumEltsChanged = false;
11427   EVT ExtVT = VT.getVectorElementType();
11428   EVT LVT = ExtVT;
11429
11430   // If the result of load has to be truncated, then it's not necessarily
11431   // profitable.
11432   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11433     return SDValue();
11434
11435   if (InVec.getOpcode() == ISD::BITCAST) {
11436     // Don't duplicate a load with other uses.
11437     if (!InVec.hasOneUse())
11438       return SDValue();
11439
11440     EVT BCVT = InVec.getOperand(0).getValueType();
11441     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11442       return SDValue();
11443     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11444       BCNumEltsChanged = true;
11445     InVec = InVec.getOperand(0);
11446     ExtVT = BCVT.getVectorElementType();
11447   }
11448
11449   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11450   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11451       ISD::isNormalLoad(InVec.getNode()) &&
11452       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11453     SDValue Index = N->getOperand(1);
11454     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11455       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11456                                                            OrigLoad);
11457   }
11458
11459   // Perform only after legalization to ensure build_vector / vector_shuffle
11460   // optimizations have already been done.
11461   if (!LegalOperations) return SDValue();
11462
11463   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11464   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11465   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11466
11467   if (ConstEltNo) {
11468     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11469
11470     LoadSDNode *LN0 = nullptr;
11471     const ShuffleVectorSDNode *SVN = nullptr;
11472     if (ISD::isNormalLoad(InVec.getNode())) {
11473       LN0 = cast<LoadSDNode>(InVec);
11474     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11475                InVec.getOperand(0).getValueType() == ExtVT &&
11476                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11477       // Don't duplicate a load with other uses.
11478       if (!InVec.hasOneUse())
11479         return SDValue();
11480
11481       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11482     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11483       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11484       // =>
11485       // (load $addr+1*size)
11486
11487       // Don't duplicate a load with other uses.
11488       if (!InVec.hasOneUse())
11489         return SDValue();
11490
11491       // If the bit convert changed the number of elements, it is unsafe
11492       // to examine the mask.
11493       if (BCNumEltsChanged)
11494         return SDValue();
11495
11496       // Select the input vector, guarding against out of range extract vector.
11497       unsigned NumElems = VT.getVectorNumElements();
11498       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11499       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11500
11501       if (InVec.getOpcode() == ISD::BITCAST) {
11502         // Don't duplicate a load with other uses.
11503         if (!InVec.hasOneUse())
11504           return SDValue();
11505
11506         InVec = InVec.getOperand(0);
11507       }
11508       if (ISD::isNormalLoad(InVec.getNode())) {
11509         LN0 = cast<LoadSDNode>(InVec);
11510         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11511         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11512       }
11513     }
11514
11515     // Make sure we found a non-volatile load and the extractelement is
11516     // the only use.
11517     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11518       return SDValue();
11519
11520     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11521     if (Elt == -1)
11522       return DAG.getUNDEF(LVT);
11523
11524     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11525   }
11526
11527   return SDValue();
11528 }
11529
11530 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11531 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11532   // We perform this optimization post type-legalization because
11533   // the type-legalizer often scalarizes integer-promoted vectors.
11534   // Performing this optimization before may create bit-casts which
11535   // will be type-legalized to complex code sequences.
11536   // We perform this optimization only before the operation legalizer because we
11537   // may introduce illegal operations.
11538   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11539     return SDValue();
11540
11541   unsigned NumInScalars = N->getNumOperands();
11542   SDLoc dl(N);
11543   EVT VT = N->getValueType(0);
11544
11545   // Check to see if this is a BUILD_VECTOR of a bunch of values
11546   // which come from any_extend or zero_extend nodes. If so, we can create
11547   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11548   // optimizations. We do not handle sign-extend because we can't fill the sign
11549   // using shuffles.
11550   EVT SourceType = MVT::Other;
11551   bool AllAnyExt = true;
11552
11553   for (unsigned i = 0; i != NumInScalars; ++i) {
11554     SDValue In = N->getOperand(i);
11555     // Ignore undef inputs.
11556     if (In.getOpcode() == ISD::UNDEF) continue;
11557
11558     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11559     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11560
11561     // Abort if the element is not an extension.
11562     if (!ZeroExt && !AnyExt) {
11563       SourceType = MVT::Other;
11564       break;
11565     }
11566
11567     // The input is a ZeroExt or AnyExt. Check the original type.
11568     EVT InTy = In.getOperand(0).getValueType();
11569
11570     // Check that all of the widened source types are the same.
11571     if (SourceType == MVT::Other)
11572       // First time.
11573       SourceType = InTy;
11574     else if (InTy != SourceType) {
11575       // Multiple income types. Abort.
11576       SourceType = MVT::Other;
11577       break;
11578     }
11579
11580     // Check if all of the extends are ANY_EXTENDs.
11581     AllAnyExt &= AnyExt;
11582   }
11583
11584   // In order to have valid types, all of the inputs must be extended from the
11585   // same source type and all of the inputs must be any or zero extend.
11586   // Scalar sizes must be a power of two.
11587   EVT OutScalarTy = VT.getScalarType();
11588   bool ValidTypes = SourceType != MVT::Other &&
11589                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11590                  isPowerOf2_32(SourceType.getSizeInBits());
11591
11592   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11593   // turn into a single shuffle instruction.
11594   if (!ValidTypes)
11595     return SDValue();
11596
11597   bool isLE = TLI.isLittleEndian();
11598   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11599   assert(ElemRatio > 1 && "Invalid element size ratio");
11600   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11601                                DAG.getConstant(0, SDLoc(N), SourceType);
11602
11603   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11604   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11605
11606   // Populate the new build_vector
11607   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11608     SDValue Cast = N->getOperand(i);
11609     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11610             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11611             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11612     SDValue In;
11613     if (Cast.getOpcode() == ISD::UNDEF)
11614       In = DAG.getUNDEF(SourceType);
11615     else
11616       In = Cast->getOperand(0);
11617     unsigned Index = isLE ? (i * ElemRatio) :
11618                             (i * ElemRatio + (ElemRatio - 1));
11619
11620     assert(Index < Ops.size() && "Invalid index");
11621     Ops[Index] = In;
11622   }
11623
11624   // The type of the new BUILD_VECTOR node.
11625   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11626   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11627          "Invalid vector size");
11628   // Check if the new vector type is legal.
11629   if (!isTypeLegal(VecVT)) return SDValue();
11630
11631   // Make the new BUILD_VECTOR.
11632   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11633
11634   // The new BUILD_VECTOR node has the potential to be further optimized.
11635   AddToWorklist(BV.getNode());
11636   // Bitcast to the desired type.
11637   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11638 }
11639
11640 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11641   EVT VT = N->getValueType(0);
11642
11643   unsigned NumInScalars = N->getNumOperands();
11644   SDLoc dl(N);
11645
11646   EVT SrcVT = MVT::Other;
11647   unsigned Opcode = ISD::DELETED_NODE;
11648   unsigned NumDefs = 0;
11649
11650   for (unsigned i = 0; i != NumInScalars; ++i) {
11651     SDValue In = N->getOperand(i);
11652     unsigned Opc = In.getOpcode();
11653
11654     if (Opc == ISD::UNDEF)
11655       continue;
11656
11657     // If all scalar values are floats and converted from integers.
11658     if (Opcode == ISD::DELETED_NODE &&
11659         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11660       Opcode = Opc;
11661     }
11662
11663     if (Opc != Opcode)
11664       return SDValue();
11665
11666     EVT InVT = In.getOperand(0).getValueType();
11667
11668     // If all scalar values are typed differently, bail out. It's chosen to
11669     // simplify BUILD_VECTOR of integer types.
11670     if (SrcVT == MVT::Other)
11671       SrcVT = InVT;
11672     if (SrcVT != InVT)
11673       return SDValue();
11674     NumDefs++;
11675   }
11676
11677   // If the vector has just one element defined, it's not worth to fold it into
11678   // a vectorized one.
11679   if (NumDefs < 2)
11680     return SDValue();
11681
11682   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11683          && "Should only handle conversion from integer to float.");
11684   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11685
11686   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11687
11688   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11689     return SDValue();
11690
11691   // Just because the floating-point vector type is legal does not necessarily
11692   // mean that the corresponding integer vector type is.
11693   if (!isTypeLegal(NVT))
11694     return SDValue();
11695
11696   SmallVector<SDValue, 8> Opnds;
11697   for (unsigned i = 0; i != NumInScalars; ++i) {
11698     SDValue In = N->getOperand(i);
11699
11700     if (In.getOpcode() == ISD::UNDEF)
11701       Opnds.push_back(DAG.getUNDEF(SrcVT));
11702     else
11703       Opnds.push_back(In.getOperand(0));
11704   }
11705   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11706   AddToWorklist(BV.getNode());
11707
11708   return DAG.getNode(Opcode, dl, VT, BV);
11709 }
11710
11711 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11712   unsigned NumInScalars = N->getNumOperands();
11713   SDLoc dl(N);
11714   EVT VT = N->getValueType(0);
11715
11716   // A vector built entirely of undefs is undef.
11717   if (ISD::allOperandsUndef(N))
11718     return DAG.getUNDEF(VT);
11719
11720   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11721     return V;
11722
11723   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11724     return V;
11725
11726   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11727   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11728   // at most two distinct vectors, turn this into a shuffle node.
11729
11730   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11731   if (!isTypeLegal(VT))
11732     return SDValue();
11733
11734   // May only combine to shuffle after legalize if shuffle is legal.
11735   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11736     return SDValue();
11737
11738   SDValue VecIn1, VecIn2;
11739   bool UsesZeroVector = false;
11740   for (unsigned i = 0; i != NumInScalars; ++i) {
11741     SDValue Op = N->getOperand(i);
11742     // Ignore undef inputs.
11743     if (Op.getOpcode() == ISD::UNDEF) continue;
11744
11745     // See if we can combine this build_vector into a blend with a zero vector.
11746     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11747         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11748         (Op.getOpcode() == ISD::ConstantFP &&
11749         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11750       UsesZeroVector = true;
11751       continue;
11752     }
11753
11754     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11755     // constant index, bail out.
11756     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11757         !isa<ConstantSDNode>(Op.getOperand(1))) {
11758       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11759       break;
11760     }
11761
11762     // We allow up to two distinct input vectors.
11763     SDValue ExtractedFromVec = Op.getOperand(0);
11764     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11765       continue;
11766
11767     if (!VecIn1.getNode()) {
11768       VecIn1 = ExtractedFromVec;
11769     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11770       VecIn2 = ExtractedFromVec;
11771     } else {
11772       // Too many inputs.
11773       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11774       break;
11775     }
11776   }
11777
11778   // If everything is good, we can make a shuffle operation.
11779   if (VecIn1.getNode()) {
11780     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11781     SmallVector<int, 8> Mask;
11782     for (unsigned i = 0; i != NumInScalars; ++i) {
11783       unsigned Opcode = N->getOperand(i).getOpcode();
11784       if (Opcode == ISD::UNDEF) {
11785         Mask.push_back(-1);
11786         continue;
11787       }
11788
11789       // Operands can also be zero.
11790       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11791         assert(UsesZeroVector &&
11792                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11793                "Unexpected node found!");
11794         Mask.push_back(NumInScalars+i);
11795         continue;
11796       }
11797
11798       // If extracting from the first vector, just use the index directly.
11799       SDValue Extract = N->getOperand(i);
11800       SDValue ExtVal = Extract.getOperand(1);
11801       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11802       if (Extract.getOperand(0) == VecIn1) {
11803         Mask.push_back(ExtIndex);
11804         continue;
11805       }
11806
11807       // Otherwise, use InIdx + InputVecSize
11808       Mask.push_back(InNumElements + ExtIndex);
11809     }
11810
11811     // Avoid introducing illegal shuffles with zero.
11812     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11813       return SDValue();
11814
11815     // We can't generate a shuffle node with mismatched input and output types.
11816     // Attempt to transform a single input vector to the correct type.
11817     if ((VT != VecIn1.getValueType())) {
11818       // If the input vector type has a different base type to the output
11819       // vector type, bail out.
11820       EVT VTElemType = VT.getVectorElementType();
11821       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11822           (VecIn2.getNode() &&
11823            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11824         return SDValue();
11825
11826       // If the input vector is too small, widen it.
11827       // We only support widening of vectors which are half the size of the
11828       // output registers. For example XMM->YMM widening on X86 with AVX.
11829       EVT VecInT = VecIn1.getValueType();
11830       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11831         // If we only have one small input, widen it by adding undef values.
11832         if (!VecIn2.getNode())
11833           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11834                                DAG.getUNDEF(VecIn1.getValueType()));
11835         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11836           // If we have two small inputs of the same type, try to concat them.
11837           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11838           VecIn2 = SDValue(nullptr, 0);
11839         } else
11840           return SDValue();
11841       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11842         // If the input vector is too large, try to split it.
11843         // We don't support having two input vectors that are too large.
11844         // If the zero vector was used, we can not split the vector,
11845         // since we'd need 3 inputs.
11846         if (UsesZeroVector || VecIn2.getNode())
11847           return SDValue();
11848
11849         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11850           return SDValue();
11851
11852         // Try to replace VecIn1 with two extract_subvectors
11853         // No need to update the masks, they should still be correct.
11854         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11855           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11856         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11857           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11858       } else
11859         return SDValue();
11860     }
11861
11862     if (UsesZeroVector)
11863       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11864                                 DAG.getConstantFP(0.0, dl, VT);
11865     else
11866       // If VecIn2 is unused then change it to undef.
11867       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11868
11869     // Check that we were able to transform all incoming values to the same
11870     // type.
11871     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11872         VecIn1.getValueType() != VT)
11873           return SDValue();
11874
11875     // Return the new VECTOR_SHUFFLE node.
11876     SDValue Ops[2];
11877     Ops[0] = VecIn1;
11878     Ops[1] = VecIn2;
11879     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11880   }
11881
11882   return SDValue();
11883 }
11884
11885 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11886   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11887   EVT OpVT = N->getOperand(0).getValueType();
11888
11889   // If the operands are legal vectors, leave them alone.
11890   if (TLI.isTypeLegal(OpVT))
11891     return SDValue();
11892
11893   SDLoc DL(N);
11894   EVT VT = N->getValueType(0);
11895   SmallVector<SDValue, 8> Ops;
11896
11897   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
11898   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11899
11900   // Keep track of what we encounter.
11901   bool AnyInteger = false;
11902   bool AnyFP = false;
11903   for (const SDValue &Op : N->ops()) {
11904     if (ISD::BITCAST == Op.getOpcode() &&
11905         !Op.getOperand(0).getValueType().isVector())
11906       Ops.push_back(Op.getOperand(0));
11907     else if (ISD::UNDEF == Op.getOpcode())
11908       Ops.push_back(ScalarUndef);
11909     else
11910       return SDValue();
11911
11912     // Note whether we encounter an integer or floating point scalar.
11913     // If it's neither, bail out, it could be something weird like x86mmx.
11914     EVT LastOpVT = Ops.back().getValueType();
11915     if (LastOpVT.isFloatingPoint())
11916       AnyFP = true;
11917     else if (LastOpVT.isInteger())
11918       AnyInteger = true;
11919     else
11920       return SDValue();
11921   }
11922
11923   // If any of the operands is a floating point scalar bitcast to a vector,
11924   // use floating point types throughout, and bitcast everything.  
11925   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
11926   if (AnyFP) {
11927     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
11928     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11929     if (AnyInteger) {
11930       for (SDValue &Op : Ops) {
11931         if (Op.getValueType() == SVT)
11932           continue;
11933         if (Op.getOpcode() == ISD::UNDEF)
11934           Op = ScalarUndef;
11935         else
11936           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
11937       }
11938     }
11939   }
11940
11941   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
11942                                VT.getSizeInBits() / SVT.getSizeInBits());
11943   return DAG.getNode(ISD::BITCAST, DL, VT,
11944                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
11945 }
11946
11947 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11948   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11949   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11950   // inputs come from at most two distinct vectors, turn this into a shuffle
11951   // node.
11952
11953   // If we only have one input vector, we don't need to do any concatenation.
11954   if (N->getNumOperands() == 1)
11955     return N->getOperand(0);
11956
11957   // Check if all of the operands are undefs.
11958   EVT VT = N->getValueType(0);
11959   if (ISD::allOperandsUndef(N))
11960     return DAG.getUNDEF(VT);
11961
11962   // Optimize concat_vectors where all but the first of the vectors are undef.
11963   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
11964         return Op.getOpcode() == ISD::UNDEF;
11965       })) {
11966     SDValue In = N->getOperand(0);
11967     assert(In.getValueType().isVector() && "Must concat vectors");
11968
11969     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11970     if (In->getOpcode() == ISD::BITCAST &&
11971         !In->getOperand(0)->getValueType(0).isVector()) {
11972       SDValue Scalar = In->getOperand(0);
11973
11974       // If the bitcast type isn't legal, it might be a trunc of a legal type;
11975       // look through the trunc so we can still do the transform:
11976       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
11977       if (Scalar->getOpcode() == ISD::TRUNCATE &&
11978           !TLI.isTypeLegal(Scalar.getValueType()) &&
11979           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
11980         Scalar = Scalar->getOperand(0);
11981
11982       EVT SclTy = Scalar->getValueType(0);
11983
11984       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11985         return SDValue();
11986
11987       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11988                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11989       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11990         return SDValue();
11991
11992       SDLoc dl = SDLoc(N);
11993       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11994       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11995     }
11996   }
11997
11998   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11999   // We have already tested above for an UNDEF only concatenation.
12000   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12001   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12002   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12003     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12004   };
12005   bool AllBuildVectorsOrUndefs =
12006       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12007   if (AllBuildVectorsOrUndefs) {
12008     SmallVector<SDValue, 8> Opnds;
12009     EVT SVT = VT.getScalarType();
12010
12011     EVT MinVT = SVT;
12012     if (!SVT.isFloatingPoint()) {
12013       // If BUILD_VECTOR are from built from integer, they may have different
12014       // operand types. Get the smallest type and truncate all operands to it.
12015       bool FoundMinVT = false;
12016       for (const SDValue &Op : N->ops())
12017         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12018           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12019           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12020           FoundMinVT = true;
12021         }
12022       assert(FoundMinVT && "Concat vector type mismatch");
12023     }
12024
12025     for (const SDValue &Op : N->ops()) {
12026       EVT OpVT = Op.getValueType();
12027       unsigned NumElts = OpVT.getVectorNumElements();
12028
12029       if (ISD::UNDEF == Op.getOpcode())
12030         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12031
12032       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12033         if (SVT.isFloatingPoint()) {
12034           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12035           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12036         } else {
12037           for (unsigned i = 0; i != NumElts; ++i)
12038             Opnds.push_back(
12039                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12040         }
12041       }
12042     }
12043
12044     assert(VT.getVectorNumElements() == Opnds.size() &&
12045            "Concat vector type mismatch");
12046     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12047   }
12048
12049   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12050   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12051     return V;
12052
12053   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12054   // nodes often generate nop CONCAT_VECTOR nodes.
12055   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12056   // place the incoming vectors at the exact same location.
12057   SDValue SingleSource = SDValue();
12058   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12059
12060   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12061     SDValue Op = N->getOperand(i);
12062
12063     if (Op.getOpcode() == ISD::UNDEF)
12064       continue;
12065
12066     // Check if this is the identity extract:
12067     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12068       return SDValue();
12069
12070     // Find the single incoming vector for the extract_subvector.
12071     if (SingleSource.getNode()) {
12072       if (Op.getOperand(0) != SingleSource)
12073         return SDValue();
12074     } else {
12075       SingleSource = Op.getOperand(0);
12076
12077       // Check the source type is the same as the type of the result.
12078       // If not, this concat may extend the vector, so we can not
12079       // optimize it away.
12080       if (SingleSource.getValueType() != N->getValueType(0))
12081         return SDValue();
12082     }
12083
12084     unsigned IdentityIndex = i * PartNumElem;
12085     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12086     // The extract index must be constant.
12087     if (!CS)
12088       return SDValue();
12089
12090     // Check that we are reading from the identity index.
12091     if (CS->getZExtValue() != IdentityIndex)
12092       return SDValue();
12093   }
12094
12095   if (SingleSource.getNode())
12096     return SingleSource;
12097
12098   return SDValue();
12099 }
12100
12101 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12102   EVT NVT = N->getValueType(0);
12103   SDValue V = N->getOperand(0);
12104
12105   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12106     // Combine:
12107     //    (extract_subvec (concat V1, V2, ...), i)
12108     // Into:
12109     //    Vi if possible
12110     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12111     // type.
12112     if (V->getOperand(0).getValueType() != NVT)
12113       return SDValue();
12114     unsigned Idx = N->getConstantOperandVal(1);
12115     unsigned NumElems = NVT.getVectorNumElements();
12116     assert((Idx % NumElems) == 0 &&
12117            "IDX in concat is not a multiple of the result vector length.");
12118     return V->getOperand(Idx / NumElems);
12119   }
12120
12121   // Skip bitcasting
12122   if (V->getOpcode() == ISD::BITCAST)
12123     V = V.getOperand(0);
12124
12125   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12126     SDLoc dl(N);
12127     // Handle only simple case where vector being inserted and vector
12128     // being extracted are of same type, and are half size of larger vectors.
12129     EVT BigVT = V->getOperand(0).getValueType();
12130     EVT SmallVT = V->getOperand(1).getValueType();
12131     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12132       return SDValue();
12133
12134     // Only handle cases where both indexes are constants with the same type.
12135     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12136     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12137
12138     if (InsIdx && ExtIdx &&
12139         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12140         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12141       // Combine:
12142       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12143       // Into:
12144       //    indices are equal or bit offsets are equal => V1
12145       //    otherwise => (extract_subvec V1, ExtIdx)
12146       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12147           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12148         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12149       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12150                          DAG.getNode(ISD::BITCAST, dl,
12151                                      N->getOperand(0).getValueType(),
12152                                      V->getOperand(0)), N->getOperand(1));
12153     }
12154   }
12155
12156   return SDValue();
12157 }
12158
12159 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12160                                                  SDValue V, SelectionDAG &DAG) {
12161   SDLoc DL(V);
12162   EVT VT = V.getValueType();
12163
12164   switch (V.getOpcode()) {
12165   default:
12166     return V;
12167
12168   case ISD::CONCAT_VECTORS: {
12169     EVT OpVT = V->getOperand(0).getValueType();
12170     int OpSize = OpVT.getVectorNumElements();
12171     SmallBitVector OpUsedElements(OpSize, false);
12172     bool FoundSimplification = false;
12173     SmallVector<SDValue, 4> NewOps;
12174     NewOps.reserve(V->getNumOperands());
12175     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12176       SDValue Op = V->getOperand(i);
12177       bool OpUsed = false;
12178       for (int j = 0; j < OpSize; ++j)
12179         if (UsedElements[i * OpSize + j]) {
12180           OpUsedElements[j] = true;
12181           OpUsed = true;
12182         }
12183       NewOps.push_back(
12184           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12185                  : DAG.getUNDEF(OpVT));
12186       FoundSimplification |= Op == NewOps.back();
12187       OpUsedElements.reset();
12188     }
12189     if (FoundSimplification)
12190       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12191     return V;
12192   }
12193
12194   case ISD::INSERT_SUBVECTOR: {
12195     SDValue BaseV = V->getOperand(0);
12196     SDValue SubV = V->getOperand(1);
12197     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12198     if (!IdxN)
12199       return V;
12200
12201     int SubSize = SubV.getValueType().getVectorNumElements();
12202     int Idx = IdxN->getZExtValue();
12203     bool SubVectorUsed = false;
12204     SmallBitVector SubUsedElements(SubSize, false);
12205     for (int i = 0; i < SubSize; ++i)
12206       if (UsedElements[i + Idx]) {
12207         SubVectorUsed = true;
12208         SubUsedElements[i] = true;
12209         UsedElements[i + Idx] = false;
12210       }
12211
12212     // Now recurse on both the base and sub vectors.
12213     SDValue SimplifiedSubV =
12214         SubVectorUsed
12215             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12216             : DAG.getUNDEF(SubV.getValueType());
12217     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12218     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12219       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12220                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12221     return V;
12222   }
12223   }
12224 }
12225
12226 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12227                                        SDValue N1, SelectionDAG &DAG) {
12228   EVT VT = SVN->getValueType(0);
12229   int NumElts = VT.getVectorNumElements();
12230   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12231   for (int M : SVN->getMask())
12232     if (M >= 0 && M < NumElts)
12233       N0UsedElements[M] = true;
12234     else if (M >= NumElts)
12235       N1UsedElements[M - NumElts] = true;
12236
12237   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12238   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12239   if (S0 == N0 && S1 == N1)
12240     return SDValue();
12241
12242   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12243 }
12244
12245 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12246 // or turn a shuffle of a single concat into simpler shuffle then concat.
12247 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12248   EVT VT = N->getValueType(0);
12249   unsigned NumElts = VT.getVectorNumElements();
12250
12251   SDValue N0 = N->getOperand(0);
12252   SDValue N1 = N->getOperand(1);
12253   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12254
12255   SmallVector<SDValue, 4> Ops;
12256   EVT ConcatVT = N0.getOperand(0).getValueType();
12257   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12258   unsigned NumConcats = NumElts / NumElemsPerConcat;
12259
12260   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12261   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12262   // half vector elements.
12263   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12264       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12265                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12266     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12267                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12268     N1 = DAG.getUNDEF(ConcatVT);
12269     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12270   }
12271
12272   // Look at every vector that's inserted. We're looking for exact
12273   // subvector-sized copies from a concatenated vector
12274   for (unsigned I = 0; I != NumConcats; ++I) {
12275     // Make sure we're dealing with a copy.
12276     unsigned Begin = I * NumElemsPerConcat;
12277     bool AllUndef = true, NoUndef = true;
12278     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12279       if (SVN->getMaskElt(J) >= 0)
12280         AllUndef = false;
12281       else
12282         NoUndef = false;
12283     }
12284
12285     if (NoUndef) {
12286       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12287         return SDValue();
12288
12289       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12290         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12291           return SDValue();
12292
12293       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12294       if (FirstElt < N0.getNumOperands())
12295         Ops.push_back(N0.getOperand(FirstElt));
12296       else
12297         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12298
12299     } else if (AllUndef) {
12300       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12301     } else { // Mixed with general masks and undefs, can't do optimization.
12302       return SDValue();
12303     }
12304   }
12305
12306   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12307 }
12308
12309 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12310   EVT VT = N->getValueType(0);
12311   unsigned NumElts = VT.getVectorNumElements();
12312
12313   SDValue N0 = N->getOperand(0);
12314   SDValue N1 = N->getOperand(1);
12315
12316   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12317
12318   // Canonicalize shuffle undef, undef -> undef
12319   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12320     return DAG.getUNDEF(VT);
12321
12322   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12323
12324   // Canonicalize shuffle v, v -> v, undef
12325   if (N0 == N1) {
12326     SmallVector<int, 8> NewMask;
12327     for (unsigned i = 0; i != NumElts; ++i) {
12328       int Idx = SVN->getMaskElt(i);
12329       if (Idx >= (int)NumElts) Idx -= NumElts;
12330       NewMask.push_back(Idx);
12331     }
12332     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12333                                 &NewMask[0]);
12334   }
12335
12336   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12337   if (N0.getOpcode() == ISD::UNDEF) {
12338     SmallVector<int, 8> NewMask;
12339     for (unsigned i = 0; i != NumElts; ++i) {
12340       int Idx = SVN->getMaskElt(i);
12341       if (Idx >= 0) {
12342         if (Idx >= (int)NumElts)
12343           Idx -= NumElts;
12344         else
12345           Idx = -1; // remove reference to lhs
12346       }
12347       NewMask.push_back(Idx);
12348     }
12349     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12350                                 &NewMask[0]);
12351   }
12352
12353   // Remove references to rhs if it is undef
12354   if (N1.getOpcode() == ISD::UNDEF) {
12355     bool Changed = false;
12356     SmallVector<int, 8> NewMask;
12357     for (unsigned i = 0; i != NumElts; ++i) {
12358       int Idx = SVN->getMaskElt(i);
12359       if (Idx >= (int)NumElts) {
12360         Idx = -1;
12361         Changed = true;
12362       }
12363       NewMask.push_back(Idx);
12364     }
12365     if (Changed)
12366       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12367   }
12368
12369   // If it is a splat, check if the argument vector is another splat or a
12370   // build_vector.
12371   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12372     SDNode *V = N0.getNode();
12373
12374     // If this is a bit convert that changes the element type of the vector but
12375     // not the number of vector elements, look through it.  Be careful not to
12376     // look though conversions that change things like v4f32 to v2f64.
12377     if (V->getOpcode() == ISD::BITCAST) {
12378       SDValue ConvInput = V->getOperand(0);
12379       if (ConvInput.getValueType().isVector() &&
12380           ConvInput.getValueType().getVectorNumElements() == NumElts)
12381         V = ConvInput.getNode();
12382     }
12383
12384     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12385       assert(V->getNumOperands() == NumElts &&
12386              "BUILD_VECTOR has wrong number of operands");
12387       SDValue Base;
12388       bool AllSame = true;
12389       for (unsigned i = 0; i != NumElts; ++i) {
12390         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12391           Base = V->getOperand(i);
12392           break;
12393         }
12394       }
12395       // Splat of <u, u, u, u>, return <u, u, u, u>
12396       if (!Base.getNode())
12397         return N0;
12398       for (unsigned i = 0; i != NumElts; ++i) {
12399         if (V->getOperand(i) != Base) {
12400           AllSame = false;
12401           break;
12402         }
12403       }
12404       // Splat of <x, x, x, x>, return <x, x, x, x>
12405       if (AllSame)
12406         return N0;
12407
12408       // Canonicalize any other splat as a build_vector.
12409       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12410       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12411       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12412                                   V->getValueType(0), Ops);
12413
12414       // We may have jumped through bitcasts, so the type of the
12415       // BUILD_VECTOR may not match the type of the shuffle.
12416       if (V->getValueType(0) != VT)
12417         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12418       return NewBV;
12419     }
12420   }
12421
12422   // There are various patterns used to build up a vector from smaller vectors,
12423   // subvectors, or elements. Scan chains of these and replace unused insertions
12424   // or components with undef.
12425   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12426     return S;
12427
12428   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12429       Level < AfterLegalizeVectorOps &&
12430       (N1.getOpcode() == ISD::UNDEF ||
12431       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12432        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12433     SDValue V = partitionShuffleOfConcats(N, DAG);
12434
12435     if (V.getNode())
12436       return V;
12437   }
12438
12439   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12440   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12441   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12442     SmallVector<SDValue, 8> Ops;
12443     for (int M : SVN->getMask()) {
12444       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12445       if (M >= 0) {
12446         int Idx = M % NumElts;
12447         SDValue &S = (M < (int)NumElts ? N0 : N1);
12448         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12449           Op = S.getOperand(Idx);
12450         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12451           if (Idx == 0)
12452             Op = S.getOperand(0);
12453         } else {
12454           // Operand can't be combined - bail out.
12455           break;
12456         }
12457       }
12458       Ops.push_back(Op);
12459     }
12460     if (Ops.size() == VT.getVectorNumElements()) {
12461       // BUILD_VECTOR requires all inputs to be of the same type, find the
12462       // maximum type and extend them all.
12463       EVT SVT = VT.getScalarType();
12464       if (SVT.isInteger())
12465         for (SDValue &Op : Ops)
12466           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12467       if (SVT != VT.getScalarType())
12468         for (SDValue &Op : Ops)
12469           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12470                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12471                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12472       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12473     }
12474   }
12475
12476   // If this shuffle only has a single input that is a bitcasted shuffle,
12477   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12478   // back to their original types.
12479   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12480       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12481       TLI.isTypeLegal(VT)) {
12482
12483     // Peek through the bitcast only if there is one user.
12484     SDValue BC0 = N0;
12485     while (BC0.getOpcode() == ISD::BITCAST) {
12486       if (!BC0.hasOneUse())
12487         break;
12488       BC0 = BC0.getOperand(0);
12489     }
12490
12491     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12492       if (Scale == 1)
12493         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12494
12495       SmallVector<int, 8> NewMask;
12496       for (int M : Mask)
12497         for (int s = 0; s != Scale; ++s)
12498           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12499       return NewMask;
12500     };
12501
12502     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12503       EVT SVT = VT.getScalarType();
12504       EVT InnerVT = BC0->getValueType(0);
12505       EVT InnerSVT = InnerVT.getScalarType();
12506
12507       // Determine which shuffle works with the smaller scalar type.
12508       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12509       EVT ScaleSVT = ScaleVT.getScalarType();
12510
12511       if (TLI.isTypeLegal(ScaleVT) &&
12512           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12513           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12514
12515         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12516         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12517
12518         // Scale the shuffle masks to the smaller scalar type.
12519         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12520         SmallVector<int, 8> InnerMask =
12521             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12522         SmallVector<int, 8> OuterMask =
12523             ScaleShuffleMask(SVN->getMask(), OuterScale);
12524
12525         // Merge the shuffle masks.
12526         SmallVector<int, 8> NewMask;
12527         for (int M : OuterMask)
12528           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12529
12530         // Test for shuffle mask legality over both commutations.
12531         SDValue SV0 = BC0->getOperand(0);
12532         SDValue SV1 = BC0->getOperand(1);
12533         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12534         if (!LegalMask) {
12535           std::swap(SV0, SV1);
12536           ShuffleVectorSDNode::commuteMask(NewMask);
12537           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12538         }
12539
12540         if (LegalMask) {
12541           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12542           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12543           return DAG.getNode(
12544               ISD::BITCAST, SDLoc(N), VT,
12545               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12546         }
12547       }
12548     }
12549   }
12550
12551   // Canonicalize shuffles according to rules:
12552   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12553   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12554   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12555   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12556       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12557       TLI.isTypeLegal(VT)) {
12558     // The incoming shuffle must be of the same type as the result of the
12559     // current shuffle.
12560     assert(N1->getOperand(0).getValueType() == VT &&
12561            "Shuffle types don't match");
12562
12563     SDValue SV0 = N1->getOperand(0);
12564     SDValue SV1 = N1->getOperand(1);
12565     bool HasSameOp0 = N0 == SV0;
12566     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12567     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12568       // Commute the operands of this shuffle so that next rule
12569       // will trigger.
12570       return DAG.getCommutedVectorShuffle(*SVN);
12571   }
12572
12573   // Try to fold according to rules:
12574   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12575   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12576   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12577   // Don't try to fold shuffles with illegal type.
12578   // Only fold if this shuffle is the only user of the other shuffle.
12579   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12580       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12581     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12582
12583     // The incoming shuffle must be of the same type as the result of the
12584     // current shuffle.
12585     assert(OtherSV->getOperand(0).getValueType() == VT &&
12586            "Shuffle types don't match");
12587
12588     SDValue SV0, SV1;
12589     SmallVector<int, 4> Mask;
12590     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12591     // operand, and SV1 as the second operand.
12592     for (unsigned i = 0; i != NumElts; ++i) {
12593       int Idx = SVN->getMaskElt(i);
12594       if (Idx < 0) {
12595         // Propagate Undef.
12596         Mask.push_back(Idx);
12597         continue;
12598       }
12599
12600       SDValue CurrentVec;
12601       if (Idx < (int)NumElts) {
12602         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12603         // shuffle mask to identify which vector is actually referenced.
12604         Idx = OtherSV->getMaskElt(Idx);
12605         if (Idx < 0) {
12606           // Propagate Undef.
12607           Mask.push_back(Idx);
12608           continue;
12609         }
12610
12611         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12612                                            : OtherSV->getOperand(1);
12613       } else {
12614         // This shuffle index references an element within N1.
12615         CurrentVec = N1;
12616       }
12617
12618       // Simple case where 'CurrentVec' is UNDEF.
12619       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12620         Mask.push_back(-1);
12621         continue;
12622       }
12623
12624       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12625       // will be the first or second operand of the combined shuffle.
12626       Idx = Idx % NumElts;
12627       if (!SV0.getNode() || SV0 == CurrentVec) {
12628         // Ok. CurrentVec is the left hand side.
12629         // Update the mask accordingly.
12630         SV0 = CurrentVec;
12631         Mask.push_back(Idx);
12632         continue;
12633       }
12634
12635       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12636       if (SV1.getNode() && SV1 != CurrentVec)
12637         return SDValue();
12638
12639       // Ok. CurrentVec is the right hand side.
12640       // Update the mask accordingly.
12641       SV1 = CurrentVec;
12642       Mask.push_back(Idx + NumElts);
12643     }
12644
12645     // Check if all indices in Mask are Undef. In case, propagate Undef.
12646     bool isUndefMask = true;
12647     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12648       isUndefMask &= Mask[i] < 0;
12649
12650     if (isUndefMask)
12651       return DAG.getUNDEF(VT);
12652
12653     if (!SV0.getNode())
12654       SV0 = DAG.getUNDEF(VT);
12655     if (!SV1.getNode())
12656       SV1 = DAG.getUNDEF(VT);
12657
12658     // Avoid introducing shuffles with illegal mask.
12659     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12660       ShuffleVectorSDNode::commuteMask(Mask);
12661
12662       if (!TLI.isShuffleMaskLegal(Mask, VT))
12663         return SDValue();
12664
12665       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12666       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12667       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12668       std::swap(SV0, SV1);
12669     }
12670
12671     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12672     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12673     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12674     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12675   }
12676
12677   return SDValue();
12678 }
12679
12680 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12681   SDValue InVal = N->getOperand(0);
12682   EVT VT = N->getValueType(0);
12683
12684   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12685   // with a VECTOR_SHUFFLE.
12686   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12687     SDValue InVec = InVal->getOperand(0);
12688     SDValue EltNo = InVal->getOperand(1);
12689
12690     // FIXME: We could support implicit truncation if the shuffle can be
12691     // scaled to a smaller vector scalar type.
12692     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12693     if (C0 && VT == InVec.getValueType() &&
12694         VT.getScalarType() == InVal.getValueType()) {
12695       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12696       int Elt = C0->getZExtValue();
12697       NewMask[0] = Elt;
12698
12699       if (TLI.isShuffleMaskLegal(NewMask, VT))
12700         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12701                                     NewMask);
12702     }
12703   }
12704
12705   return SDValue();
12706 }
12707
12708 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12709   SDValue N0 = N->getOperand(0);
12710   SDValue N2 = N->getOperand(2);
12711
12712   // If the input vector is a concatenation, and the insert replaces
12713   // one of the halves, we can optimize into a single concat_vectors.
12714   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12715       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12716     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12717     EVT VT = N->getValueType(0);
12718
12719     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12720     // (concat_vectors Z, Y)
12721     if (InsIdx == 0)
12722       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12723                          N->getOperand(1), N0.getOperand(1));
12724
12725     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12726     // (concat_vectors X, Z)
12727     if (InsIdx == VT.getVectorNumElements()/2)
12728       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12729                          N0.getOperand(0), N->getOperand(1));
12730   }
12731
12732   return SDValue();
12733 }
12734
12735 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12736   SDValue N0 = N->getOperand(0);
12737
12738   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12739   if (N0->getOpcode() == ISD::FP16_TO_FP)
12740     return N0->getOperand(0);
12741
12742   return SDValue();
12743 }
12744
12745 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12746 /// with the destination vector and a zero vector.
12747 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12748 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12749 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12750   EVT VT = N->getValueType(0);
12751   SDValue LHS = N->getOperand(0);
12752   SDValue RHS = N->getOperand(1);
12753   SDLoc dl(N);
12754
12755   // Make sure we're not running after operation legalization where it 
12756   // may have custom lowered the vector shuffles.
12757   if (LegalOperations)
12758     return SDValue();
12759
12760   if (N->getOpcode() != ISD::AND)
12761     return SDValue();
12762
12763   if (RHS.getOpcode() == ISD::BITCAST)
12764     RHS = RHS.getOperand(0);
12765
12766   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12767     SmallVector<int, 8> Indices;
12768     unsigned NumElts = RHS.getNumOperands();
12769
12770     for (unsigned i = 0; i != NumElts; ++i) {
12771       SDValue Elt = RHS.getOperand(i);
12772       if (!isa<ConstantSDNode>(Elt))
12773         return SDValue();
12774
12775       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12776         Indices.push_back(i);
12777       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12778         Indices.push_back(NumElts+i);
12779       else
12780         return SDValue();
12781     }
12782
12783     // Let's see if the target supports this vector_shuffle.
12784     EVT RVT = RHS.getValueType();
12785     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12786       return SDValue();
12787
12788     // Return the new VECTOR_SHUFFLE node.
12789     EVT EltVT = RVT.getVectorElementType();
12790     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12791                                    DAG.getConstant(0, dl, EltVT));
12792     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12793     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12794     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12795     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12796   }
12797
12798   return SDValue();
12799 }
12800
12801 /// Visit a binary vector operation, like ADD.
12802 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12803   assert(N->getValueType(0).isVector() &&
12804          "SimplifyVBinOp only works on vectors!");
12805
12806   SDValue LHS = N->getOperand(0);
12807   SDValue RHS = N->getOperand(1);
12808
12809   if (SDValue Shuffle = XformToShuffleWithZero(N))
12810     return Shuffle;
12811
12812   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12813   // this operation.
12814   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12815       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12816     // Check if both vectors are constants. If not bail out.
12817     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12818           cast<BuildVectorSDNode>(RHS)->isConstant()))
12819       return SDValue();
12820
12821     SmallVector<SDValue, 8> Ops;
12822     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12823       SDValue LHSOp = LHS.getOperand(i);
12824       SDValue RHSOp = RHS.getOperand(i);
12825
12826       // Can't fold divide by zero.
12827       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12828           N->getOpcode() == ISD::FDIV) {
12829         if ((RHSOp.getOpcode() == ISD::Constant &&
12830              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12831             (RHSOp.getOpcode() == ISD::ConstantFP &&
12832              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12833           break;
12834       }
12835
12836       EVT VT = LHSOp.getValueType();
12837       EVT RVT = RHSOp.getValueType();
12838       if (RVT != VT) {
12839         // Integer BUILD_VECTOR operands may have types larger than the element
12840         // size (e.g., when the element type is not legal).  Prior to type
12841         // legalization, the types may not match between the two BUILD_VECTORS.
12842         // Truncate one of the operands to make them match.
12843         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12844           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12845         } else {
12846           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12847           VT = RVT;
12848         }
12849       }
12850       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12851                                    LHSOp, RHSOp);
12852       if (FoldOp.getOpcode() != ISD::UNDEF &&
12853           FoldOp.getOpcode() != ISD::Constant &&
12854           FoldOp.getOpcode() != ISD::ConstantFP)
12855         break;
12856       Ops.push_back(FoldOp);
12857       AddToWorklist(FoldOp.getNode());
12858     }
12859
12860     if (Ops.size() == LHS.getNumOperands())
12861       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12862   }
12863
12864   // Type legalization might introduce new shuffles in the DAG.
12865   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12866   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12867   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12868       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12869       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12870       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12871     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12872     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12873
12874     if (SVN0->getMask().equals(SVN1->getMask())) {
12875       EVT VT = N->getValueType(0);
12876       SDValue UndefVector = LHS.getOperand(1);
12877       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12878                                      LHS.getOperand(0), RHS.getOperand(0));
12879       AddUsersToWorklist(N);
12880       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12881                                   &SVN0->getMask()[0]);
12882     }
12883   }
12884
12885   return SDValue();
12886 }
12887
12888 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12889                                     SDValue N1, SDValue N2){
12890   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12891
12892   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12893                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12894
12895   // If we got a simplified select_cc node back from SimplifySelectCC, then
12896   // break it down into a new SETCC node, and a new SELECT node, and then return
12897   // the SELECT node, since we were called with a SELECT node.
12898   if (SCC.getNode()) {
12899     // Check to see if we got a select_cc back (to turn into setcc/select).
12900     // Otherwise, just return whatever node we got back, like fabs.
12901     if (SCC.getOpcode() == ISD::SELECT_CC) {
12902       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12903                                   N0.getValueType(),
12904                                   SCC.getOperand(0), SCC.getOperand(1),
12905                                   SCC.getOperand(4));
12906       AddToWorklist(SETCC.getNode());
12907       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12908                            SCC.getOperand(2), SCC.getOperand(3));
12909     }
12910
12911     return SCC;
12912   }
12913   return SDValue();
12914 }
12915
12916 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12917 /// being selected between, see if we can simplify the select.  Callers of this
12918 /// should assume that TheSelect is deleted if this returns true.  As such, they
12919 /// should return the appropriate thing (e.g. the node) back to the top-level of
12920 /// the DAG combiner loop to avoid it being looked at.
12921 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12922                                     SDValue RHS) {
12923
12924   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12925   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
12926   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
12927     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
12928       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
12929       SDValue Sqrt = RHS;
12930       ISD::CondCode CC;
12931       SDValue CmpLHS;
12932       const ConstantFPSDNode *NegZero = nullptr;
12933
12934       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
12935         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
12936         CmpLHS = TheSelect->getOperand(0);
12937         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
12938       } else {
12939         // SELECT or VSELECT
12940         SDValue Cmp = TheSelect->getOperand(0);
12941         if (Cmp.getOpcode() == ISD::SETCC) {
12942           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
12943           CmpLHS = Cmp.getOperand(0);
12944           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
12945         }
12946       }
12947       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
12948           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
12949           CC == ISD::SETULT || CC == ISD::SETLT)) {
12950         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12951         CombineTo(TheSelect, Sqrt);
12952         return true;
12953       }
12954     }
12955   }
12956   // Cannot simplify select with vector condition
12957   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12958
12959   // If this is a select from two identical things, try to pull the operation
12960   // through the select.
12961   if (LHS.getOpcode() != RHS.getOpcode() ||
12962       !LHS.hasOneUse() || !RHS.hasOneUse())
12963     return false;
12964
12965   // If this is a load and the token chain is identical, replace the select
12966   // of two loads with a load through a select of the address to load from.
12967   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12968   // constants have been dropped into the constant pool.
12969   if (LHS.getOpcode() == ISD::LOAD) {
12970     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12971     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12972
12973     // Token chains must be identical.
12974     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12975         // Do not let this transformation reduce the number of volatile loads.
12976         LLD->isVolatile() || RLD->isVolatile() ||
12977         // FIXME: If either is a pre/post inc/dec load,
12978         // we'd need to split out the address adjustment.
12979         LLD->isIndexed() || RLD->isIndexed() ||
12980         // If this is an EXTLOAD, the VT's must match.
12981         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12982         // If this is an EXTLOAD, the kind of extension must match.
12983         (LLD->getExtensionType() != RLD->getExtensionType() &&
12984          // The only exception is if one of the extensions is anyext.
12985          LLD->getExtensionType() != ISD::EXTLOAD &&
12986          RLD->getExtensionType() != ISD::EXTLOAD) ||
12987         // FIXME: this discards src value information.  This is
12988         // over-conservative. It would be beneficial to be able to remember
12989         // both potential memory locations.  Since we are discarding
12990         // src value info, don't do the transformation if the memory
12991         // locations are not in the default address space.
12992         LLD->getPointerInfo().getAddrSpace() != 0 ||
12993         RLD->getPointerInfo().getAddrSpace() != 0 ||
12994         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12995                                       LLD->getBasePtr().getValueType()))
12996       return false;
12997
12998     // Check that the select condition doesn't reach either load.  If so,
12999     // folding this will induce a cycle into the DAG.  If not, this is safe to
13000     // xform, so create a select of the addresses.
13001     SDValue Addr;
13002     if (TheSelect->getOpcode() == ISD::SELECT) {
13003       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13004       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13005           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13006         return false;
13007       // The loads must not depend on one another.
13008       if (LLD->isPredecessorOf(RLD) ||
13009           RLD->isPredecessorOf(LLD))
13010         return false;
13011       Addr = DAG.getSelect(SDLoc(TheSelect),
13012                            LLD->getBasePtr().getValueType(),
13013                            TheSelect->getOperand(0), LLD->getBasePtr(),
13014                            RLD->getBasePtr());
13015     } else {  // Otherwise SELECT_CC
13016       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13017       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13018
13019       if ((LLD->hasAnyUseOfValue(1) &&
13020            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13021           (RLD->hasAnyUseOfValue(1) &&
13022            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13023         return false;
13024
13025       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13026                          LLD->getBasePtr().getValueType(),
13027                          TheSelect->getOperand(0),
13028                          TheSelect->getOperand(1),
13029                          LLD->getBasePtr(), RLD->getBasePtr(),
13030                          TheSelect->getOperand(4));
13031     }
13032
13033     SDValue Load;
13034     // It is safe to replace the two loads if they have different alignments,
13035     // but the new load must be the minimum (most restrictive) alignment of the
13036     // inputs.
13037     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13038     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13039     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13040       Load = DAG.getLoad(TheSelect->getValueType(0),
13041                          SDLoc(TheSelect),
13042                          // FIXME: Discards pointer and AA info.
13043                          LLD->getChain(), Addr, MachinePointerInfo(),
13044                          LLD->isVolatile(), LLD->isNonTemporal(),
13045                          isInvariant, Alignment);
13046     } else {
13047       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13048                             RLD->getExtensionType() : LLD->getExtensionType(),
13049                             SDLoc(TheSelect),
13050                             TheSelect->getValueType(0),
13051                             // FIXME: Discards pointer and AA info.
13052                             LLD->getChain(), Addr, MachinePointerInfo(),
13053                             LLD->getMemoryVT(), LLD->isVolatile(),
13054                             LLD->isNonTemporal(), isInvariant, Alignment);
13055     }
13056
13057     // Users of the select now use the result of the load.
13058     CombineTo(TheSelect, Load);
13059
13060     // Users of the old loads now use the new load's chain.  We know the
13061     // old-load value is dead now.
13062     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13063     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13064     return true;
13065   }
13066
13067   return false;
13068 }
13069
13070 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13071 /// where 'cond' is the comparison specified by CC.
13072 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13073                                       SDValue N2, SDValue N3,
13074                                       ISD::CondCode CC, bool NotExtCompare) {
13075   // (x ? y : y) -> y.
13076   if (N2 == N3) return N2;
13077
13078   EVT VT = N2.getValueType();
13079   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13080   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13081   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13082
13083   // Determine if the condition we're dealing with is constant
13084   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13085                               N0, N1, CC, DL, false);
13086   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13087   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13088
13089   // fold select_cc true, x, y -> x
13090   if (SCCC && !SCCC->isNullValue())
13091     return N2;
13092   // fold select_cc false, x, y -> y
13093   if (SCCC && SCCC->isNullValue())
13094     return N3;
13095
13096   // Check to see if we can simplify the select into an fabs node
13097   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13098     // Allow either -0.0 or 0.0
13099     if (CFP->getValueAPF().isZero()) {
13100       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13101       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13102           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13103           N2 == N3.getOperand(0))
13104         return DAG.getNode(ISD::FABS, DL, VT, N0);
13105
13106       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13107       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13108           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13109           N2.getOperand(0) == N3)
13110         return DAG.getNode(ISD::FABS, DL, VT, N3);
13111     }
13112   }
13113
13114   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13115   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13116   // in it.  This is a win when the constant is not otherwise available because
13117   // it replaces two constant pool loads with one.  We only do this if the FP
13118   // type is known to be legal, because if it isn't, then we are before legalize
13119   // types an we want the other legalization to happen first (e.g. to avoid
13120   // messing with soft float) and if the ConstantFP is not legal, because if
13121   // it is legal, we may not need to store the FP constant in a constant pool.
13122   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13123     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13124       if (TLI.isTypeLegal(N2.getValueType()) &&
13125           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13126                TargetLowering::Legal &&
13127            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13128            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13129           // If both constants have multiple uses, then we won't need to do an
13130           // extra load, they are likely around in registers for other users.
13131           (TV->hasOneUse() || FV->hasOneUse())) {
13132         Constant *Elts[] = {
13133           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13134           const_cast<ConstantFP*>(TV->getConstantFPValue())
13135         };
13136         Type *FPTy = Elts[0]->getType();
13137         const DataLayout &TD = *TLI.getDataLayout();
13138
13139         // Create a ConstantArray of the two constants.
13140         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13141         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13142                                             TD.getPrefTypeAlignment(FPTy));
13143         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13144
13145         // Get the offsets to the 0 and 1 element of the array so that we can
13146         // select between them.
13147         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13148         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13149         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13150
13151         SDValue Cond = DAG.getSetCC(DL,
13152                                     getSetCCResultType(N0.getValueType()),
13153                                     N0, N1, CC);
13154         AddToWorklist(Cond.getNode());
13155         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13156                                           Cond, One, Zero);
13157         AddToWorklist(CstOffset.getNode());
13158         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13159                             CstOffset);
13160         AddToWorklist(CPIdx.getNode());
13161         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13162                            MachinePointerInfo::getConstantPool(), false,
13163                            false, false, Alignment);
13164       }
13165     }
13166
13167   // Check to see if we can perform the "gzip trick", transforming
13168   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13169   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13170       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13171        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13172     EVT XType = N0.getValueType();
13173     EVT AType = N2.getValueType();
13174     if (XType.bitsGE(AType)) {
13175       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13176       // single-bit constant.
13177       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13178         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13179         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13180         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13181                                        getShiftAmountTy(N0.getValueType()));
13182         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13183                                     XType, N0, ShCt);
13184         AddToWorklist(Shift.getNode());
13185
13186         if (XType.bitsGT(AType)) {
13187           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13188           AddToWorklist(Shift.getNode());
13189         }
13190
13191         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13192       }
13193
13194       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13195                                   XType, N0,
13196                                   DAG.getConstant(XType.getSizeInBits() - 1,
13197                                                   SDLoc(N0),
13198                                          getShiftAmountTy(N0.getValueType())));
13199       AddToWorklist(Shift.getNode());
13200
13201       if (XType.bitsGT(AType)) {
13202         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13203         AddToWorklist(Shift.getNode());
13204       }
13205
13206       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13207     }
13208   }
13209
13210   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13211   // where y is has a single bit set.
13212   // A plaintext description would be, we can turn the SELECT_CC into an AND
13213   // when the condition can be materialized as an all-ones register.  Any
13214   // single bit-test can be materialized as an all-ones register with
13215   // shift-left and shift-right-arith.
13216   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13217       N0->getValueType(0) == VT &&
13218       N1C && N1C->isNullValue() &&
13219       N2C && N2C->isNullValue()) {
13220     SDValue AndLHS = N0->getOperand(0);
13221     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13222     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13223       // Shift the tested bit over the sign bit.
13224       APInt AndMask = ConstAndRHS->getAPIntValue();
13225       SDValue ShlAmt =
13226         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13227                         getShiftAmountTy(AndLHS.getValueType()));
13228       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13229
13230       // Now arithmetic right shift it all the way over, so the result is either
13231       // all-ones, or zero.
13232       SDValue ShrAmt =
13233         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13234                         getShiftAmountTy(Shl.getValueType()));
13235       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13236
13237       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13238     }
13239   }
13240
13241   // fold select C, 16, 0 -> shl C, 4
13242   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13243       TLI.getBooleanContents(N0.getValueType()) ==
13244           TargetLowering::ZeroOrOneBooleanContent) {
13245
13246     // If the caller doesn't want us to simplify this into a zext of a compare,
13247     // don't do it.
13248     if (NotExtCompare && N2C->getAPIntValue() == 1)
13249       return SDValue();
13250
13251     // Get a SetCC of the condition
13252     // NOTE: Don't create a SETCC if it's not legal on this target.
13253     if (!LegalOperations ||
13254         TLI.isOperationLegal(ISD::SETCC,
13255           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13256       SDValue Temp, SCC;
13257       // cast from setcc result type to select result type
13258       if (LegalTypes) {
13259         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13260                             N0, N1, CC);
13261         if (N2.getValueType().bitsLT(SCC.getValueType()))
13262           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13263                                         N2.getValueType());
13264         else
13265           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13266                              N2.getValueType(), SCC);
13267       } else {
13268         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13269         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13270                            N2.getValueType(), SCC);
13271       }
13272
13273       AddToWorklist(SCC.getNode());
13274       AddToWorklist(Temp.getNode());
13275
13276       if (N2C->getAPIntValue() == 1)
13277         return Temp;
13278
13279       // shl setcc result by log2 n2c
13280       return DAG.getNode(
13281           ISD::SHL, DL, N2.getValueType(), Temp,
13282           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13283                           getShiftAmountTy(Temp.getValueType())));
13284     }
13285   }
13286
13287   // Check to see if this is the equivalent of setcc
13288   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13289   // otherwise, go ahead with the folds.
13290   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13291     EVT XType = N0.getValueType();
13292     if (!LegalOperations ||
13293         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13294       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13295       if (Res.getValueType() != VT)
13296         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13297       return Res;
13298     }
13299
13300     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13301     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13302         (!LegalOperations ||
13303          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13304       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13305       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13306                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13307                                          SDLoc(Ctlz),
13308                                        getShiftAmountTy(Ctlz.getValueType())));
13309     }
13310     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13311     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13312       SDLoc DL(N0);
13313       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13314                                   XType, DAG.getConstant(0, DL, XType), N0);
13315       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13316       return DAG.getNode(ISD::SRL, DL, XType,
13317                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13318                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13319                                          getShiftAmountTy(XType)));
13320     }
13321     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13322     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13323       SDLoc DL(N0);
13324       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13325                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13326                                          getShiftAmountTy(N0.getValueType())));
13327       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13328                                                                     XType));
13329     }
13330   }
13331
13332   // Check to see if this is an integer abs.
13333   // select_cc setg[te] X,  0,  X, -X ->
13334   // select_cc setgt    X, -1,  X, -X ->
13335   // select_cc setl[te] X,  0, -X,  X ->
13336   // select_cc setlt    X,  1, -X,  X ->
13337   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13338   if (N1C) {
13339     ConstantSDNode *SubC = nullptr;
13340     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13341          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13342         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13343       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13344     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13345               (N1C->isOne() && CC == ISD::SETLT)) &&
13346              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13347       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13348
13349     EVT XType = N0.getValueType();
13350     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13351       SDLoc DL(N0);
13352       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13353                                   N0,
13354                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13355                                          getShiftAmountTy(N0.getValueType())));
13356       SDValue Add = DAG.getNode(ISD::ADD, DL,
13357                                 XType, N0, Shift);
13358       AddToWorklist(Shift.getNode());
13359       AddToWorklist(Add.getNode());
13360       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13361     }
13362   }
13363
13364   return SDValue();
13365 }
13366
13367 /// This is a stub for TargetLowering::SimplifySetCC.
13368 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13369                                    SDValue N1, ISD::CondCode Cond,
13370                                    SDLoc DL, bool foldBooleans) {
13371   TargetLowering::DAGCombinerInfo
13372     DagCombineInfo(DAG, Level, false, this);
13373   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13374 }
13375
13376 /// Given an ISD::SDIV node expressing a divide by constant, return
13377 /// a DAG expression to select that will generate the same value by multiplying
13378 /// by a magic number.
13379 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13380 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13381   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13382   if (!C)
13383     return SDValue();
13384
13385   // Avoid division by zero.
13386   if (!C->getAPIntValue())
13387     return SDValue();
13388
13389   std::vector<SDNode*> Built;
13390   SDValue S =
13391       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13392
13393   for (SDNode *N : Built)
13394     AddToWorklist(N);
13395   return S;
13396 }
13397
13398 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13399 /// DAG expression that will generate the same value by right shifting.
13400 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13401   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13402   if (!C)
13403     return SDValue();
13404
13405   // Avoid division by zero.
13406   if (!C->getAPIntValue())
13407     return SDValue();
13408
13409   std::vector<SDNode *> Built;
13410   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13411
13412   for (SDNode *N : Built)
13413     AddToWorklist(N);
13414   return S;
13415 }
13416
13417 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13418 /// expression that will generate the same value by multiplying by a magic
13419 /// number.
13420 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13421 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13422   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13423   if (!C)
13424     return SDValue();
13425
13426   // Avoid division by zero.
13427   if (!C->getAPIntValue())
13428     return SDValue();
13429
13430   std::vector<SDNode*> Built;
13431   SDValue S =
13432       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13433
13434   for (SDNode *N : Built)
13435     AddToWorklist(N);
13436   return S;
13437 }
13438
13439 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13440   if (Level >= AfterLegalizeDAG)
13441     return SDValue();
13442
13443   // Expose the DAG combiner to the target combiner implementations.
13444   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13445
13446   unsigned Iterations = 0;
13447   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13448     if (Iterations) {
13449       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13450       // For the reciprocal, we need to find the zero of the function:
13451       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13452       //     =>
13453       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13454       //     does not require additional intermediate precision]
13455       EVT VT = Op.getValueType();
13456       SDLoc DL(Op);
13457       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13458
13459       AddToWorklist(Est.getNode());
13460
13461       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13462       for (unsigned i = 0; i < Iterations; ++i) {
13463         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13464         AddToWorklist(NewEst.getNode());
13465
13466         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13467         AddToWorklist(NewEst.getNode());
13468
13469         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13470         AddToWorklist(NewEst.getNode());
13471
13472         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13473         AddToWorklist(Est.getNode());
13474       }
13475     }
13476     return Est;
13477   }
13478
13479   return SDValue();
13480 }
13481
13482 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13483 /// For the reciprocal sqrt, we need to find the zero of the function:
13484 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13485 ///     =>
13486 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13487 /// As a result, we precompute A/2 prior to the iteration loop.
13488 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13489                                           unsigned Iterations) {
13490   EVT VT = Arg.getValueType();
13491   SDLoc DL(Arg);
13492   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13493
13494   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13495   // this entire sequence requires only one FP constant.
13496   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13497   AddToWorklist(HalfArg.getNode());
13498
13499   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13500   AddToWorklist(HalfArg.getNode());
13501
13502   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13503   for (unsigned i = 0; i < Iterations; ++i) {
13504     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13505     AddToWorklist(NewEst.getNode());
13506
13507     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13508     AddToWorklist(NewEst.getNode());
13509
13510     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13511     AddToWorklist(NewEst.getNode());
13512
13513     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13514     AddToWorklist(Est.getNode());
13515   }
13516   return Est;
13517 }
13518
13519 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13520 /// For the reciprocal sqrt, we need to find the zero of the function:
13521 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13522 ///     =>
13523 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13524 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13525                                           unsigned Iterations) {
13526   EVT VT = Arg.getValueType();
13527   SDLoc DL(Arg);
13528   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13529   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13530
13531   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13532   for (unsigned i = 0; i < Iterations; ++i) {
13533     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13534     AddToWorklist(HalfEst.getNode());
13535
13536     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13537     AddToWorklist(Est.getNode());
13538
13539     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13540     AddToWorklist(Est.getNode());
13541
13542     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13543     AddToWorklist(Est.getNode());
13544
13545     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13546     AddToWorklist(Est.getNode());
13547   }
13548   return Est;
13549 }
13550
13551 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13552   if (Level >= AfterLegalizeDAG)
13553     return SDValue();
13554
13555   // Expose the DAG combiner to the target combiner implementations.
13556   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13557   unsigned Iterations = 0;
13558   bool UseOneConstNR = false;
13559   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13560     AddToWorklist(Est.getNode());
13561     if (Iterations) {
13562       Est = UseOneConstNR ?
13563         BuildRsqrtNROneConst(Op, Est, Iterations) :
13564         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13565     }
13566     return Est;
13567   }
13568
13569   return SDValue();
13570 }
13571
13572 /// Return true if base is a frame index, which is known not to alias with
13573 /// anything but itself.  Provides base object and offset as results.
13574 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13575                            const GlobalValue *&GV, const void *&CV) {
13576   // Assume it is a primitive operation.
13577   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13578
13579   // If it's an adding a simple constant then integrate the offset.
13580   if (Base.getOpcode() == ISD::ADD) {
13581     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13582       Base = Base.getOperand(0);
13583       Offset += C->getZExtValue();
13584     }
13585   }
13586
13587   // Return the underlying GlobalValue, and update the Offset.  Return false
13588   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13589   // by multiple nodes with different offsets.
13590   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13591     GV = G->getGlobal();
13592     Offset += G->getOffset();
13593     return false;
13594   }
13595
13596   // Return the underlying Constant value, and update the Offset.  Return false
13597   // for ConstantSDNodes since the same constant pool entry may be represented
13598   // by multiple nodes with different offsets.
13599   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13600     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13601                                          : (const void *)C->getConstVal();
13602     Offset += C->getOffset();
13603     return false;
13604   }
13605   // If it's any of the following then it can't alias with anything but itself.
13606   return isa<FrameIndexSDNode>(Base);
13607 }
13608
13609 /// Return true if there is any possibility that the two addresses overlap.
13610 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13611   // If they are the same then they must be aliases.
13612   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13613
13614   // If they are both volatile then they cannot be reordered.
13615   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13616
13617   // Gather base node and offset information.
13618   SDValue Base1, Base2;
13619   int64_t Offset1, Offset2;
13620   const GlobalValue *GV1, *GV2;
13621   const void *CV1, *CV2;
13622   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13623                                       Base1, Offset1, GV1, CV1);
13624   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13625                                       Base2, Offset2, GV2, CV2);
13626
13627   // If they have a same base address then check to see if they overlap.
13628   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13629     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13630              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13631
13632   // It is possible for different frame indices to alias each other, mostly
13633   // when tail call optimization reuses return address slots for arguments.
13634   // To catch this case, look up the actual index of frame indices to compute
13635   // the real alias relationship.
13636   if (isFrameIndex1 && isFrameIndex2) {
13637     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13638     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13639     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13640     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13641              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13642   }
13643
13644   // Otherwise, if we know what the bases are, and they aren't identical, then
13645   // we know they cannot alias.
13646   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13647     return false;
13648
13649   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13650   // compared to the size and offset of the access, we may be able to prove they
13651   // do not alias.  This check is conservative for now to catch cases created by
13652   // splitting vector types.
13653   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13654       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13655       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13656        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13657       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13658     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13659     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13660
13661     // There is no overlap between these relatively aligned accesses of similar
13662     // size, return no alias.
13663     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13664         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13665       return false;
13666   }
13667
13668   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13669                    ? CombinerGlobalAA
13670                    : DAG.getSubtarget().useAA();
13671 #ifndef NDEBUG
13672   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13673       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13674     UseAA = false;
13675 #endif
13676   if (UseAA &&
13677       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13678     // Use alias analysis information.
13679     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13680                                  Op1->getSrcValueOffset());
13681     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13682         Op0->getSrcValueOffset() - MinOffset;
13683     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13684         Op1->getSrcValueOffset() - MinOffset;
13685     AliasAnalysis::AliasResult AAResult =
13686         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13687                                          Overlap1,
13688                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13689                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13690                                          Overlap2,
13691                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13692     if (AAResult == AliasAnalysis::NoAlias)
13693       return false;
13694   }
13695
13696   // Otherwise we have to assume they alias.
13697   return true;
13698 }
13699
13700 /// Walk up chain skipping non-aliasing memory nodes,
13701 /// looking for aliasing nodes and adding them to the Aliases vector.
13702 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13703                                    SmallVectorImpl<SDValue> &Aliases) {
13704   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13705   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13706
13707   // Get alias information for node.
13708   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13709
13710   // Starting off.
13711   Chains.push_back(OriginalChain);
13712   unsigned Depth = 0;
13713
13714   // Look at each chain and determine if it is an alias.  If so, add it to the
13715   // aliases list.  If not, then continue up the chain looking for the next
13716   // candidate.
13717   while (!Chains.empty()) {
13718     SDValue Chain = Chains.back();
13719     Chains.pop_back();
13720
13721     // For TokenFactor nodes, look at each operand and only continue up the
13722     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13723     // find more and revert to original chain since the xform is unlikely to be
13724     // profitable.
13725     //
13726     // FIXME: The depth check could be made to return the last non-aliasing
13727     // chain we found before we hit a tokenfactor rather than the original
13728     // chain.
13729     if (Depth > 6 || Aliases.size() == 2) {
13730       Aliases.clear();
13731       Aliases.push_back(OriginalChain);
13732       return;
13733     }
13734
13735     // Don't bother if we've been before.
13736     if (!Visited.insert(Chain.getNode()).second)
13737       continue;
13738
13739     switch (Chain.getOpcode()) {
13740     case ISD::EntryToken:
13741       // Entry token is ideal chain operand, but handled in FindBetterChain.
13742       break;
13743
13744     case ISD::LOAD:
13745     case ISD::STORE: {
13746       // Get alias information for Chain.
13747       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13748           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13749
13750       // If chain is alias then stop here.
13751       if (!(IsLoad && IsOpLoad) &&
13752           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13753         Aliases.push_back(Chain);
13754       } else {
13755         // Look further up the chain.
13756         Chains.push_back(Chain.getOperand(0));
13757         ++Depth;
13758       }
13759       break;
13760     }
13761
13762     case ISD::TokenFactor:
13763       // We have to check each of the operands of the token factor for "small"
13764       // token factors, so we queue them up.  Adding the operands to the queue
13765       // (stack) in reverse order maintains the original order and increases the
13766       // likelihood that getNode will find a matching token factor (CSE.)
13767       if (Chain.getNumOperands() > 16) {
13768         Aliases.push_back(Chain);
13769         break;
13770       }
13771       for (unsigned n = Chain.getNumOperands(); n;)
13772         Chains.push_back(Chain.getOperand(--n));
13773       ++Depth;
13774       break;
13775
13776     default:
13777       // For all other instructions we will just have to take what we can get.
13778       Aliases.push_back(Chain);
13779       break;
13780     }
13781   }
13782
13783   // We need to be careful here to also search for aliases through the
13784   // value operand of a store, etc. Consider the following situation:
13785   //   Token1 = ...
13786   //   L1 = load Token1, %52
13787   //   S1 = store Token1, L1, %51
13788   //   L2 = load Token1, %52+8
13789   //   S2 = store Token1, L2, %51+8
13790   //   Token2 = Token(S1, S2)
13791   //   L3 = load Token2, %53
13792   //   S3 = store Token2, L3, %52
13793   //   L4 = load Token2, %53+8
13794   //   S4 = store Token2, L4, %52+8
13795   // If we search for aliases of S3 (which loads address %52), and we look
13796   // only through the chain, then we'll miss the trivial dependence on L1
13797   // (which also loads from %52). We then might change all loads and
13798   // stores to use Token1 as their chain operand, which could result in
13799   // copying %53 into %52 before copying %52 into %51 (which should
13800   // happen first).
13801   //
13802   // The problem is, however, that searching for such data dependencies
13803   // can become expensive, and the cost is not directly related to the
13804   // chain depth. Instead, we'll rule out such configurations here by
13805   // insisting that we've visited all chain users (except for users
13806   // of the original chain, which is not necessary). When doing this,
13807   // we need to look through nodes we don't care about (otherwise, things
13808   // like register copies will interfere with trivial cases).
13809
13810   SmallVector<const SDNode *, 16> Worklist;
13811   for (const SDNode *N : Visited)
13812     if (N != OriginalChain.getNode())
13813       Worklist.push_back(N);
13814
13815   while (!Worklist.empty()) {
13816     const SDNode *M = Worklist.pop_back_val();
13817
13818     // We have already visited M, and want to make sure we've visited any uses
13819     // of M that we care about. For uses that we've not visisted, and don't
13820     // care about, queue them to the worklist.
13821
13822     for (SDNode::use_iterator UI = M->use_begin(),
13823          UIE = M->use_end(); UI != UIE; ++UI)
13824       if (UI.getUse().getValueType() == MVT::Other &&
13825           Visited.insert(*UI).second) {
13826         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13827           // We've not visited this use, and we care about it (it could have an
13828           // ordering dependency with the original node).
13829           Aliases.clear();
13830           Aliases.push_back(OriginalChain);
13831           return;
13832         }
13833
13834         // We've not visited this use, but we don't care about it. Mark it as
13835         // visited and enqueue it to the worklist.
13836         Worklist.push_back(*UI);
13837       }
13838   }
13839 }
13840
13841 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13842 /// (aliasing node.)
13843 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13844   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13845
13846   // Accumulate all the aliases to this node.
13847   GatherAllAliases(N, OldChain, Aliases);
13848
13849   // If no operands then chain to entry token.
13850   if (Aliases.size() == 0)
13851     return DAG.getEntryNode();
13852
13853   // If a single operand then chain to it.  We don't need to revisit it.
13854   if (Aliases.size() == 1)
13855     return Aliases[0];
13856
13857   // Construct a custom tailored token factor.
13858   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13859 }
13860
13861 /// This is the entry point for the file.
13862 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13863                            CodeGenOpt::Level OptLevel) {
13864   /// This is the main entry point to this class.
13865   DAGCombiner(*this, AA, OptLevel).Run(Level);
13866 }