[DAGCombiner] Fix wrong folding of a build_vector into a blend with zero.
[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 visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
272     SDValue visitTRUNCATE(SDNode *N);
273     SDValue visitBITCAST(SDNode *N);
274     SDValue visitBUILD_PAIR(SDNode *N);
275     SDValue visitFADD(SDNode *N);
276     SDValue visitFSUB(SDNode *N);
277     SDValue visitFMUL(SDNode *N);
278     SDValue visitFMA(SDNode *N);
279     SDValue visitFDIV(SDNode *N);
280     SDValue visitFREM(SDNode *N);
281     SDValue visitFSQRT(SDNode *N);
282     SDValue visitFCOPYSIGN(SDNode *N);
283     SDValue visitSINT_TO_FP(SDNode *N);
284     SDValue visitUINT_TO_FP(SDNode *N);
285     SDValue visitFP_TO_SINT(SDNode *N);
286     SDValue visitFP_TO_UINT(SDNode *N);
287     SDValue visitFP_ROUND(SDNode *N);
288     SDValue visitFP_ROUND_INREG(SDNode *N);
289     SDValue visitFP_EXTEND(SDNode *N);
290     SDValue visitFNEG(SDNode *N);
291     SDValue visitFABS(SDNode *N);
292     SDValue visitFCEIL(SDNode *N);
293     SDValue visitFTRUNC(SDNode *N);
294     SDValue visitFFLOOR(SDNode *N);
295     SDValue visitFMINNUM(SDNode *N);
296     SDValue visitFMAXNUM(SDNode *N);
297     SDValue visitBRCOND(SDNode *N);
298     SDValue visitBR_CC(SDNode *N);
299     SDValue visitLOAD(SDNode *N);
300     SDValue visitSTORE(SDNode *N);
301     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
302     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
303     SDValue visitBUILD_VECTOR(SDNode *N);
304     SDValue visitCONCAT_VECTORS(SDNode *N);
305     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
306     SDValue visitVECTOR_SHUFFLE(SDNode *N);
307     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
308     SDValue visitINSERT_SUBVECTOR(SDNode *N);
309     SDValue visitMLOAD(SDNode *N);
310     SDValue visitMSTORE(SDNode *N);
311     SDValue visitMGATHER(SDNode *N);
312     SDValue visitMSCATTER(SDNode *N);
313     SDValue visitFP_TO_FP16(SDNode *N);
314
315     SDValue visitFADDForFMACombine(SDNode *N);
316     SDValue visitFSUBForFMACombine(SDNode *N);
317
318     SDValue XformToShuffleWithZero(SDNode *N);
319     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
320
321     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
322
323     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
324     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
325     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
326     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
327                              SDValue N3, ISD::CondCode CC,
328                              bool NotExtCompare = false);
329     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
330                           SDLoc DL, bool foldBooleans = true);
331
332     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
333                            SDValue &CC) const;
334     bool isOneUseSetCC(SDValue N) const;
335
336     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
337                                          unsigned HiOp);
338     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
339     SDValue CombineExtLoad(SDNode *N);
340     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
341     SDValue BuildSDIV(SDNode *N);
342     SDValue BuildSDIVPow2(SDNode *N);
343     SDValue BuildUDIV(SDNode *N);
344     SDValue BuildReciprocalEstimate(SDValue Op);
345     SDValue BuildRsqrtEstimate(SDValue Op);
346     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
347     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
348     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
349                                bool DemandHighBits = true);
350     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
351     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
352                               SDValue InnerPos, SDValue InnerNeg,
353                               unsigned PosOpcode, unsigned NegOpcode,
354                               SDLoc DL);
355     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
356     SDValue ReduceLoadWidth(SDNode *N);
357     SDValue ReduceLoadOpStoreWidth(SDNode *N);
358     SDValue TransformFPLoadStorePair(SDNode *N);
359     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
360     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
361
362     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
363
364     /// Walk up chain skipping non-aliasing memory nodes,
365     /// looking for aliasing nodes and adding them to the Aliases vector.
366     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
367                           SmallVectorImpl<SDValue> &Aliases);
368
369     /// Return true if there is any possibility that the two addresses overlap.
370     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
371
372     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
373     /// chain (aliasing node.)
374     SDValue FindBetterChain(SDNode *N, SDValue Chain);
375
376     /// Holds a pointer to an LSBaseSDNode as well as information on where it
377     /// is located in a sequence of memory operations connected by a chain.
378     struct MemOpLink {
379       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
380       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
381       // Ptr to the mem node.
382       LSBaseSDNode *MemNode;
383       // Offset from the base ptr.
384       int64_t OffsetFromBase;
385       // What is the sequence number of this mem node.
386       // Lowest mem operand in the DAG starts at zero.
387       unsigned SequenceNum;
388     };
389
390     /// This is a helper function for MergeConsecutiveStores. When the source
391     /// elements of the consecutive stores are all constants or all extracted
392     /// vector elements, try to merge them into one larger store.
393     /// \return True if a merged store was created.
394     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
395                                          EVT MemVT, unsigned NumElem,
396                                          bool IsConstantSrc, bool UseVector);
397
398     /// Merge consecutive store operations into a wide store.
399     /// This optimization uses wide integers or vectors when possible.
400     /// \return True if some memory operations were changed.
401     bool MergeConsecutiveStores(StoreSDNode *N);
402
403     /// \brief Try to transform a truncation where C is a constant:
404     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
405     ///
406     /// \p N needs to be a truncation and its first operand an AND. Other
407     /// requirements are checked by the function (e.g. that trunc is
408     /// single-use) and if missed an empty SDValue is returned.
409     SDValue distributeTruncateThroughAnd(SDNode *N);
410
411   public:
412     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
413         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
414           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
415       auto *F = DAG.getMachineFunction().getFunction();
416       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
417                     F->hasFnAttribute(Attribute::MinSize);
418     }
419
420     /// Runs the dag combiner on all nodes in the work list
421     void Run(CombineLevel AtLevel);
422
423     SelectionDAG &getDAG() const { return DAG; }
424
425     /// Returns a type large enough to hold any valid shift amount - before type
426     /// legalization these can be huge.
427     EVT getShiftAmountTy(EVT LHSTy) {
428       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
429       if (LHSTy.isVector())
430         return LHSTy;
431       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
432                         : TLI.getPointerTy();
433     }
434
435     /// This method returns true if we are running before type legalization or
436     /// if the specified VT is legal.
437     bool isTypeLegal(const EVT &VT) {
438       if (!LegalTypes) return true;
439       return TLI.isTypeLegal(VT);
440     }
441
442     /// Convenience wrapper around TargetLowering::getSetCCResultType
443     EVT getSetCCResultType(EVT VT) const {
444       return TLI.getSetCCResultType(*DAG.getContext(), VT);
445     }
446   };
447 }
448
449
450 namespace {
451 /// This class is a DAGUpdateListener that removes any deleted
452 /// nodes from the worklist.
453 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
454   DAGCombiner &DC;
455 public:
456   explicit WorklistRemover(DAGCombiner &dc)
457     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
458
459   void NodeDeleted(SDNode *N, SDNode *E) override {
460     DC.removeFromWorklist(N);
461   }
462 };
463 }
464
465 //===----------------------------------------------------------------------===//
466 //  TargetLowering::DAGCombinerInfo implementation
467 //===----------------------------------------------------------------------===//
468
469 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
470   ((DAGCombiner*)DC)->AddToWorklist(N);
471 }
472
473 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
474   ((DAGCombiner*)DC)->removeFromWorklist(N);
475 }
476
477 SDValue TargetLowering::DAGCombinerInfo::
478 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
479   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
480 }
481
482 SDValue TargetLowering::DAGCombinerInfo::
483 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
484   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
485 }
486
487
488 SDValue TargetLowering::DAGCombinerInfo::
489 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
490   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
491 }
492
493 void TargetLowering::DAGCombinerInfo::
494 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
495   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
496 }
497
498 //===----------------------------------------------------------------------===//
499 // Helper Functions
500 //===----------------------------------------------------------------------===//
501
502 void DAGCombiner::deleteAndRecombine(SDNode *N) {
503   removeFromWorklist(N);
504
505   // If the operands of this node are only used by the node, they will now be
506   // dead. Make sure to re-visit them and recursively delete dead nodes.
507   for (const SDValue &Op : N->ops())
508     // For an operand generating multiple values, one of the values may
509     // become dead allowing further simplification (e.g. split index
510     // arithmetic from an indexed load).
511     if (Op->hasOneUse() || Op->getNumValues() > 1)
512       AddToWorklist(Op.getNode());
513
514   DAG.DeleteNode(N);
515 }
516
517 /// Return 1 if we can compute the negated form of the specified expression for
518 /// the same cost as the expression itself, or 2 if we can compute the negated
519 /// form more cheaply than the expression itself.
520 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
521                                const TargetLowering &TLI,
522                                const TargetOptions *Options,
523                                unsigned Depth = 0) {
524   // fneg is removable even if it has multiple uses.
525   if (Op.getOpcode() == ISD::FNEG) return 2;
526
527   // Don't allow anything with multiple uses.
528   if (!Op.hasOneUse()) return 0;
529
530   // Don't recurse exponentially.
531   if (Depth > 6) return 0;
532
533   switch (Op.getOpcode()) {
534   default: return false;
535   case ISD::ConstantFP:
536     // Don't invert constant FP values after legalize.  The negated constant
537     // isn't necessarily legal.
538     return LegalOperations ? 0 : 1;
539   case ISD::FADD:
540     // FIXME: determine better conditions for this xform.
541     if (!Options->UnsafeFPMath) return 0;
542
543     // After operation legalization, it might not be legal to create new FSUBs.
544     if (LegalOperations &&
545         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
546       return 0;
547
548     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
549     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
550                                     Options, Depth + 1))
551       return V;
552     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
553     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
554                               Depth + 1);
555   case ISD::FSUB:
556     // We can't turn -(A-B) into B-A when we honor signed zeros.
557     if (!Options->UnsafeFPMath) return 0;
558
559     // fold (fneg (fsub A, B)) -> (fsub B, A)
560     return 1;
561
562   case ISD::FMUL:
563   case ISD::FDIV:
564     if (Options->HonorSignDependentRoundingFPMath()) return 0;
565
566     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
567     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
568                                     Options, Depth + 1))
569       return V;
570
571     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
572                               Depth + 1);
573
574   case ISD::FP_EXTEND:
575   case ISD::FP_ROUND:
576   case ISD::FSIN:
577     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
578                               Depth + 1);
579   }
580 }
581
582 /// If isNegatibleForFree returns true, return the newly negated expression.
583 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
584                                     bool LegalOperations, unsigned Depth = 0) {
585   const TargetOptions &Options = DAG.getTarget().Options;
586   // fneg is removable even if it has multiple uses.
587   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
588
589   // Don't allow anything with multiple uses.
590   assert(Op.hasOneUse() && "Unknown reuse!");
591
592   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
593   switch (Op.getOpcode()) {
594   default: llvm_unreachable("Unknown code");
595   case ISD::ConstantFP: {
596     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
597     V.changeSign();
598     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
599   }
600   case ISD::FADD:
601     // FIXME: determine better conditions for this xform.
602     assert(Options.UnsafeFPMath);
603
604     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
605     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
606                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
607       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
608                          GetNegatedExpression(Op.getOperand(0), DAG,
609                                               LegalOperations, Depth+1),
610                          Op.getOperand(1));
611     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
612     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
613                        GetNegatedExpression(Op.getOperand(1), DAG,
614                                             LegalOperations, Depth+1),
615                        Op.getOperand(0));
616   case ISD::FSUB:
617     // We can't turn -(A-B) into B-A when we honor signed zeros.
618     assert(Options.UnsafeFPMath);
619
620     // fold (fneg (fsub 0, B)) -> B
621     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
622       if (N0CFP->getValueAPF().isZero())
623         return Op.getOperand(1);
624
625     // fold (fneg (fsub A, B)) -> (fsub B, A)
626     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
627                        Op.getOperand(1), Op.getOperand(0));
628
629   case ISD::FMUL:
630   case ISD::FDIV:
631     assert(!Options.HonorSignDependentRoundingFPMath());
632
633     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
634     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
635                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
636       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
637                          GetNegatedExpression(Op.getOperand(0), DAG,
638                                               LegalOperations, Depth+1),
639                          Op.getOperand(1));
640
641     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
642     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
643                        Op.getOperand(0),
644                        GetNegatedExpression(Op.getOperand(1), DAG,
645                                             LegalOperations, Depth+1));
646
647   case ISD::FP_EXTEND:
648   case ISD::FSIN:
649     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
650                        GetNegatedExpression(Op.getOperand(0), DAG,
651                                             LegalOperations, Depth+1));
652   case ISD::FP_ROUND:
653       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
654                          GetNegatedExpression(Op.getOperand(0), DAG,
655                                               LegalOperations, Depth+1),
656                          Op.getOperand(1));
657   }
658 }
659
660 // Return true if this node is a setcc, or is a select_cc
661 // that selects between the target values used for true and false, making it
662 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
663 // the appropriate nodes based on the type of node we are checking. This
664 // simplifies life a bit for the callers.
665 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
666                                     SDValue &CC) const {
667   if (N.getOpcode() == ISD::SETCC) {
668     LHS = N.getOperand(0);
669     RHS = N.getOperand(1);
670     CC  = N.getOperand(2);
671     return true;
672   }
673
674   if (N.getOpcode() != ISD::SELECT_CC ||
675       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
676       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
677     return false;
678
679   if (TLI.getBooleanContents(N.getValueType()) ==
680       TargetLowering::UndefinedBooleanContent)
681     return false;
682
683   LHS = N.getOperand(0);
684   RHS = N.getOperand(1);
685   CC  = N.getOperand(4);
686   return true;
687 }
688
689 /// Return true if this is a SetCC-equivalent operation with only one use.
690 /// If this is true, it allows the users to invert the operation for free when
691 /// it is profitable to do so.
692 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
693   SDValue N0, N1, N2;
694   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
695     return true;
696   return false;
697 }
698
699 /// Returns true if N is a BUILD_VECTOR node whose
700 /// elements are all the same constant or undefined.
701 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
702   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
703   if (!C)
704     return false;
705
706   APInt SplatUndef;
707   unsigned SplatBitSize;
708   bool HasAnyUndefs;
709   EVT EltVT = N->getValueType(0).getVectorElementType();
710   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
711                              HasAnyUndefs) &&
712           EltVT.getSizeInBits() >= SplatBitSize);
713 }
714
715 // \brief Returns the SDNode if it is a constant integer BuildVector
716 // or constant integer.
717 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
718   if (isa<ConstantSDNode>(N))
719     return N.getNode();
720   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
721     return N.getNode();
722   return nullptr;
723 }
724
725 // \brief Returns the SDNode if it is a constant float BuildVector
726 // or constant float.
727 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
728   if (isa<ConstantFPSDNode>(N))
729     return N.getNode();
730   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
731     return N.getNode();
732   return nullptr;
733 }
734
735 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
736 // int.
737 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
738   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
739     return CN;
740
741   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
742     BitVector UndefElements;
743     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
744
745     // BuildVectors can truncate their operands. Ignore that case here.
746     // FIXME: We blindly ignore splats which include undef which is overly
747     // pessimistic.
748     if (CN && UndefElements.none() &&
749         CN->getValueType(0) == N.getValueType().getScalarType())
750       return CN;
751   }
752
753   return nullptr;
754 }
755
756 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
757 // float.
758 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
759   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
760     return CN;
761
762   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
763     BitVector UndefElements;
764     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
765
766     if (CN && UndefElements.none())
767       return CN;
768   }
769
770   return nullptr;
771 }
772
773 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
774                                     SDValue N0, SDValue N1) {
775   EVT VT = N0.getValueType();
776   if (N0.getOpcode() == Opc) {
777     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
778       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
779         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
780         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
781           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
782         return SDValue();
783       }
784       if (N0.hasOneUse()) {
785         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
786         // use
787         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
788         if (!OpNode.getNode())
789           return SDValue();
790         AddToWorklist(OpNode.getNode());
791         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
792       }
793     }
794   }
795
796   if (N1.getOpcode() == Opc) {
797     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
798       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
799         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
800         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
801           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
802         return SDValue();
803       }
804       if (N1.hasOneUse()) {
805         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
806         // use
807         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
808         if (!OpNode.getNode())
809           return SDValue();
810         AddToWorklist(OpNode.getNode());
811         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
812       }
813     }
814   }
815
816   return SDValue();
817 }
818
819 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
820                                bool AddTo) {
821   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
822   ++NodesCombined;
823   DEBUG(dbgs() << "\nReplacing.1 ";
824         N->dump(&DAG);
825         dbgs() << "\nWith: ";
826         To[0].getNode()->dump(&DAG);
827         dbgs() << " and " << NumTo-1 << " other values\n");
828   for (unsigned i = 0, e = NumTo; i != e; ++i)
829     assert((!To[i].getNode() ||
830             N->getValueType(i) == To[i].getValueType()) &&
831            "Cannot combine value to value of different type!");
832
833   WorklistRemover DeadNodes(*this);
834   DAG.ReplaceAllUsesWith(N, To);
835   if (AddTo) {
836     // Push the new nodes and any users onto the worklist
837     for (unsigned i = 0, e = NumTo; i != e; ++i) {
838       if (To[i].getNode()) {
839         AddToWorklist(To[i].getNode());
840         AddUsersToWorklist(To[i].getNode());
841       }
842     }
843   }
844
845   // Finally, if the node is now dead, remove it from the graph.  The node
846   // may not be dead if the replacement process recursively simplified to
847   // something else needing this node.
848   if (N->use_empty())
849     deleteAndRecombine(N);
850   return SDValue(N, 0);
851 }
852
853 void DAGCombiner::
854 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
855   // Replace all uses.  If any nodes become isomorphic to other nodes and
856   // are deleted, make sure to remove them from our worklist.
857   WorklistRemover DeadNodes(*this);
858   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
859
860   // Push the new node and any (possibly new) users onto the worklist.
861   AddToWorklist(TLO.New.getNode());
862   AddUsersToWorklist(TLO.New.getNode());
863
864   // Finally, if the node is now dead, remove it from the graph.  The node
865   // may not be dead if the replacement process recursively simplified to
866   // something else needing this node.
867   if (TLO.Old.getNode()->use_empty())
868     deleteAndRecombine(TLO.Old.getNode());
869 }
870
871 /// Check the specified integer node value to see if it can be simplified or if
872 /// things it uses can be simplified by bit propagation. If so, return true.
873 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
874   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
875   APInt KnownZero, KnownOne;
876   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
877     return false;
878
879   // Revisit the node.
880   AddToWorklist(Op.getNode());
881
882   // Replace the old value with the new one.
883   ++NodesCombined;
884   DEBUG(dbgs() << "\nReplacing.2 ";
885         TLO.Old.getNode()->dump(&DAG);
886         dbgs() << "\nWith: ";
887         TLO.New.getNode()->dump(&DAG);
888         dbgs() << '\n');
889
890   CommitTargetLoweringOpt(TLO);
891   return true;
892 }
893
894 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
895   SDLoc dl(Load);
896   EVT VT = Load->getValueType(0);
897   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
898
899   DEBUG(dbgs() << "\nReplacing.9 ";
900         Load->dump(&DAG);
901         dbgs() << "\nWith: ";
902         Trunc.getNode()->dump(&DAG);
903         dbgs() << '\n');
904   WorklistRemover DeadNodes(*this);
905   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
906   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
907   deleteAndRecombine(Load);
908   AddToWorklist(Trunc.getNode());
909 }
910
911 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
912   Replace = false;
913   SDLoc dl(Op);
914   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
915     EVT MemVT = LD->getMemoryVT();
916     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
917       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
918                                                        : ISD::EXTLOAD)
919       : LD->getExtensionType();
920     Replace = true;
921     return DAG.getExtLoad(ExtType, dl, PVT,
922                           LD->getChain(), LD->getBasePtr(),
923                           MemVT, LD->getMemOperand());
924   }
925
926   unsigned Opc = Op.getOpcode();
927   switch (Opc) {
928   default: break;
929   case ISD::AssertSext:
930     return DAG.getNode(ISD::AssertSext, dl, PVT,
931                        SExtPromoteOperand(Op.getOperand(0), PVT),
932                        Op.getOperand(1));
933   case ISD::AssertZext:
934     return DAG.getNode(ISD::AssertZext, dl, PVT,
935                        ZExtPromoteOperand(Op.getOperand(0), PVT),
936                        Op.getOperand(1));
937   case ISD::Constant: {
938     unsigned ExtOpc =
939       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
940     return DAG.getNode(ExtOpc, dl, PVT, Op);
941   }
942   }
943
944   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
945     return SDValue();
946   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
947 }
948
949 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
950   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
951     return SDValue();
952   EVT OldVT = Op.getValueType();
953   SDLoc dl(Op);
954   bool Replace = false;
955   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
956   if (!NewOp.getNode())
957     return SDValue();
958   AddToWorklist(NewOp.getNode());
959
960   if (Replace)
961     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
962   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
963                      DAG.getValueType(OldVT));
964 }
965
966 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
967   EVT OldVT = Op.getValueType();
968   SDLoc dl(Op);
969   bool Replace = false;
970   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
971   if (!NewOp.getNode())
972     return SDValue();
973   AddToWorklist(NewOp.getNode());
974
975   if (Replace)
976     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
977   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
978 }
979
980 /// Promote the specified integer binary operation if the target indicates it is
981 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
982 /// i32 since i16 instructions are longer.
983 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
984   if (!LegalOperations)
985     return SDValue();
986
987   EVT VT = Op.getValueType();
988   if (VT.isVector() || !VT.isInteger())
989     return SDValue();
990
991   // If operation type is 'undesirable', e.g. i16 on x86, consider
992   // promoting it.
993   unsigned Opc = Op.getOpcode();
994   if (TLI.isTypeDesirableForOp(Opc, VT))
995     return SDValue();
996
997   EVT PVT = VT;
998   // Consult target whether it is a good idea to promote this operation and
999   // what's the right type to promote it to.
1000   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1001     assert(PVT != VT && "Don't know what type to promote to!");
1002
1003     bool Replace0 = false;
1004     SDValue N0 = Op.getOperand(0);
1005     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1006     if (!NN0.getNode())
1007       return SDValue();
1008
1009     bool Replace1 = false;
1010     SDValue N1 = Op.getOperand(1);
1011     SDValue NN1;
1012     if (N0 == N1)
1013       NN1 = NN0;
1014     else {
1015       NN1 = PromoteOperand(N1, PVT, Replace1);
1016       if (!NN1.getNode())
1017         return SDValue();
1018     }
1019
1020     AddToWorklist(NN0.getNode());
1021     if (NN1.getNode())
1022       AddToWorklist(NN1.getNode());
1023
1024     if (Replace0)
1025       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1026     if (Replace1)
1027       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1028
1029     DEBUG(dbgs() << "\nPromoting ";
1030           Op.getNode()->dump(&DAG));
1031     SDLoc dl(Op);
1032     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1033                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1034   }
1035   return SDValue();
1036 }
1037
1038 /// Promote the specified integer shift operation if the target indicates it is
1039 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1040 /// i32 since i16 instructions are longer.
1041 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1042   if (!LegalOperations)
1043     return SDValue();
1044
1045   EVT VT = Op.getValueType();
1046   if (VT.isVector() || !VT.isInteger())
1047     return SDValue();
1048
1049   // If operation type is 'undesirable', e.g. i16 on x86, consider
1050   // promoting it.
1051   unsigned Opc = Op.getOpcode();
1052   if (TLI.isTypeDesirableForOp(Opc, VT))
1053     return SDValue();
1054
1055   EVT PVT = VT;
1056   // Consult target whether it is a good idea to promote this operation and
1057   // what's the right type to promote it to.
1058   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1059     assert(PVT != VT && "Don't know what type to promote to!");
1060
1061     bool Replace = false;
1062     SDValue N0 = Op.getOperand(0);
1063     if (Opc == ISD::SRA)
1064       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1065     else if (Opc == ISD::SRL)
1066       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1067     else
1068       N0 = PromoteOperand(N0, PVT, Replace);
1069     if (!N0.getNode())
1070       return SDValue();
1071
1072     AddToWorklist(N0.getNode());
1073     if (Replace)
1074       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1075
1076     DEBUG(dbgs() << "\nPromoting ";
1077           Op.getNode()->dump(&DAG));
1078     SDLoc dl(Op);
1079     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1080                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1081   }
1082   return SDValue();
1083 }
1084
1085 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1086   if (!LegalOperations)
1087     return SDValue();
1088
1089   EVT VT = Op.getValueType();
1090   if (VT.isVector() || !VT.isInteger())
1091     return SDValue();
1092
1093   // If operation type is 'undesirable', e.g. i16 on x86, consider
1094   // promoting it.
1095   unsigned Opc = Op.getOpcode();
1096   if (TLI.isTypeDesirableForOp(Opc, VT))
1097     return SDValue();
1098
1099   EVT PVT = VT;
1100   // Consult target whether it is a good idea to promote this operation and
1101   // what's the right type to promote it to.
1102   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1103     assert(PVT != VT && "Don't know what type to promote to!");
1104     // fold (aext (aext x)) -> (aext x)
1105     // fold (aext (zext x)) -> (zext x)
1106     // fold (aext (sext x)) -> (sext x)
1107     DEBUG(dbgs() << "\nPromoting ";
1108           Op.getNode()->dump(&DAG));
1109     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1110   }
1111   return SDValue();
1112 }
1113
1114 bool DAGCombiner::PromoteLoad(SDValue Op) {
1115   if (!LegalOperations)
1116     return false;
1117
1118   EVT VT = Op.getValueType();
1119   if (VT.isVector() || !VT.isInteger())
1120     return false;
1121
1122   // If operation type is 'undesirable', e.g. i16 on x86, consider
1123   // promoting it.
1124   unsigned Opc = Op.getOpcode();
1125   if (TLI.isTypeDesirableForOp(Opc, VT))
1126     return false;
1127
1128   EVT PVT = VT;
1129   // Consult target whether it is a good idea to promote this operation and
1130   // what's the right type to promote it to.
1131   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1132     assert(PVT != VT && "Don't know what type to promote to!");
1133
1134     SDLoc dl(Op);
1135     SDNode *N = Op.getNode();
1136     LoadSDNode *LD = cast<LoadSDNode>(N);
1137     EVT MemVT = LD->getMemoryVT();
1138     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1139       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1140                                                        : ISD::EXTLOAD)
1141       : LD->getExtensionType();
1142     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1143                                    LD->getChain(), LD->getBasePtr(),
1144                                    MemVT, LD->getMemOperand());
1145     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1146
1147     DEBUG(dbgs() << "\nPromoting ";
1148           N->dump(&DAG);
1149           dbgs() << "\nTo: ";
1150           Result.getNode()->dump(&DAG);
1151           dbgs() << '\n');
1152     WorklistRemover DeadNodes(*this);
1153     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1154     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1155     deleteAndRecombine(N);
1156     AddToWorklist(Result.getNode());
1157     return true;
1158   }
1159   return false;
1160 }
1161
1162 /// \brief Recursively delete a node which has no uses and any operands for
1163 /// which it is the only use.
1164 ///
1165 /// Note that this both deletes the nodes and removes them from the worklist.
1166 /// It also adds any nodes who have had a user deleted to the worklist as they
1167 /// may now have only one use and subject to other combines.
1168 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1169   if (!N->use_empty())
1170     return false;
1171
1172   SmallSetVector<SDNode *, 16> Nodes;
1173   Nodes.insert(N);
1174   do {
1175     N = Nodes.pop_back_val();
1176     if (!N)
1177       continue;
1178
1179     if (N->use_empty()) {
1180       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1181         Nodes.insert(N->getOperand(i).getNode());
1182
1183       removeFromWorklist(N);
1184       DAG.DeleteNode(N);
1185     } else {
1186       AddToWorklist(N);
1187     }
1188   } while (!Nodes.empty());
1189   return true;
1190 }
1191
1192 //===----------------------------------------------------------------------===//
1193 //  Main DAG Combiner implementation
1194 //===----------------------------------------------------------------------===//
1195
1196 void DAGCombiner::Run(CombineLevel AtLevel) {
1197   // set the instance variables, so that the various visit routines may use it.
1198   Level = AtLevel;
1199   LegalOperations = Level >= AfterLegalizeVectorOps;
1200   LegalTypes = Level >= AfterLegalizeTypes;
1201
1202   // Add all the dag nodes to the worklist.
1203   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1204        E = DAG.allnodes_end(); I != E; ++I)
1205     AddToWorklist(I);
1206
1207   // Create a dummy node (which is not added to allnodes), that adds a reference
1208   // to the root node, preventing it from being deleted, and tracking any
1209   // changes of the root.
1210   HandleSDNode Dummy(DAG.getRoot());
1211
1212   // while the worklist isn't empty, find a node and
1213   // try and combine it.
1214   while (!WorklistMap.empty()) {
1215     SDNode *N;
1216     // The Worklist holds the SDNodes in order, but it may contain null entries.
1217     do {
1218       N = Worklist.pop_back_val();
1219     } while (!N);
1220
1221     bool GoodWorklistEntry = WorklistMap.erase(N);
1222     (void)GoodWorklistEntry;
1223     assert(GoodWorklistEntry &&
1224            "Found a worklist entry without a corresponding map entry!");
1225
1226     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1227     // N is deleted from the DAG, since they too may now be dead or may have a
1228     // reduced number of uses, allowing other xforms.
1229     if (recursivelyDeleteUnusedNodes(N))
1230       continue;
1231
1232     WorklistRemover DeadNodes(*this);
1233
1234     // If this combine is running after legalizing the DAG, re-legalize any
1235     // nodes pulled off the worklist.
1236     if (Level == AfterLegalizeDAG) {
1237       SmallSetVector<SDNode *, 16> UpdatedNodes;
1238       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1239
1240       for (SDNode *LN : UpdatedNodes) {
1241         AddToWorklist(LN);
1242         AddUsersToWorklist(LN);
1243       }
1244       if (!NIsValid)
1245         continue;
1246     }
1247
1248     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1249
1250     // Add any operands of the new node which have not yet been combined to the
1251     // worklist as well. Because the worklist uniques things already, this
1252     // won't repeatedly process the same operand.
1253     CombinedNodes.insert(N);
1254     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1255       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1256         AddToWorklist(N->getOperand(i).getNode());
1257
1258     SDValue RV = combine(N);
1259
1260     if (!RV.getNode())
1261       continue;
1262
1263     ++NodesCombined;
1264
1265     // If we get back the same node we passed in, rather than a new node or
1266     // zero, we know that the node must have defined multiple values and
1267     // CombineTo was used.  Since CombineTo takes care of the worklist
1268     // mechanics for us, we have no work to do in this case.
1269     if (RV.getNode() == N)
1270       continue;
1271
1272     assert(N->getOpcode() != ISD::DELETED_NODE &&
1273            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1274            "Node was deleted but visit returned new node!");
1275
1276     DEBUG(dbgs() << " ... into: ";
1277           RV.getNode()->dump(&DAG));
1278
1279     // Transfer debug value.
1280     DAG.TransferDbgValues(SDValue(N, 0), RV);
1281     if (N->getNumValues() == RV.getNode()->getNumValues())
1282       DAG.ReplaceAllUsesWith(N, RV.getNode());
1283     else {
1284       assert(N->getValueType(0) == RV.getValueType() &&
1285              N->getNumValues() == 1 && "Type mismatch");
1286       SDValue OpV = RV;
1287       DAG.ReplaceAllUsesWith(N, &OpV);
1288     }
1289
1290     // Push the new node and any users onto the worklist
1291     AddToWorklist(RV.getNode());
1292     AddUsersToWorklist(RV.getNode());
1293
1294     // Finally, if the node is now dead, remove it from the graph.  The node
1295     // may not be dead if the replacement process recursively simplified to
1296     // something else needing this node. This will also take care of adding any
1297     // operands which have lost a user to the worklist.
1298     recursivelyDeleteUnusedNodes(N);
1299   }
1300
1301   // If the root changed (e.g. it was a dead load, update the root).
1302   DAG.setRoot(Dummy.getValue());
1303   DAG.RemoveDeadNodes();
1304 }
1305
1306 SDValue DAGCombiner::visit(SDNode *N) {
1307   switch (N->getOpcode()) {
1308   default: break;
1309   case ISD::TokenFactor:        return visitTokenFactor(N);
1310   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1311   case ISD::ADD:                return visitADD(N);
1312   case ISD::SUB:                return visitSUB(N);
1313   case ISD::ADDC:               return visitADDC(N);
1314   case ISD::SUBC:               return visitSUBC(N);
1315   case ISD::ADDE:               return visitADDE(N);
1316   case ISD::SUBE:               return visitSUBE(N);
1317   case ISD::MUL:                return visitMUL(N);
1318   case ISD::SDIV:               return visitSDIV(N);
1319   case ISD::UDIV:               return visitUDIV(N);
1320   case ISD::SREM:               return visitSREM(N);
1321   case ISD::UREM:               return visitUREM(N);
1322   case ISD::MULHU:              return visitMULHU(N);
1323   case ISD::MULHS:              return visitMULHS(N);
1324   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1325   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1326   case ISD::SMULO:              return visitSMULO(N);
1327   case ISD::UMULO:              return visitUMULO(N);
1328   case ISD::SDIVREM:            return visitSDIVREM(N);
1329   case ISD::UDIVREM:            return visitUDIVREM(N);
1330   case ISD::AND:                return visitAND(N);
1331   case ISD::OR:                 return visitOR(N);
1332   case ISD::XOR:                return visitXOR(N);
1333   case ISD::SHL:                return visitSHL(N);
1334   case ISD::SRA:                return visitSRA(N);
1335   case ISD::SRL:                return visitSRL(N);
1336   case ISD::ROTR:
1337   case ISD::ROTL:               return visitRotate(N);
1338   case ISD::CTLZ:               return visitCTLZ(N);
1339   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1340   case ISD::CTTZ:               return visitCTTZ(N);
1341   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1342   case ISD::CTPOP:              return visitCTPOP(N);
1343   case ISD::SELECT:             return visitSELECT(N);
1344   case ISD::VSELECT:            return visitVSELECT(N);
1345   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1346   case ISD::SETCC:              return visitSETCC(N);
1347   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1348   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1349   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1350   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1351   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1352   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1353   case ISD::BITCAST:            return visitBITCAST(N);
1354   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1355   case ISD::FADD:               return visitFADD(N);
1356   case ISD::FSUB:               return visitFSUB(N);
1357   case ISD::FMUL:               return visitFMUL(N);
1358   case ISD::FMA:                return visitFMA(N);
1359   case ISD::FDIV:               return visitFDIV(N);
1360   case ISD::FREM:               return visitFREM(N);
1361   case ISD::FSQRT:              return visitFSQRT(N);
1362   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1363   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1364   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1365   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1366   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1367   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1368   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1369   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1370   case ISD::FNEG:               return visitFNEG(N);
1371   case ISD::FABS:               return visitFABS(N);
1372   case ISD::FFLOOR:             return visitFFLOOR(N);
1373   case ISD::FMINNUM:            return visitFMINNUM(N);
1374   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1375   case ISD::FCEIL:              return visitFCEIL(N);
1376   case ISD::FTRUNC:             return visitFTRUNC(N);
1377   case ISD::BRCOND:             return visitBRCOND(N);
1378   case ISD::BR_CC:              return visitBR_CC(N);
1379   case ISD::LOAD:               return visitLOAD(N);
1380   case ISD::STORE:              return visitSTORE(N);
1381   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1382   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1383   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1384   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1385   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1386   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1387   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1388   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1389   case ISD::MGATHER:            return visitMGATHER(N);
1390   case ISD::MLOAD:              return visitMLOAD(N);
1391   case ISD::MSCATTER:           return visitMSCATTER(N);
1392   case ISD::MSTORE:             return visitMSTORE(N);
1393   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1394   }
1395   return SDValue();
1396 }
1397
1398 SDValue DAGCombiner::combine(SDNode *N) {
1399   SDValue RV = visit(N);
1400
1401   // If nothing happened, try a target-specific DAG combine.
1402   if (!RV.getNode()) {
1403     assert(N->getOpcode() != ISD::DELETED_NODE &&
1404            "Node was deleted but visit returned NULL!");
1405
1406     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1407         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1408
1409       // Expose the DAG combiner to the target combiner impls.
1410       TargetLowering::DAGCombinerInfo
1411         DagCombineInfo(DAG, Level, false, this);
1412
1413       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1414     }
1415   }
1416
1417   // If nothing happened still, try promoting the operation.
1418   if (!RV.getNode()) {
1419     switch (N->getOpcode()) {
1420     default: break;
1421     case ISD::ADD:
1422     case ISD::SUB:
1423     case ISD::MUL:
1424     case ISD::AND:
1425     case ISD::OR:
1426     case ISD::XOR:
1427       RV = PromoteIntBinOp(SDValue(N, 0));
1428       break;
1429     case ISD::SHL:
1430     case ISD::SRA:
1431     case ISD::SRL:
1432       RV = PromoteIntShiftOp(SDValue(N, 0));
1433       break;
1434     case ISD::SIGN_EXTEND:
1435     case ISD::ZERO_EXTEND:
1436     case ISD::ANY_EXTEND:
1437       RV = PromoteExtend(SDValue(N, 0));
1438       break;
1439     case ISD::LOAD:
1440       if (PromoteLoad(SDValue(N, 0)))
1441         RV = SDValue(N, 0);
1442       break;
1443     }
1444   }
1445
1446   // If N is a commutative binary node, try commuting it to enable more
1447   // sdisel CSE.
1448   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1449       N->getNumValues() == 1) {
1450     SDValue N0 = N->getOperand(0);
1451     SDValue N1 = N->getOperand(1);
1452
1453     // Constant operands are canonicalized to RHS.
1454     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1455       SDValue Ops[] = {N1, N0};
1456       SDNode *CSENode;
1457       if (const BinaryWithFlagsSDNode *BinNode =
1458               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1459         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1460                                       BinNode->Flags.hasNoUnsignedWrap(),
1461                                       BinNode->Flags.hasNoSignedWrap(),
1462                                       BinNode->Flags.hasExact());
1463       } else {
1464         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1465       }
1466       if (CSENode)
1467         return SDValue(CSENode, 0);
1468     }
1469   }
1470
1471   return RV;
1472 }
1473
1474 /// Given a node, return its input chain if it has one, otherwise return a null
1475 /// sd operand.
1476 static SDValue getInputChainForNode(SDNode *N) {
1477   if (unsigned NumOps = N->getNumOperands()) {
1478     if (N->getOperand(0).getValueType() == MVT::Other)
1479       return N->getOperand(0);
1480     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1481       return N->getOperand(NumOps-1);
1482     for (unsigned i = 1; i < NumOps-1; ++i)
1483       if (N->getOperand(i).getValueType() == MVT::Other)
1484         return N->getOperand(i);
1485   }
1486   return SDValue();
1487 }
1488
1489 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1490   // If N has two operands, where one has an input chain equal to the other,
1491   // the 'other' chain is redundant.
1492   if (N->getNumOperands() == 2) {
1493     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1494       return N->getOperand(0);
1495     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1496       return N->getOperand(1);
1497   }
1498
1499   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1500   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1501   SmallPtrSet<SDNode*, 16> SeenOps;
1502   bool Changed = false;             // If we should replace this token factor.
1503
1504   // Start out with this token factor.
1505   TFs.push_back(N);
1506
1507   // Iterate through token factors.  The TFs grows when new token factors are
1508   // encountered.
1509   for (unsigned i = 0; i < TFs.size(); ++i) {
1510     SDNode *TF = TFs[i];
1511
1512     // Check each of the operands.
1513     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1514       SDValue Op = TF->getOperand(i);
1515
1516       switch (Op.getOpcode()) {
1517       case ISD::EntryToken:
1518         // Entry tokens don't need to be added to the list. They are
1519         // redundant.
1520         Changed = true;
1521         break;
1522
1523       case ISD::TokenFactor:
1524         if (Op.hasOneUse() &&
1525             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1526           // Queue up for processing.
1527           TFs.push_back(Op.getNode());
1528           // Clean up in case the token factor is removed.
1529           AddToWorklist(Op.getNode());
1530           Changed = true;
1531           break;
1532         }
1533         // Fall thru
1534
1535       default:
1536         // Only add if it isn't already in the list.
1537         if (SeenOps.insert(Op.getNode()).second)
1538           Ops.push_back(Op);
1539         else
1540           Changed = true;
1541         break;
1542       }
1543     }
1544   }
1545
1546   SDValue Result;
1547
1548   // If we've changed things around then replace token factor.
1549   if (Changed) {
1550     if (Ops.empty()) {
1551       // The entry token is the only possible outcome.
1552       Result = DAG.getEntryNode();
1553     } else {
1554       // New and improved token factor.
1555       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1556     }
1557
1558     // Add users to worklist if AA is enabled, since it may introduce
1559     // a lot of new chained token factors while removing memory deps.
1560     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1561       : DAG.getSubtarget().useAA();
1562     return CombineTo(N, Result, UseAA /*add to worklist*/);
1563   }
1564
1565   return Result;
1566 }
1567
1568 /// MERGE_VALUES can always be eliminated.
1569 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1570   WorklistRemover DeadNodes(*this);
1571   // Replacing results may cause a different MERGE_VALUES to suddenly
1572   // be CSE'd with N, and carry its uses with it. Iterate until no
1573   // uses remain, to ensure that the node can be safely deleted.
1574   // First add the users of this node to the work list so that they
1575   // can be tried again once they have new operands.
1576   AddUsersToWorklist(N);
1577   do {
1578     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1579       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1580   } while (!N->use_empty());
1581   deleteAndRecombine(N);
1582   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1583 }
1584
1585 static bool isNullConstant(SDValue V) {
1586   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1587   return Const != nullptr && Const->isNullValue();
1588 }
1589
1590 static bool isNullFPConstant(SDValue V) {
1591   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1592   return Const != nullptr && Const->isZero() && !Const->isNegative();
1593 }
1594
1595 static bool isAllOnesConstant(SDValue V) {
1596   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1597   return Const != nullptr && Const->isAllOnesValue();
1598 }
1599
1600 static bool isOneConstant(SDValue V) {
1601   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1602   return Const != nullptr && Const->isOne();
1603 }
1604
1605 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1606 /// ContantSDNode pointer else nullptr.
1607 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1608   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1609   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1610 }
1611
1612 SDValue DAGCombiner::visitADD(SDNode *N) {
1613   SDValue N0 = N->getOperand(0);
1614   SDValue N1 = N->getOperand(1);
1615   EVT VT = N0.getValueType();
1616
1617   // fold vector ops
1618   if (VT.isVector()) {
1619     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1620       return FoldedVOp;
1621
1622     // fold (add x, 0) -> x, vector edition
1623     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1624       return N0;
1625     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1626       return N1;
1627   }
1628
1629   // fold (add x, undef) -> undef
1630   if (N0.getOpcode() == ISD::UNDEF)
1631     return N0;
1632   if (N1.getOpcode() == ISD::UNDEF)
1633     return N1;
1634   // fold (add c1, c2) -> c1+c2
1635   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1636   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1637   if (N0C && N1C)
1638     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1639   // canonicalize constant to RHS
1640   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1641      !isConstantIntBuildVectorOrConstantInt(N1))
1642     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1643   // fold (add x, 0) -> x
1644   if (isNullConstant(N1))
1645     return N0;
1646   // fold (add Sym, c) -> Sym+c
1647   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1648     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1649         GA->getOpcode() == ISD::GlobalAddress)
1650       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1651                                   GA->getOffset() +
1652                                     (uint64_t)N1C->getSExtValue());
1653   // fold ((c1-A)+c2) -> (c1+c2)-A
1654   if (N1C && N0.getOpcode() == ISD::SUB)
1655     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1656       SDLoc DL(N);
1657       return DAG.getNode(ISD::SUB, DL, VT,
1658                          DAG.getConstant(N1C->getAPIntValue()+
1659                                          N0C->getAPIntValue(), DL, VT),
1660                          N0.getOperand(1));
1661     }
1662   // reassociate add
1663   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1664     return RADD;
1665   // fold ((0-A) + B) -> B-A
1666   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1667     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1668   // fold (A + (0-B)) -> A-B
1669   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1670     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1671   // fold (A+(B-A)) -> B
1672   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1673     return N1.getOperand(0);
1674   // fold ((B-A)+A) -> B
1675   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1676     return N0.getOperand(0);
1677   // fold (A+(B-(A+C))) to (B-C)
1678   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1679       N0 == N1.getOperand(1).getOperand(0))
1680     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1681                        N1.getOperand(1).getOperand(1));
1682   // fold (A+(B-(C+A))) to (B-C)
1683   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1684       N0 == N1.getOperand(1).getOperand(1))
1685     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1686                        N1.getOperand(1).getOperand(0));
1687   // fold (A+((B-A)+or-C)) to (B+or-C)
1688   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1689       N1.getOperand(0).getOpcode() == ISD::SUB &&
1690       N0 == N1.getOperand(0).getOperand(1))
1691     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1692                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1693
1694   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1695   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1696     SDValue N00 = N0.getOperand(0);
1697     SDValue N01 = N0.getOperand(1);
1698     SDValue N10 = N1.getOperand(0);
1699     SDValue N11 = N1.getOperand(1);
1700
1701     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1702       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1703                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1704                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1705   }
1706
1707   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1708     return SDValue(N, 0);
1709
1710   // fold (a+b) -> (a|b) iff a and b share no bits.
1711   if (VT.isInteger() && !VT.isVector()) {
1712     APInt LHSZero, LHSOne;
1713     APInt RHSZero, RHSOne;
1714     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1715
1716     if (LHSZero.getBoolValue()) {
1717       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1718
1719       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1720       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1721       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1722         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1723           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1724       }
1725     }
1726   }
1727
1728   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1729   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1730       isNullConstant(N1.getOperand(0).getOperand(0)))
1731     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1732                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1733                                    N1.getOperand(0).getOperand(1),
1734                                    N1.getOperand(1)));
1735   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1736       isNullConstant(N0.getOperand(0).getOperand(0)))
1737     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1738                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1739                                    N0.getOperand(0).getOperand(1),
1740                                    N0.getOperand(1)));
1741
1742   if (N1.getOpcode() == ISD::AND) {
1743     SDValue AndOp0 = N1.getOperand(0);
1744     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1745     unsigned DestBits = VT.getScalarType().getSizeInBits();
1746
1747     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1748     // and similar xforms where the inner op is either ~0 or 0.
1749     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1750       SDLoc DL(N);
1751       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1752     }
1753   }
1754
1755   // add (sext i1), X -> sub X, (zext i1)
1756   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1757       N0.getOperand(0).getValueType() == MVT::i1 &&
1758       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1759     SDLoc DL(N);
1760     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1761     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1762   }
1763
1764   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1765   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1766     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1767     if (TN->getVT() == MVT::i1) {
1768       SDLoc DL(N);
1769       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1770                                  DAG.getConstant(1, DL, VT));
1771       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1772     }
1773   }
1774
1775   return SDValue();
1776 }
1777
1778 SDValue DAGCombiner::visitADDC(SDNode *N) {
1779   SDValue N0 = N->getOperand(0);
1780   SDValue N1 = N->getOperand(1);
1781   EVT VT = N0.getValueType();
1782
1783   // If the flag result is dead, turn this into an ADD.
1784   if (!N->hasAnyUseOfValue(1))
1785     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1786                      DAG.getNode(ISD::CARRY_FALSE,
1787                                  SDLoc(N), MVT::Glue));
1788
1789   // canonicalize constant to RHS.
1790   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1791   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1792   if (N0C && !N1C)
1793     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1794
1795   // fold (addc x, 0) -> x + no carry out
1796   if (isNullConstant(N1))
1797     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1798                                         SDLoc(N), MVT::Glue));
1799
1800   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1801   APInt LHSZero, LHSOne;
1802   APInt RHSZero, RHSOne;
1803   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1804
1805   if (LHSZero.getBoolValue()) {
1806     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1807
1808     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1809     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1810     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1811       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1812                        DAG.getNode(ISD::CARRY_FALSE,
1813                                    SDLoc(N), MVT::Glue));
1814   }
1815
1816   return SDValue();
1817 }
1818
1819 SDValue DAGCombiner::visitADDE(SDNode *N) {
1820   SDValue N0 = N->getOperand(0);
1821   SDValue N1 = N->getOperand(1);
1822   SDValue CarryIn = N->getOperand(2);
1823
1824   // canonicalize constant to RHS
1825   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1826   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1827   if (N0C && !N1C)
1828     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1829                        N1, N0, CarryIn);
1830
1831   // fold (adde x, y, false) -> (addc x, y)
1832   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1833     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1834
1835   return SDValue();
1836 }
1837
1838 // Since it may not be valid to emit a fold to zero for vector initializers
1839 // check if we can before folding.
1840 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1841                              SelectionDAG &DAG,
1842                              bool LegalOperations, bool LegalTypes) {
1843   if (!VT.isVector())
1844     return DAG.getConstant(0, DL, VT);
1845   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1846     return DAG.getConstant(0, DL, VT);
1847   return SDValue();
1848 }
1849
1850 SDValue DAGCombiner::visitSUB(SDNode *N) {
1851   SDValue N0 = N->getOperand(0);
1852   SDValue N1 = N->getOperand(1);
1853   EVT VT = N0.getValueType();
1854
1855   // fold vector ops
1856   if (VT.isVector()) {
1857     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1858       return FoldedVOp;
1859
1860     // fold (sub x, 0) -> x, vector edition
1861     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1862       return N0;
1863   }
1864
1865   // fold (sub x, x) -> 0
1866   // FIXME: Refactor this and xor and other similar operations together.
1867   if (N0 == N1)
1868     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1869   // fold (sub c1, c2) -> c1-c2
1870   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1871   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1872   if (N0C && N1C)
1873     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1874   // fold (sub x, c) -> (add x, -c)
1875   if (N1C) {
1876     SDLoc DL(N);
1877     return DAG.getNode(ISD::ADD, DL, VT, N0,
1878                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1879   }
1880   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1881   if (isAllOnesConstant(N0))
1882     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1883   // fold A-(A-B) -> B
1884   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1885     return N1.getOperand(1);
1886   // fold (A+B)-A -> B
1887   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1888     return N0.getOperand(1);
1889   // fold (A+B)-B -> A
1890   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1891     return N0.getOperand(0);
1892   // fold C2-(A+C1) -> (C2-C1)-A
1893   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1894     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1895   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1896     SDLoc DL(N);
1897     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1898                                    DL, VT);
1899     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1900                        N1.getOperand(0));
1901   }
1902   // fold ((A+(B+or-C))-B) -> A+or-C
1903   if (N0.getOpcode() == ISD::ADD &&
1904       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1905        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1906       N0.getOperand(1).getOperand(0) == N1)
1907     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1908                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1909   // fold ((A+(C+B))-B) -> A+C
1910   if (N0.getOpcode() == ISD::ADD &&
1911       N0.getOperand(1).getOpcode() == ISD::ADD &&
1912       N0.getOperand(1).getOperand(1) == N1)
1913     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1914                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1915   // fold ((A-(B-C))-C) -> A-B
1916   if (N0.getOpcode() == ISD::SUB &&
1917       N0.getOperand(1).getOpcode() == ISD::SUB &&
1918       N0.getOperand(1).getOperand(1) == N1)
1919     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1920                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1921
1922   // If either operand of a sub is undef, the result is undef
1923   if (N0.getOpcode() == ISD::UNDEF)
1924     return N0;
1925   if (N1.getOpcode() == ISD::UNDEF)
1926     return N1;
1927
1928   // If the relocation model supports it, consider symbol offsets.
1929   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1930     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1931       // fold (sub Sym, c) -> Sym-c
1932       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1933         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1934                                     GA->getOffset() -
1935                                       (uint64_t)N1C->getSExtValue());
1936       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1937       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1938         if (GA->getGlobal() == GB->getGlobal())
1939           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1940                                  SDLoc(N), VT);
1941     }
1942
1943   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1944   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1945     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1946     if (TN->getVT() == MVT::i1) {
1947       SDLoc DL(N);
1948       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1949                                  DAG.getConstant(1, DL, VT));
1950       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1951     }
1952   }
1953
1954   return SDValue();
1955 }
1956
1957 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1958   SDValue N0 = N->getOperand(0);
1959   SDValue N1 = N->getOperand(1);
1960   EVT VT = N0.getValueType();
1961
1962   // If the flag result is dead, turn this into an SUB.
1963   if (!N->hasAnyUseOfValue(1))
1964     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1965                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1966                                  MVT::Glue));
1967
1968   // fold (subc x, x) -> 0 + no borrow
1969   if (N0 == N1) {
1970     SDLoc DL(N);
1971     return CombineTo(N, DAG.getConstant(0, DL, VT),
1972                      DAG.getNode(ISD::CARRY_FALSE, DL,
1973                                  MVT::Glue));
1974   }
1975
1976   // fold (subc x, 0) -> x + no borrow
1977   if (isNullConstant(N1))
1978     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1979                                         MVT::Glue));
1980
1981   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1982   if (isAllOnesConstant(N0))
1983     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1984                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1985                                  MVT::Glue));
1986
1987   return SDValue();
1988 }
1989
1990 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1991   SDValue N0 = N->getOperand(0);
1992   SDValue N1 = N->getOperand(1);
1993   SDValue CarryIn = N->getOperand(2);
1994
1995   // fold (sube x, y, false) -> (subc x, y)
1996   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1997     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1998
1999   return SDValue();
2000 }
2001
2002 SDValue DAGCombiner::visitMUL(SDNode *N) {
2003   SDValue N0 = N->getOperand(0);
2004   SDValue N1 = N->getOperand(1);
2005   EVT VT = N0.getValueType();
2006
2007   // fold (mul x, undef) -> 0
2008   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2009     return DAG.getConstant(0, SDLoc(N), VT);
2010
2011   bool N0IsConst = false;
2012   bool N1IsConst = false;
2013   bool N1IsOpaqueConst = false;
2014   bool N0IsOpaqueConst = false;
2015   APInt ConstValue0, ConstValue1;
2016   // fold vector ops
2017   if (VT.isVector()) {
2018     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2019       return FoldedVOp;
2020
2021     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2022     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2023   } else {
2024     N0IsConst = isa<ConstantSDNode>(N0);
2025     if (N0IsConst) {
2026       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2027       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2028     }
2029     N1IsConst = isa<ConstantSDNode>(N1);
2030     if (N1IsConst) {
2031       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2032       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2033     }
2034   }
2035
2036   // fold (mul c1, c2) -> c1*c2
2037   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2038     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2039                                       N0.getNode(), N1.getNode());
2040
2041   // canonicalize constant to RHS (vector doesn't have to splat)
2042   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2043      !isConstantIntBuildVectorOrConstantInt(N1))
2044     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2045   // fold (mul x, 0) -> 0
2046   if (N1IsConst && ConstValue1 == 0)
2047     return N1;
2048   // We require a splat of the entire scalar bit width for non-contiguous
2049   // bit patterns.
2050   bool IsFullSplat =
2051     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2052   // fold (mul x, 1) -> x
2053   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2054     return N0;
2055   // fold (mul x, -1) -> 0-x
2056   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2057     SDLoc DL(N);
2058     return DAG.getNode(ISD::SUB, DL, VT,
2059                        DAG.getConstant(0, DL, VT), N0);
2060   }
2061   // fold (mul x, (1 << c)) -> x << c
2062   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2063       IsFullSplat) {
2064     SDLoc DL(N);
2065     return DAG.getNode(ISD::SHL, DL, VT, N0,
2066                        DAG.getConstant(ConstValue1.logBase2(), DL,
2067                                        getShiftAmountTy(N0.getValueType())));
2068   }
2069   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2070   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2071       IsFullSplat) {
2072     unsigned Log2Val = (-ConstValue1).logBase2();
2073     SDLoc DL(N);
2074     // FIXME: If the input is something that is easily negated (e.g. a
2075     // single-use add), we should put the negate there.
2076     return DAG.getNode(ISD::SUB, DL, VT,
2077                        DAG.getConstant(0, DL, VT),
2078                        DAG.getNode(ISD::SHL, DL, VT, N0,
2079                             DAG.getConstant(Log2Val, DL,
2080                                       getShiftAmountTy(N0.getValueType()))));
2081   }
2082
2083   APInt Val;
2084   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2085   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2086       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2087                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2088     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2089                              N1, N0.getOperand(1));
2090     AddToWorklist(C3.getNode());
2091     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2092                        N0.getOperand(0), C3);
2093   }
2094
2095   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2096   // use.
2097   {
2098     SDValue Sh(nullptr,0), Y(nullptr,0);
2099     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2100     if (N0.getOpcode() == ISD::SHL &&
2101         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2102                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2103         N0.getNode()->hasOneUse()) {
2104       Sh = N0; Y = N1;
2105     } else if (N1.getOpcode() == ISD::SHL &&
2106                isa<ConstantSDNode>(N1.getOperand(1)) &&
2107                N1.getNode()->hasOneUse()) {
2108       Sh = N1; Y = N0;
2109     }
2110
2111     if (Sh.getNode()) {
2112       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2113                                 Sh.getOperand(0), Y);
2114       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2115                          Mul, Sh.getOperand(1));
2116     }
2117   }
2118
2119   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2120   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2121       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2122                      isa<ConstantSDNode>(N0.getOperand(1))))
2123     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2124                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2125                                    N0.getOperand(0), N1),
2126                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2127                                    N0.getOperand(1), N1));
2128
2129   // reassociate mul
2130   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2131     return RMUL;
2132
2133   return SDValue();
2134 }
2135
2136 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2137   SDValue N0 = N->getOperand(0);
2138   SDValue N1 = N->getOperand(1);
2139   EVT VT = N->getValueType(0);
2140
2141   // fold vector ops
2142   if (VT.isVector())
2143     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2144       return FoldedVOp;
2145
2146   // fold (sdiv c1, c2) -> c1/c2
2147   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2148   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2149   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2150     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2151   // fold (sdiv X, 1) -> X
2152   if (N1C && N1C->isOne())
2153     return N0;
2154   // fold (sdiv X, -1) -> 0-X
2155   if (N1C && N1C->isAllOnesValue()) {
2156     SDLoc DL(N);
2157     return DAG.getNode(ISD::SUB, DL, VT,
2158                        DAG.getConstant(0, DL, VT), N0);
2159   }
2160   // If we know the sign bits of both operands are zero, strength reduce to a
2161   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2162   if (!VT.isVector()) {
2163     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2164       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2165                          N0, N1);
2166   }
2167
2168   // fold (sdiv X, pow2) -> simple ops after legalize
2169   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2170       (N1C->getAPIntValue().isPowerOf2() ||
2171        (-N1C->getAPIntValue()).isPowerOf2())) {
2172     // If dividing by powers of two is cheap, then don't perform the following
2173     // fold.
2174     if (TLI.isPow2SDivCheap())
2175       return SDValue();
2176
2177     // Target-specific implementation of sdiv x, pow2.
2178     SDValue Res = BuildSDIVPow2(N);
2179     if (Res.getNode())
2180       return Res;
2181
2182     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2183     SDLoc DL(N);
2184
2185     // Splat the sign bit into the register
2186     SDValue SGN =
2187         DAG.getNode(ISD::SRA, DL, VT, N0,
2188                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2189                                     getShiftAmountTy(N0.getValueType())));
2190     AddToWorklist(SGN.getNode());
2191
2192     // Add (N0 < 0) ? abs2 - 1 : 0;
2193     SDValue SRL =
2194         DAG.getNode(ISD::SRL, DL, VT, SGN,
2195                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2196                                     getShiftAmountTy(SGN.getValueType())));
2197     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2198     AddToWorklist(SRL.getNode());
2199     AddToWorklist(ADD.getNode());    // Divide by pow2
2200     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2201                   DAG.getConstant(lg2, DL,
2202                                   getShiftAmountTy(ADD.getValueType())));
2203
2204     // If we're dividing by a positive value, we're done.  Otherwise, we must
2205     // negate the result.
2206     if (N1C->getAPIntValue().isNonNegative())
2207       return SRA;
2208
2209     AddToWorklist(SRA.getNode());
2210     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2211   }
2212
2213   // If integer divide is expensive and we satisfy the requirements, emit an
2214   // alternate sequence.
2215   if (N1C && !TLI.isIntDivCheap()) {
2216     SDValue Op = BuildSDIV(N);
2217     if (Op.getNode()) return Op;
2218   }
2219
2220   // undef / X -> 0
2221   if (N0.getOpcode() == ISD::UNDEF)
2222     return DAG.getConstant(0, SDLoc(N), VT);
2223   // X / undef -> undef
2224   if (N1.getOpcode() == ISD::UNDEF)
2225     return N1;
2226
2227   return SDValue();
2228 }
2229
2230 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2231   SDValue N0 = N->getOperand(0);
2232   SDValue N1 = N->getOperand(1);
2233   EVT VT = N->getValueType(0);
2234
2235   // fold vector ops
2236   if (VT.isVector())
2237     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2238       return FoldedVOp;
2239
2240   // fold (udiv c1, c2) -> c1/c2
2241   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2242   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2243   if (N0C && N1C)
2244     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2245                                                     N0C, N1C))
2246       return Folded;
2247   // fold (udiv x, (1 << c)) -> x >>u c
2248   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2249     SDLoc DL(N);
2250     return DAG.getNode(ISD::SRL, DL, VT, N0,
2251                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2252                                        getShiftAmountTy(N0.getValueType())));
2253   }
2254   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2255   if (N1.getOpcode() == ISD::SHL) {
2256     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2257       if (SHC->getAPIntValue().isPowerOf2()) {
2258         EVT ADDVT = N1.getOperand(1).getValueType();
2259         SDLoc DL(N);
2260         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2261                                   N1.getOperand(1),
2262                                   DAG.getConstant(SHC->getAPIntValue()
2263                                                                   .logBase2(),
2264                                                   DL, ADDVT));
2265         AddToWorklist(Add.getNode());
2266         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2267       }
2268     }
2269   }
2270   // fold (udiv x, c) -> alternate
2271   if (N1C && !TLI.isIntDivCheap()) {
2272     SDValue Op = BuildUDIV(N);
2273     if (Op.getNode()) return Op;
2274   }
2275
2276   // undef / X -> 0
2277   if (N0.getOpcode() == ISD::UNDEF)
2278     return DAG.getConstant(0, SDLoc(N), VT);
2279   // X / undef -> undef
2280   if (N1.getOpcode() == ISD::UNDEF)
2281     return N1;
2282
2283   return SDValue();
2284 }
2285
2286 SDValue DAGCombiner::visitSREM(SDNode *N) {
2287   SDValue N0 = N->getOperand(0);
2288   SDValue N1 = N->getOperand(1);
2289   EVT VT = N->getValueType(0);
2290
2291   // fold (srem c1, c2) -> c1%c2
2292   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2293   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2294   if (N0C && N1C)
2295     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2296                                                     N0C, N1C))
2297       return Folded;
2298   // If we know the sign bits of both operands are zero, strength reduce to a
2299   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2300   if (!VT.isVector()) {
2301     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2302       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2303   }
2304
2305   // If X/C can be simplified by the division-by-constant logic, lower
2306   // X%C to the equivalent of X-X/C*C.
2307   if (N1C && !N1C->isNullValue()) {
2308     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2309     AddToWorklist(Div.getNode());
2310     SDValue OptimizedDiv = combine(Div.getNode());
2311     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2312       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2313                                 OptimizedDiv, N1);
2314       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2315       AddToWorklist(Mul.getNode());
2316       return Sub;
2317     }
2318   }
2319
2320   // undef % X -> 0
2321   if (N0.getOpcode() == ISD::UNDEF)
2322     return DAG.getConstant(0, SDLoc(N), VT);
2323   // X % undef -> undef
2324   if (N1.getOpcode() == ISD::UNDEF)
2325     return N1;
2326
2327   return SDValue();
2328 }
2329
2330 SDValue DAGCombiner::visitUREM(SDNode *N) {
2331   SDValue N0 = N->getOperand(0);
2332   SDValue N1 = N->getOperand(1);
2333   EVT VT = N->getValueType(0);
2334
2335   // fold (urem c1, c2) -> c1%c2
2336   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2337   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2338   if (N0C && N1C)
2339     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2340                                                     N0C, N1C))
2341       return Folded;
2342   // fold (urem x, pow2) -> (and x, pow2-1)
2343   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2344       N1C->getAPIntValue().isPowerOf2()) {
2345     SDLoc DL(N);
2346     return DAG.getNode(ISD::AND, DL, VT, N0,
2347                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2348   }
2349   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2350   if (N1.getOpcode() == ISD::SHL) {
2351     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2352       if (SHC->getAPIntValue().isPowerOf2()) {
2353         SDLoc DL(N);
2354         SDValue Add =
2355           DAG.getNode(ISD::ADD, DL, VT, N1,
2356                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2357                                  VT));
2358         AddToWorklist(Add.getNode());
2359         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2360       }
2361     }
2362   }
2363
2364   // If X/C can be simplified by the division-by-constant logic, lower
2365   // X%C to the equivalent of X-X/C*C.
2366   if (N1C && !N1C->isNullValue()) {
2367     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2368     AddToWorklist(Div.getNode());
2369     SDValue OptimizedDiv = combine(Div.getNode());
2370     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2371       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2372                                 OptimizedDiv, N1);
2373       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2374       AddToWorklist(Mul.getNode());
2375       return Sub;
2376     }
2377   }
2378
2379   // undef % X -> 0
2380   if (N0.getOpcode() == ISD::UNDEF)
2381     return DAG.getConstant(0, SDLoc(N), VT);
2382   // X % undef -> undef
2383   if (N1.getOpcode() == ISD::UNDEF)
2384     return N1;
2385
2386   return SDValue();
2387 }
2388
2389 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2390   SDValue N0 = N->getOperand(0);
2391   SDValue N1 = N->getOperand(1);
2392   EVT VT = N->getValueType(0);
2393   SDLoc DL(N);
2394
2395   // fold (mulhs x, 0) -> 0
2396   if (isNullConstant(N1))
2397     return N1;
2398   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2399   if (isOneConstant(N1)) {
2400     SDLoc DL(N);
2401     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2402                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2403                                        DL,
2404                                        getShiftAmountTy(N0.getValueType())));
2405   }
2406   // fold (mulhs x, undef) -> 0
2407   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2408     return DAG.getConstant(0, SDLoc(N), VT);
2409
2410   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2411   // plus a shift.
2412   if (VT.isSimple() && !VT.isVector()) {
2413     MVT Simple = VT.getSimpleVT();
2414     unsigned SimpleSize = Simple.getSizeInBits();
2415     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2416     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2417       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2418       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2419       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2420       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2421             DAG.getConstant(SimpleSize, DL,
2422                             getShiftAmountTy(N1.getValueType())));
2423       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2424     }
2425   }
2426
2427   return SDValue();
2428 }
2429
2430 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2431   SDValue N0 = N->getOperand(0);
2432   SDValue N1 = N->getOperand(1);
2433   EVT VT = N->getValueType(0);
2434   SDLoc DL(N);
2435
2436   // fold (mulhu x, 0) -> 0
2437   if (isNullConstant(N1))
2438     return N1;
2439   // fold (mulhu x, 1) -> 0
2440   if (isOneConstant(N1))
2441     return DAG.getConstant(0, DL, N0.getValueType());
2442   // fold (mulhu x, undef) -> 0
2443   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2444     return DAG.getConstant(0, DL, VT);
2445
2446   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2447   // plus a shift.
2448   if (VT.isSimple() && !VT.isVector()) {
2449     MVT Simple = VT.getSimpleVT();
2450     unsigned SimpleSize = Simple.getSizeInBits();
2451     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2452     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2453       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2454       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2455       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2456       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2457             DAG.getConstant(SimpleSize, DL,
2458                             getShiftAmountTy(N1.getValueType())));
2459       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2460     }
2461   }
2462
2463   return SDValue();
2464 }
2465
2466 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2467 /// give the opcodes for the two computations that are being performed. Return
2468 /// true if a simplification was made.
2469 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2470                                                 unsigned HiOp) {
2471   // If the high half is not needed, just compute the low half.
2472   bool HiExists = N->hasAnyUseOfValue(1);
2473   if (!HiExists &&
2474       (!LegalOperations ||
2475        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2476     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2477     return CombineTo(N, Res, Res);
2478   }
2479
2480   // If the low half is not needed, just compute the high half.
2481   bool LoExists = N->hasAnyUseOfValue(0);
2482   if (!LoExists &&
2483       (!LegalOperations ||
2484        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2485     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2486     return CombineTo(N, Res, Res);
2487   }
2488
2489   // If both halves are used, return as it is.
2490   if (LoExists && HiExists)
2491     return SDValue();
2492
2493   // If the two computed results can be simplified separately, separate them.
2494   if (LoExists) {
2495     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2496     AddToWorklist(Lo.getNode());
2497     SDValue LoOpt = combine(Lo.getNode());
2498     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2499         (!LegalOperations ||
2500          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2501       return CombineTo(N, LoOpt, LoOpt);
2502   }
2503
2504   if (HiExists) {
2505     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2506     AddToWorklist(Hi.getNode());
2507     SDValue HiOpt = combine(Hi.getNode());
2508     if (HiOpt.getNode() && HiOpt != Hi &&
2509         (!LegalOperations ||
2510          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2511       return CombineTo(N, HiOpt, HiOpt);
2512   }
2513
2514   return SDValue();
2515 }
2516
2517 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2518   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2519   if (Res.getNode()) return Res;
2520
2521   EVT VT = N->getValueType(0);
2522   SDLoc DL(N);
2523
2524   // If the type is twice as wide is legal, transform the mulhu to a wider
2525   // multiply plus a shift.
2526   if (VT.isSimple() && !VT.isVector()) {
2527     MVT Simple = VT.getSimpleVT();
2528     unsigned SimpleSize = Simple.getSizeInBits();
2529     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2530     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2531       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2532       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2533       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2534       // Compute the high part as N1.
2535       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2536             DAG.getConstant(SimpleSize, DL,
2537                             getShiftAmountTy(Lo.getValueType())));
2538       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2539       // Compute the low part as N0.
2540       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2541       return CombineTo(N, Lo, Hi);
2542     }
2543   }
2544
2545   return SDValue();
2546 }
2547
2548 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2549   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2550   if (Res.getNode()) return Res;
2551
2552   EVT VT = N->getValueType(0);
2553   SDLoc DL(N);
2554
2555   // If the type is twice as wide is legal, transform the mulhu to a wider
2556   // multiply plus a shift.
2557   if (VT.isSimple() && !VT.isVector()) {
2558     MVT Simple = VT.getSimpleVT();
2559     unsigned SimpleSize = Simple.getSizeInBits();
2560     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2561     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2562       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2563       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2564       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2565       // Compute the high part as N1.
2566       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2567             DAG.getConstant(SimpleSize, DL,
2568                             getShiftAmountTy(Lo.getValueType())));
2569       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2570       // Compute the low part as N0.
2571       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2572       return CombineTo(N, Lo, Hi);
2573     }
2574   }
2575
2576   return SDValue();
2577 }
2578
2579 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2580   // (smulo x, 2) -> (saddo x, x)
2581   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2582     if (C2->getAPIntValue() == 2)
2583       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2584                          N->getOperand(0), N->getOperand(0));
2585
2586   return SDValue();
2587 }
2588
2589 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2590   // (umulo x, 2) -> (uaddo x, x)
2591   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2592     if (C2->getAPIntValue() == 2)
2593       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2594                          N->getOperand(0), N->getOperand(0));
2595
2596   return SDValue();
2597 }
2598
2599 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2600   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2601   if (Res.getNode()) return Res;
2602
2603   return SDValue();
2604 }
2605
2606 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2607   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2608   if (Res.getNode()) return Res;
2609
2610   return SDValue();
2611 }
2612
2613 /// If this is a binary operator with two operands of the same opcode, try to
2614 /// simplify it.
2615 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2616   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2617   EVT VT = N0.getValueType();
2618   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2619
2620   // Bail early if none of these transforms apply.
2621   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2622
2623   // For each of OP in AND/OR/XOR:
2624   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2625   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2626   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2627   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2628   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2629   //
2630   // do not sink logical op inside of a vector extend, since it may combine
2631   // into a vsetcc.
2632   EVT Op0VT = N0.getOperand(0).getValueType();
2633   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2634        N0.getOpcode() == ISD::SIGN_EXTEND ||
2635        N0.getOpcode() == ISD::BSWAP ||
2636        // Avoid infinite looping with PromoteIntBinOp.
2637        (N0.getOpcode() == ISD::ANY_EXTEND &&
2638         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2639        (N0.getOpcode() == ISD::TRUNCATE &&
2640         (!TLI.isZExtFree(VT, Op0VT) ||
2641          !TLI.isTruncateFree(Op0VT, VT)) &&
2642         TLI.isTypeLegal(Op0VT))) &&
2643       !VT.isVector() &&
2644       Op0VT == N1.getOperand(0).getValueType() &&
2645       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2646     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2647                                  N0.getOperand(0).getValueType(),
2648                                  N0.getOperand(0), N1.getOperand(0));
2649     AddToWorklist(ORNode.getNode());
2650     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2651   }
2652
2653   // For each of OP in SHL/SRL/SRA/AND...
2654   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2655   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2656   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2657   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2658        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2659       N0.getOperand(1) == N1.getOperand(1)) {
2660     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2661                                  N0.getOperand(0).getValueType(),
2662                                  N0.getOperand(0), N1.getOperand(0));
2663     AddToWorklist(ORNode.getNode());
2664     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2665                        ORNode, N0.getOperand(1));
2666   }
2667
2668   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2669   // Only perform this optimization after type legalization and before
2670   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2671   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2672   // we don't want to undo this promotion.
2673   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2674   // on scalars.
2675   if ((N0.getOpcode() == ISD::BITCAST ||
2676        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2677       Level == AfterLegalizeTypes) {
2678     SDValue In0 = N0.getOperand(0);
2679     SDValue In1 = N1.getOperand(0);
2680     EVT In0Ty = In0.getValueType();
2681     EVT In1Ty = In1.getValueType();
2682     SDLoc DL(N);
2683     // If both incoming values are integers, and the original types are the
2684     // same.
2685     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2686       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2687       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2688       AddToWorklist(Op.getNode());
2689       return BC;
2690     }
2691   }
2692
2693   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2694   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2695   // If both shuffles use the same mask, and both shuffle within a single
2696   // vector, then it is worthwhile to move the swizzle after the operation.
2697   // The type-legalizer generates this pattern when loading illegal
2698   // vector types from memory. In many cases this allows additional shuffle
2699   // optimizations.
2700   // There are other cases where moving the shuffle after the xor/and/or
2701   // is profitable even if shuffles don't perform a swizzle.
2702   // If both shuffles use the same mask, and both shuffles have the same first
2703   // or second operand, then it might still be profitable to move the shuffle
2704   // after the xor/and/or operation.
2705   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2706     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2707     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2708
2709     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2710            "Inputs to shuffles are not the same type");
2711
2712     // Check that both shuffles use the same mask. The masks are known to be of
2713     // the same length because the result vector type is the same.
2714     // Check also that shuffles have only one use to avoid introducing extra
2715     // instructions.
2716     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2717         SVN0->getMask().equals(SVN1->getMask())) {
2718       SDValue ShOp = N0->getOperand(1);
2719
2720       // Don't try to fold this node if it requires introducing a
2721       // build vector of all zeros that might be illegal at this stage.
2722       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2723         if (!LegalTypes)
2724           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2725         else
2726           ShOp = SDValue();
2727       }
2728
2729       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2730       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2731       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2732       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2733         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2734                                       N0->getOperand(0), N1->getOperand(0));
2735         AddToWorklist(NewNode.getNode());
2736         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2737                                     &SVN0->getMask()[0]);
2738       }
2739
2740       // Don't try to fold this node if it requires introducing a
2741       // build vector of all zeros that might be illegal at this stage.
2742       ShOp = N0->getOperand(0);
2743       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2744         if (!LegalTypes)
2745           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2746         else
2747           ShOp = SDValue();
2748       }
2749
2750       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2751       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2752       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2753       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2754         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2755                                       N0->getOperand(1), N1->getOperand(1));
2756         AddToWorklist(NewNode.getNode());
2757         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2758                                     &SVN0->getMask()[0]);
2759       }
2760     }
2761   }
2762
2763   return SDValue();
2764 }
2765
2766 /// This contains all DAGCombine rules which reduce two values combined by
2767 /// an And operation to a single value. This makes them reusable in the context
2768 /// of visitSELECT(). Rules involving constants are not included as
2769 /// visitSELECT() already handles those cases.
2770 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2771                                   SDNode *LocReference) {
2772   EVT VT = N1.getValueType();
2773
2774   // fold (and x, undef) -> 0
2775   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2776     return DAG.getConstant(0, SDLoc(LocReference), VT);
2777   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2778   SDValue LL, LR, RL, RR, CC0, CC1;
2779   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2780     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2781     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2782
2783     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2784         LL.getValueType().isInteger()) {
2785       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2786       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2787         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2788                                      LR.getValueType(), LL, RL);
2789         AddToWorklist(ORNode.getNode());
2790         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2791       }
2792       if (isAllOnesConstant(LR)) {
2793         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2794         if (Op1 == ISD::SETEQ) {
2795           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2796                                         LR.getValueType(), LL, RL);
2797           AddToWorklist(ANDNode.getNode());
2798           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2799         }
2800         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2801         if (Op1 == ISD::SETGT) {
2802           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2803                                        LR.getValueType(), LL, RL);
2804           AddToWorklist(ORNode.getNode());
2805           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2806         }
2807       }
2808     }
2809     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2810     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2811         Op0 == Op1 && LL.getValueType().isInteger() &&
2812       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2813                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2814       SDLoc DL(N0);
2815       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2816                                     LL, DAG.getConstant(1, DL,
2817                                                         LL.getValueType()));
2818       AddToWorklist(ADDNode.getNode());
2819       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2820                           DAG.getConstant(2, DL, LL.getValueType()),
2821                           ISD::SETUGE);
2822     }
2823     // canonicalize equivalent to ll == rl
2824     if (LL == RR && LR == RL) {
2825       Op1 = ISD::getSetCCSwappedOperands(Op1);
2826       std::swap(RL, RR);
2827     }
2828     if (LL == RL && LR == RR) {
2829       bool isInteger = LL.getValueType().isInteger();
2830       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2831       if (Result != ISD::SETCC_INVALID &&
2832           (!LegalOperations ||
2833            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2834             TLI.isOperationLegal(ISD::SETCC,
2835                             getSetCCResultType(N0.getSimpleValueType())))))
2836         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2837                             LL, LR, Result);
2838     }
2839   }
2840
2841   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2842       VT.getSizeInBits() <= 64) {
2843     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2844       APInt ADDC = ADDI->getAPIntValue();
2845       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2846         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2847         // immediate for an add, but it is legal if its top c2 bits are set,
2848         // transform the ADD so the immediate doesn't need to be materialized
2849         // in a register.
2850         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2851           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2852                                              SRLI->getZExtValue());
2853           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2854             ADDC |= Mask;
2855             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2856               SDLoc DL(N0);
2857               SDValue NewAdd =
2858                 DAG.getNode(ISD::ADD, DL, VT,
2859                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2860               CombineTo(N0.getNode(), NewAdd);
2861               // Return N so it doesn't get rechecked!
2862               return SDValue(LocReference, 0);
2863             }
2864           }
2865         }
2866       }
2867     }
2868   }
2869
2870   return SDValue();
2871 }
2872
2873 SDValue DAGCombiner::visitAND(SDNode *N) {
2874   SDValue N0 = N->getOperand(0);
2875   SDValue N1 = N->getOperand(1);
2876   EVT VT = N1.getValueType();
2877
2878   // fold vector ops
2879   if (VT.isVector()) {
2880     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2881       return FoldedVOp;
2882
2883     // fold (and x, 0) -> 0, vector edition
2884     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2885       // do not return N0, because undef node may exist in N0
2886       return DAG.getConstant(
2887           APInt::getNullValue(
2888               N0.getValueType().getScalarType().getSizeInBits()),
2889           SDLoc(N), N0.getValueType());
2890     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2891       // do not return N1, because undef node may exist in N1
2892       return DAG.getConstant(
2893           APInt::getNullValue(
2894               N1.getValueType().getScalarType().getSizeInBits()),
2895           SDLoc(N), N1.getValueType());
2896
2897     // fold (and x, -1) -> x, vector edition
2898     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2899       return N1;
2900     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2901       return N0;
2902   }
2903
2904   // fold (and c1, c2) -> c1&c2
2905   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2906   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2907   if (N0C && N1C && !N1C->isOpaque())
2908     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2909   // canonicalize constant to RHS
2910   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2911      !isConstantIntBuildVectorOrConstantInt(N1))
2912     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2913   // fold (and x, -1) -> x
2914   if (isAllOnesConstant(N1))
2915     return N0;
2916   // if (and x, c) is known to be zero, return 0
2917   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2918   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2919                                    APInt::getAllOnesValue(BitWidth)))
2920     return DAG.getConstant(0, SDLoc(N), VT);
2921   // reassociate and
2922   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2923     return RAND;
2924   // fold (and (or x, C), D) -> D if (C & D) == D
2925   if (N1C && N0.getOpcode() == ISD::OR)
2926     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2927       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2928         return N1;
2929   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2930   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2931     SDValue N0Op0 = N0.getOperand(0);
2932     APInt Mask = ~N1C->getAPIntValue();
2933     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2934     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2935       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2936                                  N0.getValueType(), N0Op0);
2937
2938       // Replace uses of the AND with uses of the Zero extend node.
2939       CombineTo(N, Zext);
2940
2941       // We actually want to replace all uses of the any_extend with the
2942       // zero_extend, to avoid duplicating things.  This will later cause this
2943       // AND to be folded.
2944       CombineTo(N0.getNode(), Zext);
2945       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2946     }
2947   }
2948   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2949   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2950   // already be zero by virtue of the width of the base type of the load.
2951   //
2952   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2953   // more cases.
2954   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2955        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2956       N0.getOpcode() == ISD::LOAD) {
2957     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2958                                          N0 : N0.getOperand(0) );
2959
2960     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2961     // This can be a pure constant or a vector splat, in which case we treat the
2962     // vector as a scalar and use the splat value.
2963     APInt Constant = APInt::getNullValue(1);
2964     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2965       Constant = C->getAPIntValue();
2966     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2967       APInt SplatValue, SplatUndef;
2968       unsigned SplatBitSize;
2969       bool HasAnyUndefs;
2970       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2971                                              SplatBitSize, HasAnyUndefs);
2972       if (IsSplat) {
2973         // Undef bits can contribute to a possible optimisation if set, so
2974         // set them.
2975         SplatValue |= SplatUndef;
2976
2977         // The splat value may be something like "0x00FFFFFF", which means 0 for
2978         // the first vector value and FF for the rest, repeating. We need a mask
2979         // that will apply equally to all members of the vector, so AND all the
2980         // lanes of the constant together.
2981         EVT VT = Vector->getValueType(0);
2982         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2983
2984         // If the splat value has been compressed to a bitlength lower
2985         // than the size of the vector lane, we need to re-expand it to
2986         // the lane size.
2987         if (BitWidth > SplatBitSize)
2988           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2989                SplatBitSize < BitWidth;
2990                SplatBitSize = SplatBitSize * 2)
2991             SplatValue |= SplatValue.shl(SplatBitSize);
2992
2993         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2994         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2995         if (SplatBitSize % BitWidth == 0) {
2996           Constant = APInt::getAllOnesValue(BitWidth);
2997           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2998             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2999         }
3000       }
3001     }
3002
3003     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3004     // actually legal and isn't going to get expanded, else this is a false
3005     // optimisation.
3006     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3007                                                     Load->getValueType(0),
3008                                                     Load->getMemoryVT());
3009
3010     // Resize the constant to the same size as the original memory access before
3011     // extension. If it is still the AllOnesValue then this AND is completely
3012     // unneeded.
3013     Constant =
3014       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3015
3016     bool B;
3017     switch (Load->getExtensionType()) {
3018     default: B = false; break;
3019     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3020     case ISD::ZEXTLOAD:
3021     case ISD::NON_EXTLOAD: B = true; break;
3022     }
3023
3024     if (B && Constant.isAllOnesValue()) {
3025       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3026       // preserve semantics once we get rid of the AND.
3027       SDValue NewLoad(Load, 0);
3028       if (Load->getExtensionType() == ISD::EXTLOAD) {
3029         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3030                               Load->getValueType(0), SDLoc(Load),
3031                               Load->getChain(), Load->getBasePtr(),
3032                               Load->getOffset(), Load->getMemoryVT(),
3033                               Load->getMemOperand());
3034         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3035         if (Load->getNumValues() == 3) {
3036           // PRE/POST_INC loads have 3 values.
3037           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3038                            NewLoad.getValue(2) };
3039           CombineTo(Load, To, 3, true);
3040         } else {
3041           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3042         }
3043       }
3044
3045       // Fold the AND away, taking care not to fold to the old load node if we
3046       // replaced it.
3047       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3048
3049       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3050     }
3051   }
3052
3053   // fold (and (load x), 255) -> (zextload x, i8)
3054   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3055   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3056   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3057               (N0.getOpcode() == ISD::ANY_EXTEND &&
3058                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3059     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3060     LoadSDNode *LN0 = HasAnyExt
3061       ? cast<LoadSDNode>(N0.getOperand(0))
3062       : cast<LoadSDNode>(N0);
3063     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3064         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3065       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3066       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3067         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3068         EVT LoadedVT = LN0->getMemoryVT();
3069         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3070
3071         if (ExtVT == LoadedVT &&
3072             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3073                                                     ExtVT))) {
3074
3075           SDValue NewLoad =
3076             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3077                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3078                            LN0->getMemOperand());
3079           AddToWorklist(N);
3080           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3081           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3082         }
3083
3084         // Do not change the width of a volatile load.
3085         // Do not generate loads of non-round integer types since these can
3086         // be expensive (and would be wrong if the type is not byte sized).
3087         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3088             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3089                                                     ExtVT))) {
3090           EVT PtrType = LN0->getOperand(1).getValueType();
3091
3092           unsigned Alignment = LN0->getAlignment();
3093           SDValue NewPtr = LN0->getBasePtr();
3094
3095           // For big endian targets, we need to add an offset to the pointer
3096           // to load the correct bytes.  For little endian systems, we merely
3097           // need to read fewer bytes from the same pointer.
3098           if (TLI.isBigEndian()) {
3099             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3100             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3101             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3102             SDLoc DL(LN0);
3103             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3104                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3105             Alignment = MinAlign(Alignment, PtrOff);
3106           }
3107
3108           AddToWorklist(NewPtr.getNode());
3109
3110           SDValue Load =
3111             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3112                            LN0->getChain(), NewPtr,
3113                            LN0->getPointerInfo(),
3114                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3115                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3116           AddToWorklist(N);
3117           CombineTo(LN0, Load, Load.getValue(1));
3118           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3119         }
3120       }
3121     }
3122   }
3123
3124   if (SDValue Combined = visitANDLike(N0, N1, N))
3125     return Combined;
3126
3127   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3128   if (N0.getOpcode() == N1.getOpcode()) {
3129     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3130     if (Tmp.getNode()) return Tmp;
3131   }
3132
3133   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3134   // fold (and (sra)) -> (and (srl)) when possible.
3135   if (!VT.isVector() &&
3136       SimplifyDemandedBits(SDValue(N, 0)))
3137     return SDValue(N, 0);
3138
3139   // fold (zext_inreg (extload x)) -> (zextload x)
3140   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3141     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3142     EVT MemVT = LN0->getMemoryVT();
3143     // If we zero all the possible extended bits, then we can turn this into
3144     // a zextload if we are running before legalize or the operation is legal.
3145     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3146     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3147                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3148         ((!LegalOperations && !LN0->isVolatile()) ||
3149          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3150       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3151                                        LN0->getChain(), LN0->getBasePtr(),
3152                                        MemVT, LN0->getMemOperand());
3153       AddToWorklist(N);
3154       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3155       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3156     }
3157   }
3158   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3159   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3160       N0.hasOneUse()) {
3161     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3162     EVT MemVT = LN0->getMemoryVT();
3163     // If we zero all the possible extended bits, then we can turn this into
3164     // a zextload if we are running before legalize or the operation is legal.
3165     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3166     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3167                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3168         ((!LegalOperations && !LN0->isVolatile()) ||
3169          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3170       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3171                                        LN0->getChain(), LN0->getBasePtr(),
3172                                        MemVT, LN0->getMemOperand());
3173       AddToWorklist(N);
3174       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3175       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3176     }
3177   }
3178   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3179   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3180     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3181                                        N0.getOperand(1), false);
3182     if (BSwap.getNode())
3183       return BSwap;
3184   }
3185
3186   return SDValue();
3187 }
3188
3189 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3190 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3191                                         bool DemandHighBits) {
3192   if (!LegalOperations)
3193     return SDValue();
3194
3195   EVT VT = N->getValueType(0);
3196   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3197     return SDValue();
3198   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3199     return SDValue();
3200
3201   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3202   bool LookPassAnd0 = false;
3203   bool LookPassAnd1 = false;
3204   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3205       std::swap(N0, N1);
3206   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3207       std::swap(N0, N1);
3208   if (N0.getOpcode() == ISD::AND) {
3209     if (!N0.getNode()->hasOneUse())
3210       return SDValue();
3211     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3212     if (!N01C || N01C->getZExtValue() != 0xFF00)
3213       return SDValue();
3214     N0 = N0.getOperand(0);
3215     LookPassAnd0 = true;
3216   }
3217
3218   if (N1.getOpcode() == ISD::AND) {
3219     if (!N1.getNode()->hasOneUse())
3220       return SDValue();
3221     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3222     if (!N11C || N11C->getZExtValue() != 0xFF)
3223       return SDValue();
3224     N1 = N1.getOperand(0);
3225     LookPassAnd1 = true;
3226   }
3227
3228   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3229     std::swap(N0, N1);
3230   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3231     return SDValue();
3232   if (!N0.getNode()->hasOneUse() ||
3233       !N1.getNode()->hasOneUse())
3234     return SDValue();
3235
3236   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3237   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3238   if (!N01C || !N11C)
3239     return SDValue();
3240   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3241     return SDValue();
3242
3243   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3244   SDValue N00 = N0->getOperand(0);
3245   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3246     if (!N00.getNode()->hasOneUse())
3247       return SDValue();
3248     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3249     if (!N001C || N001C->getZExtValue() != 0xFF)
3250       return SDValue();
3251     N00 = N00.getOperand(0);
3252     LookPassAnd0 = true;
3253   }
3254
3255   SDValue N10 = N1->getOperand(0);
3256   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3257     if (!N10.getNode()->hasOneUse())
3258       return SDValue();
3259     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3260     if (!N101C || N101C->getZExtValue() != 0xFF00)
3261       return SDValue();
3262     N10 = N10.getOperand(0);
3263     LookPassAnd1 = true;
3264   }
3265
3266   if (N00 != N10)
3267     return SDValue();
3268
3269   // Make sure everything beyond the low halfword gets set to zero since the SRL
3270   // 16 will clear the top bits.
3271   unsigned OpSizeInBits = VT.getSizeInBits();
3272   if (DemandHighBits && OpSizeInBits > 16) {
3273     // If the left-shift isn't masked out then the only way this is a bswap is
3274     // if all bits beyond the low 8 are 0. In that case the entire pattern
3275     // reduces to a left shift anyway: leave it for other parts of the combiner.
3276     if (!LookPassAnd0)
3277       return SDValue();
3278
3279     // However, if the right shift isn't masked out then it might be because
3280     // it's not needed. See if we can spot that too.
3281     if (!LookPassAnd1 &&
3282         !DAG.MaskedValueIsZero(
3283             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3284       return SDValue();
3285   }
3286
3287   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3288   if (OpSizeInBits > 16) {
3289     SDLoc DL(N);
3290     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3291                       DAG.getConstant(OpSizeInBits - 16, DL,
3292                                       getShiftAmountTy(VT)));
3293   }
3294   return Res;
3295 }
3296
3297 /// Return true if the specified node is an element that makes up a 32-bit
3298 /// packed halfword byteswap.
3299 /// ((x & 0x000000ff) << 8) |
3300 /// ((x & 0x0000ff00) >> 8) |
3301 /// ((x & 0x00ff0000) << 8) |
3302 /// ((x & 0xff000000) >> 8)
3303 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3304   if (!N.getNode()->hasOneUse())
3305     return false;
3306
3307   unsigned Opc = N.getOpcode();
3308   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3309     return false;
3310
3311   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3312   if (!N1C)
3313     return false;
3314
3315   unsigned Num;
3316   switch (N1C->getZExtValue()) {
3317   default:
3318     return false;
3319   case 0xFF:       Num = 0; break;
3320   case 0xFF00:     Num = 1; break;
3321   case 0xFF0000:   Num = 2; break;
3322   case 0xFF000000: Num = 3; break;
3323   }
3324
3325   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3326   SDValue N0 = N.getOperand(0);
3327   if (Opc == ISD::AND) {
3328     if (Num == 0 || Num == 2) {
3329       // (x >> 8) & 0xff
3330       // (x >> 8) & 0xff0000
3331       if (N0.getOpcode() != ISD::SRL)
3332         return false;
3333       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3334       if (!C || C->getZExtValue() != 8)
3335         return false;
3336     } else {
3337       // (x << 8) & 0xff00
3338       // (x << 8) & 0xff000000
3339       if (N0.getOpcode() != ISD::SHL)
3340         return false;
3341       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3342       if (!C || C->getZExtValue() != 8)
3343         return false;
3344     }
3345   } else if (Opc == ISD::SHL) {
3346     // (x & 0xff) << 8
3347     // (x & 0xff0000) << 8
3348     if (Num != 0 && Num != 2)
3349       return false;
3350     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3351     if (!C || C->getZExtValue() != 8)
3352       return false;
3353   } else { // Opc == ISD::SRL
3354     // (x & 0xff00) >> 8
3355     // (x & 0xff000000) >> 8
3356     if (Num != 1 && Num != 3)
3357       return false;
3358     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3359     if (!C || C->getZExtValue() != 8)
3360       return false;
3361   }
3362
3363   if (Parts[Num])
3364     return false;
3365
3366   Parts[Num] = N0.getOperand(0).getNode();
3367   return true;
3368 }
3369
3370 /// Match a 32-bit packed halfword bswap. That is
3371 /// ((x & 0x000000ff) << 8) |
3372 /// ((x & 0x0000ff00) >> 8) |
3373 /// ((x & 0x00ff0000) << 8) |
3374 /// ((x & 0xff000000) >> 8)
3375 /// => (rotl (bswap x), 16)
3376 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3377   if (!LegalOperations)
3378     return SDValue();
3379
3380   EVT VT = N->getValueType(0);
3381   if (VT != MVT::i32)
3382     return SDValue();
3383   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3384     return SDValue();
3385
3386   // Look for either
3387   // (or (or (and), (and)), (or (and), (and)))
3388   // (or (or (or (and), (and)), (and)), (and))
3389   if (N0.getOpcode() != ISD::OR)
3390     return SDValue();
3391   SDValue N00 = N0.getOperand(0);
3392   SDValue N01 = N0.getOperand(1);
3393   SDNode *Parts[4] = {};
3394
3395   if (N1.getOpcode() == ISD::OR &&
3396       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3397     // (or (or (and), (and)), (or (and), (and)))
3398     SDValue N000 = N00.getOperand(0);
3399     if (!isBSwapHWordElement(N000, Parts))
3400       return SDValue();
3401
3402     SDValue N001 = N00.getOperand(1);
3403     if (!isBSwapHWordElement(N001, Parts))
3404       return SDValue();
3405     SDValue N010 = N01.getOperand(0);
3406     if (!isBSwapHWordElement(N010, Parts))
3407       return SDValue();
3408     SDValue N011 = N01.getOperand(1);
3409     if (!isBSwapHWordElement(N011, Parts))
3410       return SDValue();
3411   } else {
3412     // (or (or (or (and), (and)), (and)), (and))
3413     if (!isBSwapHWordElement(N1, Parts))
3414       return SDValue();
3415     if (!isBSwapHWordElement(N01, Parts))
3416       return SDValue();
3417     if (N00.getOpcode() != ISD::OR)
3418       return SDValue();
3419     SDValue N000 = N00.getOperand(0);
3420     if (!isBSwapHWordElement(N000, Parts))
3421       return SDValue();
3422     SDValue N001 = N00.getOperand(1);
3423     if (!isBSwapHWordElement(N001, Parts))
3424       return SDValue();
3425   }
3426
3427   // Make sure the parts are all coming from the same node.
3428   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3429     return SDValue();
3430
3431   SDLoc DL(N);
3432   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3433                               SDValue(Parts[0], 0));
3434
3435   // Result of the bswap should be rotated by 16. If it's not legal, then
3436   // do  (x << 16) | (x >> 16).
3437   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3438   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3439     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3440   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3441     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3442   return DAG.getNode(ISD::OR, DL, VT,
3443                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3444                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3445 }
3446
3447 /// This contains all DAGCombine rules which reduce two values combined by
3448 /// an Or operation to a single value \see visitANDLike().
3449 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3450   EVT VT = N1.getValueType();
3451   // fold (or x, undef) -> -1
3452   if (!LegalOperations &&
3453       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3454     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3455     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3456                            SDLoc(LocReference), VT);
3457   }
3458   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3459   SDValue LL, LR, RL, RR, CC0, CC1;
3460   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3461     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3462     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3463
3464     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3465       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3466       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3467       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3468         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3469                                      LR.getValueType(), LL, RL);
3470         AddToWorklist(ORNode.getNode());
3471         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3472       }
3473       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3474       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3475       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3476         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3477                                       LR.getValueType(), LL, RL);
3478         AddToWorklist(ANDNode.getNode());
3479         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3480       }
3481     }
3482     // canonicalize equivalent to ll == rl
3483     if (LL == RR && LR == RL) {
3484       Op1 = ISD::getSetCCSwappedOperands(Op1);
3485       std::swap(RL, RR);
3486     }
3487     if (LL == RL && LR == RR) {
3488       bool isInteger = LL.getValueType().isInteger();
3489       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3490       if (Result != ISD::SETCC_INVALID &&
3491           (!LegalOperations ||
3492            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3493             TLI.isOperationLegal(ISD::SETCC,
3494               getSetCCResultType(N0.getValueType())))))
3495         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3496                             LL, LR, Result);
3497     }
3498   }
3499
3500   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3501   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3502       // Don't increase # computations.
3503       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3504     // We can only do this xform if we know that bits from X that are set in C2
3505     // but not in C1 are already zero.  Likewise for Y.
3506     if (const ConstantSDNode *N0O1C =
3507         getAsNonOpaqueConstant(N0.getOperand(1))) {
3508       if (const ConstantSDNode *N1O1C =
3509           getAsNonOpaqueConstant(N1.getOperand(1))) {
3510         // We can only do this xform if we know that bits from X that are set in
3511         // C2 but not in C1 are already zero.  Likewise for Y.
3512         const APInt &LHSMask = N0O1C->getAPIntValue();
3513         const APInt &RHSMask = N1O1C->getAPIntValue();
3514
3515         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3516             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3517           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3518                                   N0.getOperand(0), N1.getOperand(0));
3519           SDLoc DL(LocReference);
3520           return DAG.getNode(ISD::AND, DL, VT, X,
3521                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3522         }
3523       }
3524     }
3525   }
3526
3527   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3528   if (N0.getOpcode() == ISD::AND &&
3529       N1.getOpcode() == ISD::AND &&
3530       N0.getOperand(0) == N1.getOperand(0) &&
3531       // Don't increase # computations.
3532       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3533     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3534                             N0.getOperand(1), N1.getOperand(1));
3535     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3536   }
3537
3538   return SDValue();
3539 }
3540
3541 SDValue DAGCombiner::visitOR(SDNode *N) {
3542   SDValue N0 = N->getOperand(0);
3543   SDValue N1 = N->getOperand(1);
3544   EVT VT = N1.getValueType();
3545
3546   // fold vector ops
3547   if (VT.isVector()) {
3548     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3549       return FoldedVOp;
3550
3551     // fold (or x, 0) -> x, vector edition
3552     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3553       return N1;
3554     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3555       return N0;
3556
3557     // fold (or x, -1) -> -1, vector edition
3558     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3559       // do not return N0, because undef node may exist in N0
3560       return DAG.getConstant(
3561           APInt::getAllOnesValue(
3562               N0.getValueType().getScalarType().getSizeInBits()),
3563           SDLoc(N), N0.getValueType());
3564     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3565       // do not return N1, because undef node may exist in N1
3566       return DAG.getConstant(
3567           APInt::getAllOnesValue(
3568               N1.getValueType().getScalarType().getSizeInBits()),
3569           SDLoc(N), N1.getValueType());
3570
3571     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3572     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3573     // Do this only if the resulting shuffle is legal.
3574     if (isa<ShuffleVectorSDNode>(N0) &&
3575         isa<ShuffleVectorSDNode>(N1) &&
3576         // Avoid folding a node with illegal type.
3577         TLI.isTypeLegal(VT) &&
3578         N0->getOperand(1) == N1->getOperand(1) &&
3579         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3580       bool CanFold = true;
3581       unsigned NumElts = VT.getVectorNumElements();
3582       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3583       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3584       // We construct two shuffle masks:
3585       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3586       // and N1 as the second operand.
3587       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3588       // and N0 as the second operand.
3589       // We do this because OR is commutable and therefore there might be
3590       // two ways to fold this node into a shuffle.
3591       SmallVector<int,4> Mask1;
3592       SmallVector<int,4> Mask2;
3593
3594       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3595         int M0 = SV0->getMaskElt(i);
3596         int M1 = SV1->getMaskElt(i);
3597
3598         // Both shuffle indexes are undef. Propagate Undef.
3599         if (M0 < 0 && M1 < 0) {
3600           Mask1.push_back(M0);
3601           Mask2.push_back(M0);
3602           continue;
3603         }
3604
3605         if (M0 < 0 || M1 < 0 ||
3606             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3607             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3608           CanFold = false;
3609           break;
3610         }
3611
3612         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3613         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3614       }
3615
3616       if (CanFold) {
3617         // Fold this sequence only if the resulting shuffle is 'legal'.
3618         if (TLI.isShuffleMaskLegal(Mask1, VT))
3619           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3620                                       N1->getOperand(0), &Mask1[0]);
3621         if (TLI.isShuffleMaskLegal(Mask2, VT))
3622           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3623                                       N0->getOperand(0), &Mask2[0]);
3624       }
3625     }
3626   }
3627
3628   // fold (or c1, c2) -> c1|c2
3629   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3630   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3631   if (N0C && N1C && !N1C->isOpaque())
3632     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3633   // canonicalize constant to RHS
3634   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3635      !isConstantIntBuildVectorOrConstantInt(N1))
3636     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3637   // fold (or x, 0) -> x
3638   if (isNullConstant(N1))
3639     return N0;
3640   // fold (or x, -1) -> -1
3641   if (isAllOnesConstant(N1))
3642     return N1;
3643   // fold (or x, c) -> c iff (x & ~c) == 0
3644   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3645     return N1;
3646
3647   if (SDValue Combined = visitORLike(N0, N1, N))
3648     return Combined;
3649
3650   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3651   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3652   if (BSwap.getNode())
3653     return BSwap;
3654   BSwap = MatchBSwapHWordLow(N, N0, N1);
3655   if (BSwap.getNode())
3656     return BSwap;
3657
3658   // reassociate or
3659   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3660     return ROR;
3661   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3662   // iff (c1 & c2) == 0.
3663   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3664              isa<ConstantSDNode>(N0.getOperand(1))) {
3665     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3666     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3667       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3668                                                    N1C, C1))
3669         return DAG.getNode(
3670             ISD::AND, SDLoc(N), VT,
3671             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3672       return SDValue();
3673     }
3674   }
3675   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3676   if (N0.getOpcode() == N1.getOpcode()) {
3677     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3678     if (Tmp.getNode()) return Tmp;
3679   }
3680
3681   // See if this is some rotate idiom.
3682   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3683     return SDValue(Rot, 0);
3684
3685   // Simplify the operands using demanded-bits information.
3686   if (!VT.isVector() &&
3687       SimplifyDemandedBits(SDValue(N, 0)))
3688     return SDValue(N, 0);
3689
3690   return SDValue();
3691 }
3692
3693 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3694 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3695   if (Op.getOpcode() == ISD::AND) {
3696     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3697       Mask = Op.getOperand(1);
3698       Op = Op.getOperand(0);
3699     } else {
3700       return false;
3701     }
3702   }
3703
3704   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3705     Shift = Op;
3706     return true;
3707   }
3708
3709   return false;
3710 }
3711
3712 // Return true if we can prove that, whenever Neg and Pos are both in the
3713 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3714 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3715 //
3716 //     (or (shift1 X, Neg), (shift2 X, Pos))
3717 //
3718 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3719 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3720 // to consider shift amounts with defined behavior.
3721 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3722   // If OpSize is a power of 2 then:
3723   //
3724   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3725   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3726   //
3727   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3728   // for the stronger condition:
3729   //
3730   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3731   //
3732   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3733   // we can just replace Neg with Neg' for the rest of the function.
3734   //
3735   // In other cases we check for the even stronger condition:
3736   //
3737   //     Neg == OpSize - Pos                                    [B]
3738   //
3739   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3740   // behavior if Pos == 0 (and consequently Neg == OpSize).
3741   //
3742   // We could actually use [A] whenever OpSize is a power of 2, but the
3743   // only extra cases that it would match are those uninteresting ones
3744   // where Neg and Pos are never in range at the same time.  E.g. for
3745   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3746   // as well as (sub 32, Pos), but:
3747   //
3748   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3749   //
3750   // always invokes undefined behavior for 32-bit X.
3751   //
3752   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3753   unsigned MaskLoBits = 0;
3754   if (Neg.getOpcode() == ISD::AND &&
3755       isPowerOf2_64(OpSize) &&
3756       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3757       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3758     Neg = Neg.getOperand(0);
3759     MaskLoBits = Log2_64(OpSize);
3760   }
3761
3762   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3763   if (Neg.getOpcode() != ISD::SUB)
3764     return 0;
3765   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3766   if (!NegC)
3767     return 0;
3768   SDValue NegOp1 = Neg.getOperand(1);
3769
3770   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3771   // Pos'.  The truncation is redundant for the purpose of the equality.
3772   if (MaskLoBits &&
3773       Pos.getOpcode() == ISD::AND &&
3774       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3775       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3776     Pos = Pos.getOperand(0);
3777
3778   // The condition we need is now:
3779   //
3780   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3781   //
3782   // If NegOp1 == Pos then we need:
3783   //
3784   //              OpSize & Mask == NegC & Mask
3785   //
3786   // (because "x & Mask" is a truncation and distributes through subtraction).
3787   APInt Width;
3788   if (Pos == NegOp1)
3789     Width = NegC->getAPIntValue();
3790   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3791   // Then the condition we want to prove becomes:
3792   //
3793   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3794   //
3795   // which, again because "x & Mask" is a truncation, becomes:
3796   //
3797   //                NegC & Mask == (OpSize - PosC) & Mask
3798   //              OpSize & Mask == (NegC + PosC) & Mask
3799   else if (Pos.getOpcode() == ISD::ADD &&
3800            Pos.getOperand(0) == NegOp1 &&
3801            Pos.getOperand(1).getOpcode() == ISD::Constant)
3802     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3803              NegC->getAPIntValue());
3804   else
3805     return false;
3806
3807   // Now we just need to check that OpSize & Mask == Width & Mask.
3808   if (MaskLoBits)
3809     // Opsize & Mask is 0 since Mask is Opsize - 1.
3810     return Width.getLoBits(MaskLoBits) == 0;
3811   return Width == OpSize;
3812 }
3813
3814 // A subroutine of MatchRotate used once we have found an OR of two opposite
3815 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3816 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3817 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3818 // Neg with outer conversions stripped away.
3819 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3820                                        SDValue Neg, SDValue InnerPos,
3821                                        SDValue InnerNeg, unsigned PosOpcode,
3822                                        unsigned NegOpcode, SDLoc DL) {
3823   // fold (or (shl x, (*ext y)),
3824   //          (srl x, (*ext (sub 32, y)))) ->
3825   //   (rotl x, y) or (rotr x, (sub 32, y))
3826   //
3827   // fold (or (shl x, (*ext (sub 32, y))),
3828   //          (srl x, (*ext y))) ->
3829   //   (rotr x, y) or (rotl x, (sub 32, y))
3830   EVT VT = Shifted.getValueType();
3831   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3832     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3833     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3834                        HasPos ? Pos : Neg).getNode();
3835   }
3836
3837   return nullptr;
3838 }
3839
3840 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3841 // idioms for rotate, and if the target supports rotation instructions, generate
3842 // a rot[lr].
3843 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3844   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3845   EVT VT = LHS.getValueType();
3846   if (!TLI.isTypeLegal(VT)) return nullptr;
3847
3848   // The target must have at least one rotate flavor.
3849   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3850   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3851   if (!HasROTL && !HasROTR) return nullptr;
3852
3853   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3854   SDValue LHSShift;   // The shift.
3855   SDValue LHSMask;    // AND value if any.
3856   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3857     return nullptr; // Not part of a rotate.
3858
3859   SDValue RHSShift;   // The shift.
3860   SDValue RHSMask;    // AND value if any.
3861   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3862     return nullptr; // Not part of a rotate.
3863
3864   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3865     return nullptr;   // Not shifting the same value.
3866
3867   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3868     return nullptr;   // Shifts must disagree.
3869
3870   // Canonicalize shl to left side in a shl/srl pair.
3871   if (RHSShift.getOpcode() == ISD::SHL) {
3872     std::swap(LHS, RHS);
3873     std::swap(LHSShift, RHSShift);
3874     std::swap(LHSMask , RHSMask );
3875   }
3876
3877   unsigned OpSizeInBits = VT.getSizeInBits();
3878   SDValue LHSShiftArg = LHSShift.getOperand(0);
3879   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3880   SDValue RHSShiftArg = RHSShift.getOperand(0);
3881   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3882
3883   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3884   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3885   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3886       RHSShiftAmt.getOpcode() == ISD::Constant) {
3887     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3888     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3889     if ((LShVal + RShVal) != OpSizeInBits)
3890       return nullptr;
3891
3892     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3893                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3894
3895     // If there is an AND of either shifted operand, apply it to the result.
3896     if (LHSMask.getNode() || RHSMask.getNode()) {
3897       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3898
3899       if (LHSMask.getNode()) {
3900         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3901         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3902       }
3903       if (RHSMask.getNode()) {
3904         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3905         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3906       }
3907
3908       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3909     }
3910
3911     return Rot.getNode();
3912   }
3913
3914   // If there is a mask here, and we have a variable shift, we can't be sure
3915   // that we're masking out the right stuff.
3916   if (LHSMask.getNode() || RHSMask.getNode())
3917     return nullptr;
3918
3919   // If the shift amount is sign/zext/any-extended just peel it off.
3920   SDValue LExtOp0 = LHSShiftAmt;
3921   SDValue RExtOp0 = RHSShiftAmt;
3922   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3923        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3924        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3925        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3926       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3927        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3928        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3929        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3930     LExtOp0 = LHSShiftAmt.getOperand(0);
3931     RExtOp0 = RHSShiftAmt.getOperand(0);
3932   }
3933
3934   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3935                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3936   if (TryL)
3937     return TryL;
3938
3939   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3940                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3941   if (TryR)
3942     return TryR;
3943
3944   return nullptr;
3945 }
3946
3947 SDValue DAGCombiner::visitXOR(SDNode *N) {
3948   SDValue N0 = N->getOperand(0);
3949   SDValue N1 = N->getOperand(1);
3950   EVT VT = N0.getValueType();
3951
3952   // fold vector ops
3953   if (VT.isVector()) {
3954     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3955       return FoldedVOp;
3956
3957     // fold (xor x, 0) -> x, vector edition
3958     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3959       return N1;
3960     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3961       return N0;
3962   }
3963
3964   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3965   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3966     return DAG.getConstant(0, SDLoc(N), VT);
3967   // fold (xor x, undef) -> undef
3968   if (N0.getOpcode() == ISD::UNDEF)
3969     return N0;
3970   if (N1.getOpcode() == ISD::UNDEF)
3971     return N1;
3972   // fold (xor c1, c2) -> c1^c2
3973   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3974   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3975   if (N0C && N1C)
3976     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3977   // canonicalize constant to RHS
3978   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3979      !isConstantIntBuildVectorOrConstantInt(N1))
3980     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3981   // fold (xor x, 0) -> x
3982   if (isNullConstant(N1))
3983     return N0;
3984   // reassociate xor
3985   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3986     return RXOR;
3987
3988   // fold !(x cc y) -> (x !cc y)
3989   SDValue LHS, RHS, CC;
3990   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3991     bool isInt = LHS.getValueType().isInteger();
3992     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3993                                                isInt);
3994
3995     if (!LegalOperations ||
3996         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3997       switch (N0.getOpcode()) {
3998       default:
3999         llvm_unreachable("Unhandled SetCC Equivalent!");
4000       case ISD::SETCC:
4001         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4002       case ISD::SELECT_CC:
4003         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4004                                N0.getOperand(3), NotCC);
4005       }
4006     }
4007   }
4008
4009   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4010   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4011       N0.getNode()->hasOneUse() &&
4012       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4013     SDValue V = N0.getOperand(0);
4014     SDLoc DL(N0);
4015     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4016                     DAG.getConstant(1, DL, V.getValueType()));
4017     AddToWorklist(V.getNode());
4018     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4019   }
4020
4021   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4022   if (isOneConstant(N1) && VT == MVT::i1 &&
4023       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4024     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4025     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4026       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4027       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4028       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4029       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4030       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4031     }
4032   }
4033   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4034   if (isAllOnesConstant(N1) &&
4035       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4036     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4037     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4038       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4039       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4040       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4041       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4042       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4043     }
4044   }
4045   // fold (xor (and x, y), y) -> (and (not x), y)
4046   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4047       N0->getOperand(1) == N1) {
4048     SDValue X = N0->getOperand(0);
4049     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4050     AddToWorklist(NotX.getNode());
4051     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4052   }
4053   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4054   if (N1C && N0.getOpcode() == ISD::XOR) {
4055     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4056       SDLoc DL(N);
4057       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4058                          DAG.getConstant(N1C->getAPIntValue() ^
4059                                          N00C->getAPIntValue(), DL, VT));
4060     }
4061     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4062       SDLoc DL(N);
4063       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4064                          DAG.getConstant(N1C->getAPIntValue() ^
4065                                          N01C->getAPIntValue(), DL, VT));
4066     }
4067   }
4068   // fold (xor x, x) -> 0
4069   if (N0 == N1)
4070     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4071
4072   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4073   // Here is a concrete example of this equivalence:
4074   // i16   x ==  14
4075   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4076   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4077   //
4078   // =>
4079   //
4080   // i16     ~1      == 0b1111111111111110
4081   // i16 rol(~1, 14) == 0b1011111111111111
4082   //
4083   // Some additional tips to help conceptualize this transform:
4084   // - Try to see the operation as placing a single zero in a value of all ones.
4085   // - There exists no value for x which would allow the result to contain zero.
4086   // - Values of x larger than the bitwidth are undefined and do not require a
4087   //   consistent result.
4088   // - Pushing the zero left requires shifting one bits in from the right.
4089   // A rotate left of ~1 is a nice way of achieving the desired result.
4090   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4091       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4092     SDLoc DL(N);
4093     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4094                        N0.getOperand(1));
4095   }
4096
4097   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4098   if (N0.getOpcode() == N1.getOpcode()) {
4099     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4100     if (Tmp.getNode()) return Tmp;
4101   }
4102
4103   // Simplify the expression using non-local knowledge.
4104   if (!VT.isVector() &&
4105       SimplifyDemandedBits(SDValue(N, 0)))
4106     return SDValue(N, 0);
4107
4108   return SDValue();
4109 }
4110
4111 /// Handle transforms common to the three shifts, when the shift amount is a
4112 /// constant.
4113 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4114   SDNode *LHS = N->getOperand(0).getNode();
4115   if (!LHS->hasOneUse()) return SDValue();
4116
4117   // We want to pull some binops through shifts, so that we have (and (shift))
4118   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4119   // thing happens with address calculations, so it's important to canonicalize
4120   // it.
4121   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4122
4123   switch (LHS->getOpcode()) {
4124   default: return SDValue();
4125   case ISD::OR:
4126   case ISD::XOR:
4127     HighBitSet = false; // We can only transform sra if the high bit is clear.
4128     break;
4129   case ISD::AND:
4130     HighBitSet = true;  // We can only transform sra if the high bit is set.
4131     break;
4132   case ISD::ADD:
4133     if (N->getOpcode() != ISD::SHL)
4134       return SDValue(); // only shl(add) not sr[al](add).
4135     HighBitSet = false; // We can only transform sra if the high bit is clear.
4136     break;
4137   }
4138
4139   // We require the RHS of the binop to be a constant and not opaque as well.
4140   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4141   if (!BinOpCst) return SDValue();
4142
4143   // FIXME: disable this unless the input to the binop is a shift by a constant.
4144   // If it is not a shift, it pessimizes some common cases like:
4145   //
4146   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4147   //    int bar(int *X, int i) { return X[i & 255]; }
4148   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4149   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4150        BinOpLHSVal->getOpcode() != ISD::SRA &&
4151        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4152       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4153     return SDValue();
4154
4155   EVT VT = N->getValueType(0);
4156
4157   // If this is a signed shift right, and the high bit is modified by the
4158   // logical operation, do not perform the transformation. The highBitSet
4159   // boolean indicates the value of the high bit of the constant which would
4160   // cause it to be modified for this operation.
4161   if (N->getOpcode() == ISD::SRA) {
4162     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4163     if (BinOpRHSSignSet != HighBitSet)
4164       return SDValue();
4165   }
4166
4167   if (!TLI.isDesirableToCommuteWithShift(LHS))
4168     return SDValue();
4169
4170   // Fold the constants, shifting the binop RHS by the shift amount.
4171   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4172                                N->getValueType(0),
4173                                LHS->getOperand(1), N->getOperand(1));
4174   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4175
4176   // Create the new shift.
4177   SDValue NewShift = DAG.getNode(N->getOpcode(),
4178                                  SDLoc(LHS->getOperand(0)),
4179                                  VT, LHS->getOperand(0), N->getOperand(1));
4180
4181   // Create the new binop.
4182   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4183 }
4184
4185 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4186   assert(N->getOpcode() == ISD::TRUNCATE);
4187   assert(N->getOperand(0).getOpcode() == ISD::AND);
4188
4189   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4190   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4191     SDValue N01 = N->getOperand(0).getOperand(1);
4192
4193     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4194       if (!N01C->isOpaque()) {
4195         EVT TruncVT = N->getValueType(0);
4196         SDValue N00 = N->getOperand(0).getOperand(0);
4197         APInt TruncC = N01C->getAPIntValue();
4198         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4199         SDLoc DL(N);
4200
4201         return DAG.getNode(ISD::AND, DL, TruncVT,
4202                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4203                            DAG.getConstant(TruncC, DL, TruncVT));
4204       }
4205     }
4206   }
4207
4208   return SDValue();
4209 }
4210
4211 SDValue DAGCombiner::visitRotate(SDNode *N) {
4212   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4213   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4214       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4215     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4216     if (NewOp1.getNode())
4217       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4218                          N->getOperand(0), NewOp1);
4219   }
4220   return SDValue();
4221 }
4222
4223 SDValue DAGCombiner::visitSHL(SDNode *N) {
4224   SDValue N0 = N->getOperand(0);
4225   SDValue N1 = N->getOperand(1);
4226   EVT VT = N0.getValueType();
4227   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4228
4229   // fold vector ops
4230   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4231   if (VT.isVector()) {
4232     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4233       return FoldedVOp;
4234
4235     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4236     // If setcc produces all-one true value then:
4237     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4238     if (N1CV && N1CV->isConstant()) {
4239       if (N0.getOpcode() == ISD::AND) {
4240         SDValue N00 = N0->getOperand(0);
4241         SDValue N01 = N0->getOperand(1);
4242         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4243
4244         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4245             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4246                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4247           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4248                                                      N01CV, N1CV))
4249             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4250         }
4251       } else {
4252         N1C = isConstOrConstSplat(N1);
4253       }
4254     }
4255   }
4256
4257   // fold (shl c1, c2) -> c1<<c2
4258   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4259   if (N0C && N1C && !N1C->isOpaque())
4260     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4261   // fold (shl 0, x) -> 0
4262   if (isNullConstant(N0))
4263     return N0;
4264   // fold (shl x, c >= size(x)) -> undef
4265   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4266     return DAG.getUNDEF(VT);
4267   // fold (shl x, 0) -> x
4268   if (N1C && N1C->isNullValue())
4269     return N0;
4270   // fold (shl undef, x) -> 0
4271   if (N0.getOpcode() == ISD::UNDEF)
4272     return DAG.getConstant(0, SDLoc(N), VT);
4273   // if (shl x, c) is known to be zero, return 0
4274   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4275                             APInt::getAllOnesValue(OpSizeInBits)))
4276     return DAG.getConstant(0, SDLoc(N), VT);
4277   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4278   if (N1.getOpcode() == ISD::TRUNCATE &&
4279       N1.getOperand(0).getOpcode() == ISD::AND) {
4280     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4281     if (NewOp1.getNode())
4282       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4283   }
4284
4285   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4286     return SDValue(N, 0);
4287
4288   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4289   if (N1C && N0.getOpcode() == ISD::SHL) {
4290     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4291       uint64_t c1 = N0C1->getZExtValue();
4292       uint64_t c2 = N1C->getZExtValue();
4293       SDLoc DL(N);
4294       if (c1 + c2 >= OpSizeInBits)
4295         return DAG.getConstant(0, DL, VT);
4296       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4297                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4298     }
4299   }
4300
4301   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4302   // For this to be valid, the second form must not preserve any of the bits
4303   // that are shifted out by the inner shift in the first form.  This means
4304   // the outer shift size must be >= the number of bits added by the ext.
4305   // As a corollary, we don't care what kind of ext it is.
4306   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4307               N0.getOpcode() == ISD::ANY_EXTEND ||
4308               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4309       N0.getOperand(0).getOpcode() == ISD::SHL) {
4310     SDValue N0Op0 = N0.getOperand(0);
4311     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4312       uint64_t c1 = N0Op0C1->getZExtValue();
4313       uint64_t c2 = N1C->getZExtValue();
4314       EVT InnerShiftVT = N0Op0.getValueType();
4315       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4316       if (c2 >= OpSizeInBits - InnerShiftSize) {
4317         SDLoc DL(N0);
4318         if (c1 + c2 >= OpSizeInBits)
4319           return DAG.getConstant(0, DL, VT);
4320         return DAG.getNode(ISD::SHL, DL, VT,
4321                            DAG.getNode(N0.getOpcode(), DL, VT,
4322                                        N0Op0->getOperand(0)),
4323                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4324       }
4325     }
4326   }
4327
4328   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4329   // Only fold this if the inner zext has no other uses to avoid increasing
4330   // the total number of instructions.
4331   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4332       N0.getOperand(0).getOpcode() == ISD::SRL) {
4333     SDValue N0Op0 = N0.getOperand(0);
4334     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4335       uint64_t c1 = N0Op0C1->getZExtValue();
4336       if (c1 < VT.getScalarSizeInBits()) {
4337         uint64_t c2 = N1C->getZExtValue();
4338         if (c1 == c2) {
4339           SDValue NewOp0 = N0.getOperand(0);
4340           EVT CountVT = NewOp0.getOperand(1).getValueType();
4341           SDLoc DL(N);
4342           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4343                                        NewOp0,
4344                                        DAG.getConstant(c2, DL, CountVT));
4345           AddToWorklist(NewSHL.getNode());
4346           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4347         }
4348       }
4349     }
4350   }
4351
4352   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4353   //                               (and (srl x, (sub c1, c2), MASK)
4354   // Only fold this if the inner shift has no other uses -- if it does, folding
4355   // this will increase the total number of instructions.
4356   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4357     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4358       uint64_t c1 = N0C1->getZExtValue();
4359       if (c1 < OpSizeInBits) {
4360         uint64_t c2 = N1C->getZExtValue();
4361         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4362         SDValue Shift;
4363         if (c2 > c1) {
4364           Mask = Mask.shl(c2 - c1);
4365           SDLoc DL(N);
4366           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4367                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4368         } else {
4369           Mask = Mask.lshr(c1 - c2);
4370           SDLoc DL(N);
4371           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4372                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4373         }
4374         SDLoc DL(N0);
4375         return DAG.getNode(ISD::AND, DL, VT, Shift,
4376                            DAG.getConstant(Mask, DL, VT));
4377       }
4378     }
4379   }
4380   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4381   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4382     unsigned BitSize = VT.getScalarSizeInBits();
4383     SDLoc DL(N);
4384     SDValue HiBitsMask =
4385       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4386                                             BitSize - N1C->getZExtValue()),
4387                       DL, VT);
4388     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4389                        HiBitsMask);
4390   }
4391
4392   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4393   // Variant of version done on multiply, except mul by a power of 2 is turned
4394   // into a shift.
4395   APInt Val;
4396   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4397       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4398        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4399     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4400     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4401     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4402   }
4403
4404   if (N1C && !N1C->isOpaque()) {
4405     SDValue NewSHL = visitShiftByConstant(N, N1C);
4406     if (NewSHL.getNode())
4407       return NewSHL;
4408   }
4409
4410   return SDValue();
4411 }
4412
4413 SDValue DAGCombiner::visitSRA(SDNode *N) {
4414   SDValue N0 = N->getOperand(0);
4415   SDValue N1 = N->getOperand(1);
4416   EVT VT = N0.getValueType();
4417   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4418
4419   // fold vector ops
4420   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4421   if (VT.isVector()) {
4422     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4423       return FoldedVOp;
4424
4425     N1C = isConstOrConstSplat(N1);
4426   }
4427
4428   // fold (sra c1, c2) -> (sra c1, c2)
4429   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4430   if (N0C && N1C && !N1C->isOpaque())
4431     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4432   // fold (sra 0, x) -> 0
4433   if (isNullConstant(N0))
4434     return N0;
4435   // fold (sra -1, x) -> -1
4436   if (isAllOnesConstant(N0))
4437     return N0;
4438   // fold (sra x, (setge c, size(x))) -> undef
4439   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4440     return DAG.getUNDEF(VT);
4441   // fold (sra x, 0) -> x
4442   if (N1C && N1C->isNullValue())
4443     return N0;
4444   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4445   // sext_inreg.
4446   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4447     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4448     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4449     if (VT.isVector())
4450       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4451                                ExtVT, VT.getVectorNumElements());
4452     if ((!LegalOperations ||
4453          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4454       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4455                          N0.getOperand(0), DAG.getValueType(ExtVT));
4456   }
4457
4458   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4459   if (N1C && N0.getOpcode() == ISD::SRA) {
4460     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4461       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4462       if (Sum >= OpSizeInBits)
4463         Sum = OpSizeInBits - 1;
4464       SDLoc DL(N);
4465       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4466                          DAG.getConstant(Sum, DL, N1.getValueType()));
4467     }
4468   }
4469
4470   // fold (sra (shl X, m), (sub result_size, n))
4471   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4472   // result_size - n != m.
4473   // If truncate is free for the target sext(shl) is likely to result in better
4474   // code.
4475   if (N0.getOpcode() == ISD::SHL && N1C) {
4476     // Get the two constanst of the shifts, CN0 = m, CN = n.
4477     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4478     if (N01C) {
4479       LLVMContext &Ctx = *DAG.getContext();
4480       // Determine what the truncate's result bitsize and type would be.
4481       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4482
4483       if (VT.isVector())
4484         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4485
4486       // Determine the residual right-shift amount.
4487       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4488
4489       // If the shift is not a no-op (in which case this should be just a sign
4490       // extend already), the truncated to type is legal, sign_extend is legal
4491       // on that type, and the truncate to that type is both legal and free,
4492       // perform the transform.
4493       if ((ShiftAmt > 0) &&
4494           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4495           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4496           TLI.isTruncateFree(VT, TruncVT)) {
4497
4498         SDLoc DL(N);
4499         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4500             getShiftAmountTy(N0.getOperand(0).getValueType()));
4501         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4502                                     N0.getOperand(0), Amt);
4503         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4504                                     Shift);
4505         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4506                            N->getValueType(0), Trunc);
4507       }
4508     }
4509   }
4510
4511   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4512   if (N1.getOpcode() == ISD::TRUNCATE &&
4513       N1.getOperand(0).getOpcode() == ISD::AND) {
4514     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4515     if (NewOp1.getNode())
4516       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4517   }
4518
4519   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4520   //      if c1 is equal to the number of bits the trunc removes
4521   if (N0.getOpcode() == ISD::TRUNCATE &&
4522       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4523        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4524       N0.getOperand(0).hasOneUse() &&
4525       N0.getOperand(0).getOperand(1).hasOneUse() &&
4526       N1C) {
4527     SDValue N0Op0 = N0.getOperand(0);
4528     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4529       unsigned LargeShiftVal = LargeShift->getZExtValue();
4530       EVT LargeVT = N0Op0.getValueType();
4531
4532       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4533         SDLoc DL(N);
4534         SDValue Amt =
4535           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4536                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4537         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4538                                   N0Op0.getOperand(0), Amt);
4539         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4540       }
4541     }
4542   }
4543
4544   // Simplify, based on bits shifted out of the LHS.
4545   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4546     return SDValue(N, 0);
4547
4548
4549   // If the sign bit is known to be zero, switch this to a SRL.
4550   if (DAG.SignBitIsZero(N0))
4551     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4552
4553   if (N1C && !N1C->isOpaque()) {
4554     SDValue NewSRA = visitShiftByConstant(N, N1C);
4555     if (NewSRA.getNode())
4556       return NewSRA;
4557   }
4558
4559   return SDValue();
4560 }
4561
4562 SDValue DAGCombiner::visitSRL(SDNode *N) {
4563   SDValue N0 = N->getOperand(0);
4564   SDValue N1 = N->getOperand(1);
4565   EVT VT = N0.getValueType();
4566   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4567
4568   // fold vector ops
4569   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4570   if (VT.isVector()) {
4571     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4572       return FoldedVOp;
4573
4574     N1C = isConstOrConstSplat(N1);
4575   }
4576
4577   // fold (srl c1, c2) -> c1 >>u c2
4578   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4579   if (N0C && N1C && !N1C->isOpaque())
4580     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4581   // fold (srl 0, x) -> 0
4582   if (isNullConstant(N0))
4583     return N0;
4584   // fold (srl x, c >= size(x)) -> undef
4585   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4586     return DAG.getUNDEF(VT);
4587   // fold (srl x, 0) -> x
4588   if (N1C && N1C->isNullValue())
4589     return N0;
4590   // if (srl x, c) is known to be zero, return 0
4591   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4592                                    APInt::getAllOnesValue(OpSizeInBits)))
4593     return DAG.getConstant(0, SDLoc(N), VT);
4594
4595   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4596   if (N1C && N0.getOpcode() == ISD::SRL) {
4597     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4598       uint64_t c1 = N01C->getZExtValue();
4599       uint64_t c2 = N1C->getZExtValue();
4600       SDLoc DL(N);
4601       if (c1 + c2 >= OpSizeInBits)
4602         return DAG.getConstant(0, DL, VT);
4603       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4604                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4605     }
4606   }
4607
4608   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4609   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4610       N0.getOperand(0).getOpcode() == ISD::SRL &&
4611       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4612     uint64_t c1 =
4613       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4614     uint64_t c2 = N1C->getZExtValue();
4615     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4616     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4617     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4618     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4619     if (c1 + OpSizeInBits == InnerShiftSize) {
4620       SDLoc DL(N0);
4621       if (c1 + c2 >= InnerShiftSize)
4622         return DAG.getConstant(0, DL, VT);
4623       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4624                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4625                                      N0.getOperand(0)->getOperand(0),
4626                                      DAG.getConstant(c1 + c2, DL,
4627                                                      ShiftCountVT)));
4628     }
4629   }
4630
4631   // fold (srl (shl x, c), c) -> (and x, cst2)
4632   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4633     unsigned BitSize = N0.getScalarValueSizeInBits();
4634     if (BitSize <= 64) {
4635       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4636       SDLoc DL(N);
4637       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4638                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4639     }
4640   }
4641
4642   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4643   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4644     // Shifting in all undef bits?
4645     EVT SmallVT = N0.getOperand(0).getValueType();
4646     unsigned BitSize = SmallVT.getScalarSizeInBits();
4647     if (N1C->getZExtValue() >= BitSize)
4648       return DAG.getUNDEF(VT);
4649
4650     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4651       uint64_t ShiftAmt = N1C->getZExtValue();
4652       SDLoc DL0(N0);
4653       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4654                                        N0.getOperand(0),
4655                           DAG.getConstant(ShiftAmt, DL0,
4656                                           getShiftAmountTy(SmallVT)));
4657       AddToWorklist(SmallShift.getNode());
4658       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4659       SDLoc DL(N);
4660       return DAG.getNode(ISD::AND, DL, VT,
4661                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4662                          DAG.getConstant(Mask, DL, VT));
4663     }
4664   }
4665
4666   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4667   // bit, which is unmodified by sra.
4668   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4669     if (N0.getOpcode() == ISD::SRA)
4670       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4671   }
4672
4673   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4674   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4675       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4676     APInt KnownZero, KnownOne;
4677     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4678
4679     // If any of the input bits are KnownOne, then the input couldn't be all
4680     // zeros, thus the result of the srl will always be zero.
4681     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4682
4683     // If all of the bits input the to ctlz node are known to be zero, then
4684     // the result of the ctlz is "32" and the result of the shift is one.
4685     APInt UnknownBits = ~KnownZero;
4686     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4687
4688     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4689     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4690       // Okay, we know that only that the single bit specified by UnknownBits
4691       // could be set on input to the CTLZ node. If this bit is set, the SRL
4692       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4693       // to an SRL/XOR pair, which is likely to simplify more.
4694       unsigned ShAmt = UnknownBits.countTrailingZeros();
4695       SDValue Op = N0.getOperand(0);
4696
4697       if (ShAmt) {
4698         SDLoc DL(N0);
4699         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4700                   DAG.getConstant(ShAmt, DL,
4701                                   getShiftAmountTy(Op.getValueType())));
4702         AddToWorklist(Op.getNode());
4703       }
4704
4705       SDLoc DL(N);
4706       return DAG.getNode(ISD::XOR, DL, VT,
4707                          Op, DAG.getConstant(1, DL, VT));
4708     }
4709   }
4710
4711   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4712   if (N1.getOpcode() == ISD::TRUNCATE &&
4713       N1.getOperand(0).getOpcode() == ISD::AND) {
4714     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4715     if (NewOp1.getNode())
4716       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4717   }
4718
4719   // fold operands of srl based on knowledge that the low bits are not
4720   // demanded.
4721   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4722     return SDValue(N, 0);
4723
4724   if (N1C && !N1C->isOpaque()) {
4725     SDValue NewSRL = visitShiftByConstant(N, N1C);
4726     if (NewSRL.getNode())
4727       return NewSRL;
4728   }
4729
4730   // Attempt to convert a srl of a load into a narrower zero-extending load.
4731   SDValue NarrowLoad = ReduceLoadWidth(N);
4732   if (NarrowLoad.getNode())
4733     return NarrowLoad;
4734
4735   // Here is a common situation. We want to optimize:
4736   //
4737   //   %a = ...
4738   //   %b = and i32 %a, 2
4739   //   %c = srl i32 %b, 1
4740   //   brcond i32 %c ...
4741   //
4742   // into
4743   //
4744   //   %a = ...
4745   //   %b = and %a, 2
4746   //   %c = setcc eq %b, 0
4747   //   brcond %c ...
4748   //
4749   // However when after the source operand of SRL is optimized into AND, the SRL
4750   // itself may not be optimized further. Look for it and add the BRCOND into
4751   // the worklist.
4752   if (N->hasOneUse()) {
4753     SDNode *Use = *N->use_begin();
4754     if (Use->getOpcode() == ISD::BRCOND)
4755       AddToWorklist(Use);
4756     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4757       // Also look pass the truncate.
4758       Use = *Use->use_begin();
4759       if (Use->getOpcode() == ISD::BRCOND)
4760         AddToWorklist(Use);
4761     }
4762   }
4763
4764   return SDValue();
4765 }
4766
4767 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4768   SDValue N0 = N->getOperand(0);
4769   EVT VT = N->getValueType(0);
4770
4771   // fold (ctlz c1) -> c2
4772   if (isa<ConstantSDNode>(N0))
4773     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4774   return SDValue();
4775 }
4776
4777 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4778   SDValue N0 = N->getOperand(0);
4779   EVT VT = N->getValueType(0);
4780
4781   // fold (ctlz_zero_undef c1) -> c2
4782   if (isa<ConstantSDNode>(N0))
4783     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4784   return SDValue();
4785 }
4786
4787 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4788   SDValue N0 = N->getOperand(0);
4789   EVT VT = N->getValueType(0);
4790
4791   // fold (cttz c1) -> c2
4792   if (isa<ConstantSDNode>(N0))
4793     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4794   return SDValue();
4795 }
4796
4797 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4798   SDValue N0 = N->getOperand(0);
4799   EVT VT = N->getValueType(0);
4800
4801   // fold (cttz_zero_undef c1) -> c2
4802   if (isa<ConstantSDNode>(N0))
4803     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4804   return SDValue();
4805 }
4806
4807 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4808   SDValue N0 = N->getOperand(0);
4809   EVT VT = N->getValueType(0);
4810
4811   // fold (ctpop c1) -> c2
4812   if (isa<ConstantSDNode>(N0))
4813     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4814   return SDValue();
4815 }
4816
4817
4818 /// \brief Generate Min/Max node
4819 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4820                                    SDValue True, SDValue False,
4821                                    ISD::CondCode CC, const TargetLowering &TLI,
4822                                    SelectionDAG &DAG) {
4823   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4824     return SDValue();
4825
4826   switch (CC) {
4827   case ISD::SETOLT:
4828   case ISD::SETOLE:
4829   case ISD::SETLT:
4830   case ISD::SETLE:
4831   case ISD::SETULT:
4832   case ISD::SETULE: {
4833     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4834     if (TLI.isOperationLegal(Opcode, VT))
4835       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4836     return SDValue();
4837   }
4838   case ISD::SETOGT:
4839   case ISD::SETOGE:
4840   case ISD::SETGT:
4841   case ISD::SETGE:
4842   case ISD::SETUGT:
4843   case ISD::SETUGE: {
4844     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4845     if (TLI.isOperationLegal(Opcode, VT))
4846       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4847     return SDValue();
4848   }
4849   default:
4850     return SDValue();
4851   }
4852 }
4853
4854 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4855   SDValue N0 = N->getOperand(0);
4856   SDValue N1 = N->getOperand(1);
4857   SDValue N2 = N->getOperand(2);
4858   EVT VT = N->getValueType(0);
4859   EVT VT0 = N0.getValueType();
4860
4861   // fold (select C, X, X) -> X
4862   if (N1 == N2)
4863     return N1;
4864   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4865     // fold (select true, X, Y) -> X
4866     // fold (select false, X, Y) -> Y
4867     return !N0C->isNullValue() ? N1 : N2;
4868   }
4869   // fold (select C, 1, X) -> (or C, X)
4870   if (VT == MVT::i1 && isOneConstant(N1))
4871     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4872   // fold (select C, 0, 1) -> (xor C, 1)
4873   // We can't do this reliably if integer based booleans have different contents
4874   // to floating point based booleans. This is because we can't tell whether we
4875   // have an integer-based boolean or a floating-point-based boolean unless we
4876   // can find the SETCC that produced it and inspect its operands. This is
4877   // fairly easy if C is the SETCC node, but it can potentially be
4878   // undiscoverable (or not reasonably discoverable). For example, it could be
4879   // in another basic block or it could require searching a complicated
4880   // expression.
4881   if (VT.isInteger() &&
4882       (VT0 == MVT::i1 || (VT0.isInteger() &&
4883                           TLI.getBooleanContents(false, false) ==
4884                               TLI.getBooleanContents(false, true) &&
4885                           TLI.getBooleanContents(false, false) ==
4886                               TargetLowering::ZeroOrOneBooleanContent)) &&
4887       isNullConstant(N1) && isOneConstant(N2)) {
4888     SDValue XORNode;
4889     if (VT == VT0) {
4890       SDLoc DL(N);
4891       return DAG.getNode(ISD::XOR, DL, VT0,
4892                          N0, DAG.getConstant(1, DL, VT0));
4893     }
4894     SDLoc DL0(N0);
4895     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4896                           N0, DAG.getConstant(1, DL0, VT0));
4897     AddToWorklist(XORNode.getNode());
4898     if (VT.bitsGT(VT0))
4899       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4900     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4901   }
4902   // fold (select C, 0, X) -> (and (not C), X)
4903   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4904     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4905     AddToWorklist(NOTNode.getNode());
4906     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4907   }
4908   // fold (select C, X, 1) -> (or (not C), X)
4909   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4910     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4911     AddToWorklist(NOTNode.getNode());
4912     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4913   }
4914   // fold (select C, X, 0) -> (and C, X)
4915   if (VT == MVT::i1 && isNullConstant(N2))
4916     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4917   // fold (select X, X, Y) -> (or X, Y)
4918   // fold (select X, 1, Y) -> (or X, Y)
4919   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4920     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4921   // fold (select X, Y, X) -> (and X, Y)
4922   // fold (select X, Y, 0) -> (and X, Y)
4923   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4924     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4925
4926   // If we can fold this based on the true/false value, do so.
4927   if (SimplifySelectOps(N, N1, N2))
4928     return SDValue(N, 0);  // Don't revisit N.
4929
4930   // fold selects based on a setcc into other things, such as min/max/abs
4931   if (N0.getOpcode() == ISD::SETCC) {
4932     // select x, y (fcmp lt x, y) -> fminnum x, y
4933     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4934     //
4935     // This is OK if we don't care about what happens if either operand is a
4936     // NaN.
4937     //
4938
4939     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4940     // no signed zeros as well as no nans.
4941     const TargetOptions &Options = DAG.getTarget().Options;
4942     if (Options.UnsafeFPMath &&
4943         VT.isFloatingPoint() && N0.hasOneUse() &&
4944         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4945       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4946
4947       SDValue FMinMax =
4948           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4949                               N1, N2, CC, TLI, DAG);
4950       if (FMinMax)
4951         return FMinMax;
4952     }
4953
4954     if ((!LegalOperations &&
4955          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4956         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4957       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4958                          N0.getOperand(0), N0.getOperand(1),
4959                          N1, N2, N0.getOperand(2));
4960     return SimplifySelect(SDLoc(N), N0, N1, N2);
4961   }
4962
4963   if (VT0 == MVT::i1) {
4964     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4965       // select (and Cond0, Cond1), X, Y
4966       //   -> select Cond0, (select Cond1, X, Y), Y
4967       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4968         SDValue Cond0 = N0->getOperand(0);
4969         SDValue Cond1 = N0->getOperand(1);
4970         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4971                                           N1.getValueType(), Cond1, N1, N2);
4972         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4973                            InnerSelect, N2);
4974       }
4975       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4976       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4977         SDValue Cond0 = N0->getOperand(0);
4978         SDValue Cond1 = N0->getOperand(1);
4979         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4980                                           N1.getValueType(), Cond1, N1, N2);
4981         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4982                            InnerSelect);
4983       }
4984     }
4985
4986     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4987     if (N1->getOpcode() == ISD::SELECT) {
4988       SDValue N1_0 = N1->getOperand(0);
4989       SDValue N1_1 = N1->getOperand(1);
4990       SDValue N1_2 = N1->getOperand(2);
4991       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4992         // Create the actual and node if we can generate good code for it.
4993         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4994           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4995                                     N0, N1_0);
4996           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4997                              N1_1, N2);
4998         }
4999         // Otherwise see if we can optimize the "and" to a better pattern.
5000         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5001           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5002                              N1_1, N2);
5003       }
5004     }
5005     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5006     if (N2->getOpcode() == ISD::SELECT) {
5007       SDValue N2_0 = N2->getOperand(0);
5008       SDValue N2_1 = N2->getOperand(1);
5009       SDValue N2_2 = N2->getOperand(2);
5010       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5011         // Create the actual or node if we can generate good code for it.
5012         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5013           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5014                                    N0, N2_0);
5015           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5016                              N1, N2_2);
5017         }
5018         // Otherwise see if we can optimize to a better pattern.
5019         if (SDValue Combined = visitORLike(N0, N2_0, N))
5020           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5021                              N1, N2_2);
5022       }
5023     }
5024   }
5025
5026   return SDValue();
5027 }
5028
5029 static
5030 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5031   SDLoc DL(N);
5032   EVT LoVT, HiVT;
5033   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5034
5035   // Split the inputs.
5036   SDValue Lo, Hi, LL, LH, RL, RH;
5037   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5038   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5039
5040   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5041   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5042
5043   return std::make_pair(Lo, Hi);
5044 }
5045
5046 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5047 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5048 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5049   SDLoc dl(N);
5050   SDValue Cond = N->getOperand(0);
5051   SDValue LHS = N->getOperand(1);
5052   SDValue RHS = N->getOperand(2);
5053   EVT VT = N->getValueType(0);
5054   int NumElems = VT.getVectorNumElements();
5055   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5056          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5057          Cond.getOpcode() == ISD::BUILD_VECTOR);
5058
5059   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5060   // binary ones here.
5061   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5062     return SDValue();
5063
5064   // We're sure we have an even number of elements due to the
5065   // concat_vectors we have as arguments to vselect.
5066   // Skip BV elements until we find one that's not an UNDEF
5067   // After we find an UNDEF element, keep looping until we get to half the
5068   // length of the BV and see if all the non-undef nodes are the same.
5069   ConstantSDNode *BottomHalf = nullptr;
5070   for (int i = 0; i < NumElems / 2; ++i) {
5071     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5072       continue;
5073
5074     if (BottomHalf == nullptr)
5075       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5076     else if (Cond->getOperand(i).getNode() != BottomHalf)
5077       return SDValue();
5078   }
5079
5080   // Do the same for the second half of the BuildVector
5081   ConstantSDNode *TopHalf = nullptr;
5082   for (int i = NumElems / 2; i < NumElems; ++i) {
5083     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5084       continue;
5085
5086     if (TopHalf == nullptr)
5087       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5088     else if (Cond->getOperand(i).getNode() != TopHalf)
5089       return SDValue();
5090   }
5091
5092   assert(TopHalf && BottomHalf &&
5093          "One half of the selector was all UNDEFs and the other was all the "
5094          "same value. This should have been addressed before this function.");
5095   return DAG.getNode(
5096       ISD::CONCAT_VECTORS, dl, VT,
5097       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5098       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5099 }
5100
5101 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5102
5103   if (Level >= AfterLegalizeTypes)
5104     return SDValue();
5105
5106   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5107   SDValue Mask = MSC->getMask();
5108   SDValue Data  = MSC->getValue();
5109   SDLoc DL(N);
5110
5111   // If the MSCATTER data type requires splitting and the mask is provided by a
5112   // SETCC, then split both nodes and its operands before legalization. This
5113   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5114   // and enables future optimizations (e.g. min/max pattern matching on X86).
5115   if (Mask.getOpcode() != ISD::SETCC)
5116     return SDValue();
5117
5118   // Check if any splitting is required.
5119   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5120       TargetLowering::TypeSplitVector)
5121     return SDValue();
5122   SDValue MaskLo, MaskHi, Lo, Hi;
5123   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5124
5125   EVT LoVT, HiVT;
5126   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5127
5128   SDValue Chain = MSC->getChain();
5129
5130   EVT MemoryVT = MSC->getMemoryVT();
5131   unsigned Alignment = MSC->getOriginalAlignment();
5132
5133   EVT LoMemVT, HiMemVT;
5134   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5135
5136   SDValue DataLo, DataHi;
5137   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5138
5139   SDValue BasePtr = MSC->getBasePtr();
5140   SDValue IndexLo, IndexHi;
5141   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5142
5143   MachineMemOperand *MMO = DAG.getMachineFunction().
5144     getMachineMemOperand(MSC->getPointerInfo(), 
5145                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5146                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5147
5148   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5149   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5150                             DL, OpsLo, MMO);
5151
5152   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5153   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5154                             DL, OpsHi, MMO);
5155
5156   AddToWorklist(Lo.getNode());
5157   AddToWorklist(Hi.getNode());
5158
5159   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5160 }
5161
5162 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5163
5164   if (Level >= AfterLegalizeTypes)
5165     return SDValue();
5166
5167   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5168   SDValue Mask = MST->getMask();
5169   SDValue Data  = MST->getValue();
5170   SDLoc DL(N);
5171
5172   // If the MSTORE data type requires splitting and the mask is provided by a
5173   // SETCC, then split both nodes and its operands before legalization. This
5174   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5175   // and enables future optimizations (e.g. min/max pattern matching on X86).
5176   if (Mask.getOpcode() == ISD::SETCC) {
5177
5178     // Check if any splitting is required.
5179     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5180         TargetLowering::TypeSplitVector)
5181       return SDValue();
5182
5183     SDValue MaskLo, MaskHi, Lo, Hi;
5184     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5185
5186     EVT LoVT, HiVT;
5187     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5188
5189     SDValue Chain = MST->getChain();
5190     SDValue Ptr   = MST->getBasePtr();
5191
5192     EVT MemoryVT = MST->getMemoryVT();
5193     unsigned Alignment = MST->getOriginalAlignment();
5194
5195     // if Alignment is equal to the vector size,
5196     // take the half of it for the second part
5197     unsigned SecondHalfAlignment =
5198       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5199          Alignment/2 : Alignment;
5200
5201     EVT LoMemVT, HiMemVT;
5202     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5203
5204     SDValue DataLo, DataHi;
5205     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5206
5207     MachineMemOperand *MMO = DAG.getMachineFunction().
5208       getMachineMemOperand(MST->getPointerInfo(),
5209                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5210                            Alignment, MST->getAAInfo(), MST->getRanges());
5211
5212     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5213                             MST->isTruncatingStore());
5214
5215     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5216     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5217                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5218
5219     MMO = DAG.getMachineFunction().
5220       getMachineMemOperand(MST->getPointerInfo(),
5221                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5222                            SecondHalfAlignment, MST->getAAInfo(),
5223                            MST->getRanges());
5224
5225     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5226                             MST->isTruncatingStore());
5227
5228     AddToWorklist(Lo.getNode());
5229     AddToWorklist(Hi.getNode());
5230
5231     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5232   }
5233   return SDValue();
5234 }
5235
5236 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5237
5238   if (Level >= AfterLegalizeTypes)
5239     return SDValue();
5240
5241   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5242   SDValue Mask = MGT->getMask();
5243   SDLoc DL(N);
5244
5245   // If the MGATHER result requires splitting and the mask is provided by a
5246   // SETCC, then split both nodes and its operands before legalization. This
5247   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5248   // and enables future optimizations (e.g. min/max pattern matching on X86).
5249
5250   if (Mask.getOpcode() != ISD::SETCC)
5251     return SDValue();
5252
5253   EVT VT = N->getValueType(0);
5254
5255   // Check if any splitting is required.
5256   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5257       TargetLowering::TypeSplitVector)
5258     return SDValue();
5259
5260   SDValue MaskLo, MaskHi, Lo, Hi;
5261   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5262
5263   SDValue Src0 = MGT->getValue();
5264   SDValue Src0Lo, Src0Hi;
5265   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5266
5267   EVT LoVT, HiVT;
5268   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5269
5270   SDValue Chain = MGT->getChain();
5271   EVT MemoryVT = MGT->getMemoryVT();
5272   unsigned Alignment = MGT->getOriginalAlignment();
5273
5274   EVT LoMemVT, HiMemVT;
5275   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5276
5277   SDValue BasePtr = MGT->getBasePtr();
5278   SDValue Index = MGT->getIndex();
5279   SDValue IndexLo, IndexHi;
5280   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5281
5282   MachineMemOperand *MMO = DAG.getMachineFunction().
5283     getMachineMemOperand(MGT->getPointerInfo(), 
5284                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5285                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5286
5287   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5288   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5289                             MMO);
5290
5291   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5292   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5293                             MMO);
5294
5295   AddToWorklist(Lo.getNode());
5296   AddToWorklist(Hi.getNode());
5297
5298   // Build a factor node to remember that this load is independent of the
5299   // other one.
5300   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5301                       Hi.getValue(1));
5302
5303   // Legalized the chain result - switch anything that used the old chain to
5304   // use the new one.
5305   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5306
5307   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5308
5309   SDValue RetOps[] = { GatherRes, Chain };
5310   return DAG.getMergeValues(RetOps, DL);
5311 }
5312
5313 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5314
5315   if (Level >= AfterLegalizeTypes)
5316     return SDValue();
5317
5318   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5319   SDValue Mask = MLD->getMask();
5320   SDLoc DL(N);
5321
5322   // If the MLOAD result requires splitting and the mask is provided by a
5323   // SETCC, then split both nodes and its operands before legalization. This
5324   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5325   // and enables future optimizations (e.g. min/max pattern matching on X86).
5326
5327   if (Mask.getOpcode() == ISD::SETCC) {
5328     EVT VT = N->getValueType(0);
5329
5330     // Check if any splitting is required.
5331     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5332         TargetLowering::TypeSplitVector)
5333       return SDValue();
5334
5335     SDValue MaskLo, MaskHi, Lo, Hi;
5336     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5337
5338     SDValue Src0 = MLD->getSrc0();
5339     SDValue Src0Lo, Src0Hi;
5340     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5341
5342     EVT LoVT, HiVT;
5343     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5344
5345     SDValue Chain = MLD->getChain();
5346     SDValue Ptr   = MLD->getBasePtr();
5347     EVT MemoryVT = MLD->getMemoryVT();
5348     unsigned Alignment = MLD->getOriginalAlignment();
5349
5350     // if Alignment is equal to the vector size,
5351     // take the half of it for the second part
5352     unsigned SecondHalfAlignment =
5353       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5354          Alignment/2 : Alignment;
5355
5356     EVT LoMemVT, HiMemVT;
5357     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5358
5359     MachineMemOperand *MMO = DAG.getMachineFunction().
5360     getMachineMemOperand(MLD->getPointerInfo(),
5361                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5362                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5363
5364     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5365                            ISD::NON_EXTLOAD);
5366
5367     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5368     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5369                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5370
5371     MMO = DAG.getMachineFunction().
5372     getMachineMemOperand(MLD->getPointerInfo(),
5373                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5374                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5375
5376     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5377                            ISD::NON_EXTLOAD);
5378
5379     AddToWorklist(Lo.getNode());
5380     AddToWorklist(Hi.getNode());
5381
5382     // Build a factor node to remember that this load is independent of the
5383     // other one.
5384     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5385                         Hi.getValue(1));
5386
5387     // Legalized the chain result - switch anything that used the old chain to
5388     // use the new one.
5389     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5390
5391     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5392
5393     SDValue RetOps[] = { LoadRes, Chain };
5394     return DAG.getMergeValues(RetOps, DL);
5395   }
5396   return SDValue();
5397 }
5398
5399 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5400   SDValue N0 = N->getOperand(0);
5401   SDValue N1 = N->getOperand(1);
5402   SDValue N2 = N->getOperand(2);
5403   SDLoc DL(N);
5404
5405   // Canonicalize integer abs.
5406   // vselect (setg[te] X,  0),  X, -X ->
5407   // vselect (setgt    X, -1),  X, -X ->
5408   // vselect (setl[te] X,  0), -X,  X ->
5409   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5410   if (N0.getOpcode() == ISD::SETCC) {
5411     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5412     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5413     bool isAbs = false;
5414     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5415
5416     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5417          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5418         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5419       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5420     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5421              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5422       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5423
5424     if (isAbs) {
5425       EVT VT = LHS.getValueType();
5426       SDValue Shift = DAG.getNode(
5427           ISD::SRA, DL, VT, LHS,
5428           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5429       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5430       AddToWorklist(Shift.getNode());
5431       AddToWorklist(Add.getNode());
5432       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5433     }
5434   }
5435
5436   if (SimplifySelectOps(N, N1, N2))
5437     return SDValue(N, 0);  // Don't revisit N.
5438
5439   // If the VSELECT result requires splitting and the mask is provided by a
5440   // SETCC, then split both nodes and its operands before legalization. This
5441   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5442   // and enables future optimizations (e.g. min/max pattern matching on X86).
5443   if (N0.getOpcode() == ISD::SETCC) {
5444     EVT VT = N->getValueType(0);
5445
5446     // Check if any splitting is required.
5447     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5448         TargetLowering::TypeSplitVector)
5449       return SDValue();
5450
5451     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5452     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5453     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5454     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5455
5456     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5457     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5458
5459     // Add the new VSELECT nodes to the work list in case they need to be split
5460     // again.
5461     AddToWorklist(Lo.getNode());
5462     AddToWorklist(Hi.getNode());
5463
5464     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5465   }
5466
5467   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5468   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5469     return N1;
5470   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5471   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5472     return N2;
5473
5474   // The ConvertSelectToConcatVector function is assuming both the above
5475   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5476   // and addressed.
5477   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5478       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5479       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5480     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5481     if (CV.getNode())
5482       return CV;
5483   }
5484
5485   return SDValue();
5486 }
5487
5488 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5489   SDValue N0 = N->getOperand(0);
5490   SDValue N1 = N->getOperand(1);
5491   SDValue N2 = N->getOperand(2);
5492   SDValue N3 = N->getOperand(3);
5493   SDValue N4 = N->getOperand(4);
5494   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5495
5496   // fold select_cc lhs, rhs, x, x, cc -> x
5497   if (N2 == N3)
5498     return N2;
5499
5500   // Determine if the condition we're dealing with is constant
5501   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5502                               N0, N1, CC, SDLoc(N), false);
5503   if (SCC.getNode()) {
5504     AddToWorklist(SCC.getNode());
5505
5506     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5507       if (!SCCC->isNullValue())
5508         return N2;    // cond always true -> true val
5509       else
5510         return N3;    // cond always false -> false val
5511     } else if (SCC->getOpcode() == ISD::UNDEF) {
5512       // When the condition is UNDEF, just return the first operand. This is
5513       // coherent the DAG creation, no setcc node is created in this case
5514       return N2;
5515     } else if (SCC.getOpcode() == ISD::SETCC) {
5516       // Fold to a simpler select_cc
5517       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5518                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5519                          SCC.getOperand(2));
5520     }
5521   }
5522
5523   // If we can fold this based on the true/false value, do so.
5524   if (SimplifySelectOps(N, N2, N3))
5525     return SDValue(N, 0);  // Don't revisit N.
5526
5527   // fold select_cc into other things, such as min/max/abs
5528   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5529 }
5530
5531 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5532   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5533                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5534                        SDLoc(N));
5535 }
5536
5537 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5538 // dag node into a ConstantSDNode or a build_vector of constants.
5539 // This function is called by the DAGCombiner when visiting sext/zext/aext
5540 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5541 // Vector extends are not folded if operations are legal; this is to
5542 // avoid introducing illegal build_vector dag nodes.
5543 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5544                                          SelectionDAG &DAG, bool LegalTypes,
5545                                          bool LegalOperations) {
5546   unsigned Opcode = N->getOpcode();
5547   SDValue N0 = N->getOperand(0);
5548   EVT VT = N->getValueType(0);
5549
5550   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5551          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5552          && "Expected EXTEND dag node in input!");
5553
5554   // fold (sext c1) -> c1
5555   // fold (zext c1) -> c1
5556   // fold (aext c1) -> c1
5557   if (isa<ConstantSDNode>(N0))
5558     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5559
5560   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5561   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5562   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5563   EVT SVT = VT.getScalarType();
5564   if (!(VT.isVector() &&
5565       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5566       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5567     return nullptr;
5568
5569   // We can fold this node into a build_vector.
5570   unsigned VTBits = SVT.getSizeInBits();
5571   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5572   unsigned ShAmt = VTBits - EVTBits;
5573   SmallVector<SDValue, 8> Elts;
5574   unsigned NumElts = VT.getVectorNumElements();
5575   SDLoc DL(N);
5576
5577   for (unsigned i=0; i != NumElts; ++i) {
5578     SDValue Op = N0->getOperand(i);
5579     if (Op->getOpcode() == ISD::UNDEF) {
5580       Elts.push_back(DAG.getUNDEF(SVT));
5581       continue;
5582     }
5583
5584     SDLoc DL(Op);
5585     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5586     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5587     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5588       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5589                                      DL, SVT));
5590     else
5591       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5592                                      DL, SVT));
5593   }
5594
5595   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5596 }
5597
5598 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5599 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5600 // transformation. Returns true if extension are possible and the above
5601 // mentioned transformation is profitable.
5602 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5603                                     unsigned ExtOpc,
5604                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5605                                     const TargetLowering &TLI) {
5606   bool HasCopyToRegUses = false;
5607   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5608   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5609                             UE = N0.getNode()->use_end();
5610        UI != UE; ++UI) {
5611     SDNode *User = *UI;
5612     if (User == N)
5613       continue;
5614     if (UI.getUse().getResNo() != N0.getResNo())
5615       continue;
5616     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5617     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5618       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5619       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5620         // Sign bits will be lost after a zext.
5621         return false;
5622       bool Add = false;
5623       for (unsigned i = 0; i != 2; ++i) {
5624         SDValue UseOp = User->getOperand(i);
5625         if (UseOp == N0)
5626           continue;
5627         if (!isa<ConstantSDNode>(UseOp))
5628           return false;
5629         Add = true;
5630       }
5631       if (Add)
5632         ExtendNodes.push_back(User);
5633       continue;
5634     }
5635     // If truncates aren't free and there are users we can't
5636     // extend, it isn't worthwhile.
5637     if (!isTruncFree)
5638       return false;
5639     // Remember if this value is live-out.
5640     if (User->getOpcode() == ISD::CopyToReg)
5641       HasCopyToRegUses = true;
5642   }
5643
5644   if (HasCopyToRegUses) {
5645     bool BothLiveOut = false;
5646     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5647          UI != UE; ++UI) {
5648       SDUse &Use = UI.getUse();
5649       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5650         BothLiveOut = true;
5651         break;
5652       }
5653     }
5654     if (BothLiveOut)
5655       // Both unextended and extended values are live out. There had better be
5656       // a good reason for the transformation.
5657       return ExtendNodes.size();
5658   }
5659   return true;
5660 }
5661
5662 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5663                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5664                                   ISD::NodeType ExtType) {
5665   // Extend SetCC uses if necessary.
5666   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5667     SDNode *SetCC = SetCCs[i];
5668     SmallVector<SDValue, 4> Ops;
5669
5670     for (unsigned j = 0; j != 2; ++j) {
5671       SDValue SOp = SetCC->getOperand(j);
5672       if (SOp == Trunc)
5673         Ops.push_back(ExtLoad);
5674       else
5675         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5676     }
5677
5678     Ops.push_back(SetCC->getOperand(2));
5679     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5680   }
5681 }
5682
5683 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5684 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5685   SDValue N0 = N->getOperand(0);
5686   EVT DstVT = N->getValueType(0);
5687   EVT SrcVT = N0.getValueType();
5688
5689   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5690           N->getOpcode() == ISD::ZERO_EXTEND) &&
5691          "Unexpected node type (not an extend)!");
5692
5693   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5694   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5695   //   (v8i32 (sext (v8i16 (load x))))
5696   // into:
5697   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5698   //                          (v4i32 (sextload (x + 16)))))
5699   // Where uses of the original load, i.e.:
5700   //   (v8i16 (load x))
5701   // are replaced with:
5702   //   (v8i16 (truncate
5703   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5704   //                            (v4i32 (sextload (x + 16)))))))
5705   //
5706   // This combine is only applicable to illegal, but splittable, vectors.
5707   // All legal types, and illegal non-vector types, are handled elsewhere.
5708   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5709   //
5710   if (N0->getOpcode() != ISD::LOAD)
5711     return SDValue();
5712
5713   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5714
5715   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5716       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5717       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5718     return SDValue();
5719
5720   SmallVector<SDNode *, 4> SetCCs;
5721   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5722     return SDValue();
5723
5724   ISD::LoadExtType ExtType =
5725       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5726
5727   // Try to split the vector types to get down to legal types.
5728   EVT SplitSrcVT = SrcVT;
5729   EVT SplitDstVT = DstVT;
5730   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5731          SplitSrcVT.getVectorNumElements() > 1) {
5732     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5733     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5734   }
5735
5736   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5737     return SDValue();
5738
5739   SDLoc DL(N);
5740   const unsigned NumSplits =
5741       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5742   const unsigned Stride = SplitSrcVT.getStoreSize();
5743   SmallVector<SDValue, 4> Loads;
5744   SmallVector<SDValue, 4> Chains;
5745
5746   SDValue BasePtr = LN0->getBasePtr();
5747   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5748     const unsigned Offset = Idx * Stride;
5749     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5750
5751     SDValue SplitLoad = DAG.getExtLoad(
5752         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5753         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5754         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5755         Align, LN0->getAAInfo());
5756
5757     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5758                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5759
5760     Loads.push_back(SplitLoad.getValue(0));
5761     Chains.push_back(SplitLoad.getValue(1));
5762   }
5763
5764   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5765   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5766
5767   CombineTo(N, NewValue);
5768
5769   // Replace uses of the original load (before extension)
5770   // with a truncate of the concatenated sextloaded vectors.
5771   SDValue Trunc =
5772       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5773   CombineTo(N0.getNode(), Trunc, NewChain);
5774   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5775                   (ISD::NodeType)N->getOpcode());
5776   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5777 }
5778
5779 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5780   SDValue N0 = N->getOperand(0);
5781   EVT VT = N->getValueType(0);
5782
5783   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5784                                               LegalOperations))
5785     return SDValue(Res, 0);
5786
5787   // fold (sext (sext x)) -> (sext x)
5788   // fold (sext (aext x)) -> (sext x)
5789   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5790     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5791                        N0.getOperand(0));
5792
5793   if (N0.getOpcode() == ISD::TRUNCATE) {
5794     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5795     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5796     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5797     if (NarrowLoad.getNode()) {
5798       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5799       if (NarrowLoad.getNode() != N0.getNode()) {
5800         CombineTo(N0.getNode(), NarrowLoad);
5801         // CombineTo deleted the truncate, if needed, but not what's under it.
5802         AddToWorklist(oye);
5803       }
5804       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5805     }
5806
5807     // See if the value being truncated is already sign extended.  If so, just
5808     // eliminate the trunc/sext pair.
5809     SDValue Op = N0.getOperand(0);
5810     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5811     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5812     unsigned DestBits = VT.getScalarType().getSizeInBits();
5813     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5814
5815     if (OpBits == DestBits) {
5816       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5817       // bits, it is already ready.
5818       if (NumSignBits > DestBits-MidBits)
5819         return Op;
5820     } else if (OpBits < DestBits) {
5821       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5822       // bits, just sext from i32.
5823       if (NumSignBits > OpBits-MidBits)
5824         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5825     } else {
5826       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5827       // bits, just truncate to i32.
5828       if (NumSignBits > OpBits-MidBits)
5829         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5830     }
5831
5832     // fold (sext (truncate x)) -> (sextinreg x).
5833     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5834                                                  N0.getValueType())) {
5835       if (OpBits < DestBits)
5836         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5837       else if (OpBits > DestBits)
5838         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5839       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5840                          DAG.getValueType(N0.getValueType()));
5841     }
5842   }
5843
5844   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5845   // Only generate vector extloads when 1) they're legal, and 2) they are
5846   // deemed desirable by the target.
5847   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5848       ((!LegalOperations && !VT.isVector() &&
5849         !cast<LoadSDNode>(N0)->isVolatile()) ||
5850        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5851     bool DoXform = true;
5852     SmallVector<SDNode*, 4> SetCCs;
5853     if (!N0.hasOneUse())
5854       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5855     if (VT.isVector())
5856       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5857     if (DoXform) {
5858       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5859       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5860                                        LN0->getChain(),
5861                                        LN0->getBasePtr(), N0.getValueType(),
5862                                        LN0->getMemOperand());
5863       CombineTo(N, ExtLoad);
5864       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5865                                   N0.getValueType(), ExtLoad);
5866       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5867       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5868                       ISD::SIGN_EXTEND);
5869       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5870     }
5871   }
5872
5873   // fold (sext (load x)) to multiple smaller sextloads.
5874   // Only on illegal but splittable vectors.
5875   if (SDValue ExtLoad = CombineExtLoad(N))
5876     return ExtLoad;
5877
5878   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5879   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5880   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5881       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5882     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5883     EVT MemVT = LN0->getMemoryVT();
5884     if ((!LegalOperations && !LN0->isVolatile()) ||
5885         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5886       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5887                                        LN0->getChain(),
5888                                        LN0->getBasePtr(), MemVT,
5889                                        LN0->getMemOperand());
5890       CombineTo(N, ExtLoad);
5891       CombineTo(N0.getNode(),
5892                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5893                             N0.getValueType(), ExtLoad),
5894                 ExtLoad.getValue(1));
5895       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5896     }
5897   }
5898
5899   // fold (sext (and/or/xor (load x), cst)) ->
5900   //      (and/or/xor (sextload x), (sext cst))
5901   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5902        N0.getOpcode() == ISD::XOR) &&
5903       isa<LoadSDNode>(N0.getOperand(0)) &&
5904       N0.getOperand(1).getOpcode() == ISD::Constant &&
5905       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5906       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5907     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5908     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5909       bool DoXform = true;
5910       SmallVector<SDNode*, 4> SetCCs;
5911       if (!N0.hasOneUse())
5912         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5913                                           SetCCs, TLI);
5914       if (DoXform) {
5915         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5916                                          LN0->getChain(), LN0->getBasePtr(),
5917                                          LN0->getMemoryVT(),
5918                                          LN0->getMemOperand());
5919         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5920         Mask = Mask.sext(VT.getSizeInBits());
5921         SDLoc DL(N);
5922         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5923                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5924         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5925                                     SDLoc(N0.getOperand(0)),
5926                                     N0.getOperand(0).getValueType(), ExtLoad);
5927         CombineTo(N, And);
5928         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5929         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5930                         ISD::SIGN_EXTEND);
5931         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5932       }
5933     }
5934   }
5935
5936   if (N0.getOpcode() == ISD::SETCC) {
5937     EVT N0VT = N0.getOperand(0).getValueType();
5938     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5939     // Only do this before legalize for now.
5940     if (VT.isVector() && !LegalOperations &&
5941         TLI.getBooleanContents(N0VT) ==
5942             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5943       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5944       // of the same size as the compared operands. Only optimize sext(setcc())
5945       // if this is the case.
5946       EVT SVT = getSetCCResultType(N0VT);
5947
5948       // We know that the # elements of the results is the same as the
5949       // # elements of the compare (and the # elements of the compare result
5950       // for that matter).  Check to see that they are the same size.  If so,
5951       // we know that the element size of the sext'd result matches the
5952       // element size of the compare operands.
5953       if (VT.getSizeInBits() == SVT.getSizeInBits())
5954         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5955                              N0.getOperand(1),
5956                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5957
5958       // If the desired elements are smaller or larger than the source
5959       // elements we can use a matching integer vector type and then
5960       // truncate/sign extend
5961       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5962       if (SVT == MatchingVectorType) {
5963         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5964                                N0.getOperand(0), N0.getOperand(1),
5965                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5966         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5967       }
5968     }
5969
5970     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5971     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5972     SDLoc DL(N);
5973     SDValue NegOne =
5974       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5975     SDValue SCC =
5976       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5977                        NegOne, DAG.getConstant(0, DL, VT),
5978                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5979     if (SCC.getNode()) return SCC;
5980
5981     if (!VT.isVector()) {
5982       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5983       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5984         SDLoc DL(N);
5985         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5986         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5987                                      N0.getOperand(0), N0.getOperand(1), CC);
5988         return DAG.getSelect(DL, VT, SetCC,
5989                              NegOne, DAG.getConstant(0, DL, VT));
5990       }
5991     }
5992   }
5993
5994   // fold (sext x) -> (zext x) if the sign bit is known zero.
5995   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5996       DAG.SignBitIsZero(N0))
5997     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5998
5999   return SDValue();
6000 }
6001
6002 // isTruncateOf - If N is a truncate of some other value, return true, record
6003 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6004 // This function computes KnownZero to avoid a duplicated call to
6005 // computeKnownBits in the caller.
6006 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6007                          APInt &KnownZero) {
6008   APInt KnownOne;
6009   if (N->getOpcode() == ISD::TRUNCATE) {
6010     Op = N->getOperand(0);
6011     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6012     return true;
6013   }
6014
6015   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6016       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6017     return false;
6018
6019   SDValue Op0 = N->getOperand(0);
6020   SDValue Op1 = N->getOperand(1);
6021   assert(Op0.getValueType() == Op1.getValueType());
6022
6023   if (isNullConstant(Op0))
6024     Op = Op1;
6025   else if (isNullConstant(Op1))
6026     Op = Op0;
6027   else
6028     return false;
6029
6030   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6031
6032   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6033     return false;
6034
6035   return true;
6036 }
6037
6038 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6039   SDValue N0 = N->getOperand(0);
6040   EVT VT = N->getValueType(0);
6041
6042   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6043                                               LegalOperations))
6044     return SDValue(Res, 0);
6045
6046   // fold (zext (zext x)) -> (zext x)
6047   // fold (zext (aext x)) -> (zext x)
6048   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6049     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6050                        N0.getOperand(0));
6051
6052   // fold (zext (truncate x)) -> (zext x) or
6053   //      (zext (truncate x)) -> (truncate x)
6054   // This is valid when the truncated bits of x are already zero.
6055   // FIXME: We should extend this to work for vectors too.
6056   SDValue Op;
6057   APInt KnownZero;
6058   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6059     APInt TruncatedBits =
6060       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6061       APInt(Op.getValueSizeInBits(), 0) :
6062       APInt::getBitsSet(Op.getValueSizeInBits(),
6063                         N0.getValueSizeInBits(),
6064                         std::min(Op.getValueSizeInBits(),
6065                                  VT.getSizeInBits()));
6066     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6067       if (VT.bitsGT(Op.getValueType()))
6068         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6069       if (VT.bitsLT(Op.getValueType()))
6070         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6071
6072       return Op;
6073     }
6074   }
6075
6076   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6077   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6078   if (N0.getOpcode() == ISD::TRUNCATE) {
6079     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6080     if (NarrowLoad.getNode()) {
6081       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6082       if (NarrowLoad.getNode() != N0.getNode()) {
6083         CombineTo(N0.getNode(), NarrowLoad);
6084         // CombineTo deleted the truncate, if needed, but not what's under it.
6085         AddToWorklist(oye);
6086       }
6087       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6088     }
6089   }
6090
6091   // fold (zext (truncate x)) -> (and x, mask)
6092   if (N0.getOpcode() == ISD::TRUNCATE &&
6093       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6094
6095     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6096     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6097     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6098     if (NarrowLoad.getNode()) {
6099       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6100       if (NarrowLoad.getNode() != N0.getNode()) {
6101         CombineTo(N0.getNode(), NarrowLoad);
6102         // CombineTo deleted the truncate, if needed, but not what's under it.
6103         AddToWorklist(oye);
6104       }
6105       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6106     }
6107
6108     SDValue Op = N0.getOperand(0);
6109     if (Op.getValueType().bitsLT(VT)) {
6110       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6111       AddToWorklist(Op.getNode());
6112     } else if (Op.getValueType().bitsGT(VT)) {
6113       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6114       AddToWorklist(Op.getNode());
6115     }
6116     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6117                                   N0.getValueType().getScalarType());
6118   }
6119
6120   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6121   // if either of the casts is not free.
6122   if (N0.getOpcode() == ISD::AND &&
6123       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6124       N0.getOperand(1).getOpcode() == ISD::Constant &&
6125       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6126                            N0.getValueType()) ||
6127        !TLI.isZExtFree(N0.getValueType(), VT))) {
6128     SDValue X = N0.getOperand(0).getOperand(0);
6129     if (X.getValueType().bitsLT(VT)) {
6130       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6131     } else if (X.getValueType().bitsGT(VT)) {
6132       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6133     }
6134     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6135     Mask = Mask.zext(VT.getSizeInBits());
6136     SDLoc DL(N);
6137     return DAG.getNode(ISD::AND, DL, VT,
6138                        X, DAG.getConstant(Mask, DL, VT));
6139   }
6140
6141   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6142   // Only generate vector extloads when 1) they're legal, and 2) they are
6143   // deemed desirable by the target.
6144   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6145       ((!LegalOperations && !VT.isVector() &&
6146         !cast<LoadSDNode>(N0)->isVolatile()) ||
6147        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6148     bool DoXform = true;
6149     SmallVector<SDNode*, 4> SetCCs;
6150     if (!N0.hasOneUse())
6151       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6152     if (VT.isVector())
6153       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6154     if (DoXform) {
6155       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6156       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6157                                        LN0->getChain(),
6158                                        LN0->getBasePtr(), N0.getValueType(),
6159                                        LN0->getMemOperand());
6160       CombineTo(N, ExtLoad);
6161       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6162                                   N0.getValueType(), ExtLoad);
6163       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6164
6165       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6166                       ISD::ZERO_EXTEND);
6167       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6168     }
6169   }
6170
6171   // fold (zext (load x)) to multiple smaller zextloads.
6172   // Only on illegal but splittable vectors.
6173   if (SDValue ExtLoad = CombineExtLoad(N))
6174     return ExtLoad;
6175
6176   // fold (zext (and/or/xor (load x), cst)) ->
6177   //      (and/or/xor (zextload x), (zext cst))
6178   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6179        N0.getOpcode() == ISD::XOR) &&
6180       isa<LoadSDNode>(N0.getOperand(0)) &&
6181       N0.getOperand(1).getOpcode() == ISD::Constant &&
6182       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6183       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6184     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6185     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6186       bool DoXform = true;
6187       SmallVector<SDNode*, 4> SetCCs;
6188       if (!N0.hasOneUse())
6189         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6190                                           SetCCs, TLI);
6191       if (DoXform) {
6192         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6193                                          LN0->getChain(), LN0->getBasePtr(),
6194                                          LN0->getMemoryVT(),
6195                                          LN0->getMemOperand());
6196         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6197         Mask = Mask.zext(VT.getSizeInBits());
6198         SDLoc DL(N);
6199         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6200                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6201         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6202                                     SDLoc(N0.getOperand(0)),
6203                                     N0.getOperand(0).getValueType(), ExtLoad);
6204         CombineTo(N, And);
6205         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6206         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6207                         ISD::ZERO_EXTEND);
6208         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6209       }
6210     }
6211   }
6212
6213   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6214   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6215   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6216       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6217     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6218     EVT MemVT = LN0->getMemoryVT();
6219     if ((!LegalOperations && !LN0->isVolatile()) ||
6220         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6221       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6222                                        LN0->getChain(),
6223                                        LN0->getBasePtr(), MemVT,
6224                                        LN0->getMemOperand());
6225       CombineTo(N, ExtLoad);
6226       CombineTo(N0.getNode(),
6227                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6228                             ExtLoad),
6229                 ExtLoad.getValue(1));
6230       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6231     }
6232   }
6233
6234   if (N0.getOpcode() == ISD::SETCC) {
6235     if (!LegalOperations && VT.isVector() &&
6236         N0.getValueType().getVectorElementType() == MVT::i1) {
6237       EVT N0VT = N0.getOperand(0).getValueType();
6238       if (getSetCCResultType(N0VT) == N0.getValueType())
6239         return SDValue();
6240
6241       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6242       // Only do this before legalize for now.
6243       EVT EltVT = VT.getVectorElementType();
6244       SDLoc DL(N);
6245       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6246                                     DAG.getConstant(1, DL, EltVT));
6247       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6248         // We know that the # elements of the results is the same as the
6249         // # elements of the compare (and the # elements of the compare result
6250         // for that matter).  Check to see that they are the same size.  If so,
6251         // we know that the element size of the sext'd result matches the
6252         // element size of the compare operands.
6253         return DAG.getNode(ISD::AND, DL, VT,
6254                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6255                                          N0.getOperand(1),
6256                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6257                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6258                                        OneOps));
6259
6260       // If the desired elements are smaller or larger than the source
6261       // elements we can use a matching integer vector type and then
6262       // truncate/sign extend
6263       EVT MatchingElementType =
6264         EVT::getIntegerVT(*DAG.getContext(),
6265                           N0VT.getScalarType().getSizeInBits());
6266       EVT MatchingVectorType =
6267         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6268                          N0VT.getVectorNumElements());
6269       SDValue VsetCC =
6270         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6271                       N0.getOperand(1),
6272                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6273       return DAG.getNode(ISD::AND, DL, VT,
6274                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6275                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6276     }
6277
6278     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6279     SDLoc DL(N);
6280     SDValue SCC =
6281       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6282                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6283                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6284     if (SCC.getNode()) return SCC;
6285   }
6286
6287   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6288   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6289       isa<ConstantSDNode>(N0.getOperand(1)) &&
6290       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6291       N0.hasOneUse()) {
6292     SDValue ShAmt = N0.getOperand(1);
6293     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6294     if (N0.getOpcode() == ISD::SHL) {
6295       SDValue InnerZExt = N0.getOperand(0);
6296       // If the original shl may be shifting out bits, do not perform this
6297       // transformation.
6298       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6299         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6300       if (ShAmtVal > KnownZeroBits)
6301         return SDValue();
6302     }
6303
6304     SDLoc DL(N);
6305
6306     // Ensure that the shift amount is wide enough for the shifted value.
6307     if (VT.getSizeInBits() >= 256)
6308       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6309
6310     return DAG.getNode(N0.getOpcode(), DL, VT,
6311                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6312                        ShAmt);
6313   }
6314
6315   return SDValue();
6316 }
6317
6318 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6319   SDValue N0 = N->getOperand(0);
6320   EVT VT = N->getValueType(0);
6321
6322   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6323                                               LegalOperations))
6324     return SDValue(Res, 0);
6325
6326   // fold (aext (aext x)) -> (aext x)
6327   // fold (aext (zext x)) -> (zext x)
6328   // fold (aext (sext x)) -> (sext x)
6329   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6330       N0.getOpcode() == ISD::ZERO_EXTEND ||
6331       N0.getOpcode() == ISD::SIGN_EXTEND)
6332     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6333
6334   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6335   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6336   if (N0.getOpcode() == ISD::TRUNCATE) {
6337     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6338     if (NarrowLoad.getNode()) {
6339       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6340       if (NarrowLoad.getNode() != N0.getNode()) {
6341         CombineTo(N0.getNode(), NarrowLoad);
6342         // CombineTo deleted the truncate, if needed, but not what's under it.
6343         AddToWorklist(oye);
6344       }
6345       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6346     }
6347   }
6348
6349   // fold (aext (truncate x))
6350   if (N0.getOpcode() == ISD::TRUNCATE) {
6351     SDValue TruncOp = N0.getOperand(0);
6352     if (TruncOp.getValueType() == VT)
6353       return TruncOp; // x iff x size == zext size.
6354     if (TruncOp.getValueType().bitsGT(VT))
6355       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6356     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6357   }
6358
6359   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6360   // if the trunc is not free.
6361   if (N0.getOpcode() == ISD::AND &&
6362       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6363       N0.getOperand(1).getOpcode() == ISD::Constant &&
6364       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6365                           N0.getValueType())) {
6366     SDValue X = N0.getOperand(0).getOperand(0);
6367     if (X.getValueType().bitsLT(VT)) {
6368       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6369     } else if (X.getValueType().bitsGT(VT)) {
6370       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6371     }
6372     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6373     Mask = Mask.zext(VT.getSizeInBits());
6374     SDLoc DL(N);
6375     return DAG.getNode(ISD::AND, DL, VT,
6376                        X, DAG.getConstant(Mask, DL, VT));
6377   }
6378
6379   // fold (aext (load x)) -> (aext (truncate (extload x)))
6380   // None of the supported targets knows how to perform load and any_ext
6381   // on vectors in one instruction.  We only perform this transformation on
6382   // scalars.
6383   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6384       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6385       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6386     bool DoXform = true;
6387     SmallVector<SDNode*, 4> SetCCs;
6388     if (!N0.hasOneUse())
6389       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6390     if (DoXform) {
6391       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6392       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6393                                        LN0->getChain(),
6394                                        LN0->getBasePtr(), N0.getValueType(),
6395                                        LN0->getMemOperand());
6396       CombineTo(N, ExtLoad);
6397       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6398                                   N0.getValueType(), ExtLoad);
6399       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6400       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6401                       ISD::ANY_EXTEND);
6402       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6403     }
6404   }
6405
6406   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6407   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6408   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6409   if (N0.getOpcode() == ISD::LOAD &&
6410       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6411       N0.hasOneUse()) {
6412     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6413     ISD::LoadExtType ExtType = LN0->getExtensionType();
6414     EVT MemVT = LN0->getMemoryVT();
6415     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6416       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6417                                        VT, LN0->getChain(), LN0->getBasePtr(),
6418                                        MemVT, LN0->getMemOperand());
6419       CombineTo(N, ExtLoad);
6420       CombineTo(N0.getNode(),
6421                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6422                             N0.getValueType(), ExtLoad),
6423                 ExtLoad.getValue(1));
6424       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6425     }
6426   }
6427
6428   if (N0.getOpcode() == ISD::SETCC) {
6429     // For vectors:
6430     // aext(setcc) -> vsetcc
6431     // aext(setcc) -> truncate(vsetcc)
6432     // aext(setcc) -> aext(vsetcc)
6433     // Only do this before legalize for now.
6434     if (VT.isVector() && !LegalOperations) {
6435       EVT N0VT = N0.getOperand(0).getValueType();
6436         // We know that the # elements of the results is the same as the
6437         // # elements of the compare (and the # elements of the compare result
6438         // for that matter).  Check to see that they are the same size.  If so,
6439         // we know that the element size of the sext'd result matches the
6440         // element size of the compare operands.
6441       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6442         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6443                              N0.getOperand(1),
6444                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6445       // If the desired elements are smaller or larger than the source
6446       // elements we can use a matching integer vector type and then
6447       // truncate/any extend
6448       else {
6449         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6450         SDValue VsetCC =
6451           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6452                         N0.getOperand(1),
6453                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6454         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6455       }
6456     }
6457
6458     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6459     SDLoc DL(N);
6460     SDValue SCC =
6461       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6462                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6463                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6464     if (SCC.getNode())
6465       return SCC;
6466   }
6467
6468   return SDValue();
6469 }
6470
6471 /// See if the specified operand can be simplified with the knowledge that only
6472 /// the bits specified by Mask are used.  If so, return the simpler operand,
6473 /// otherwise return a null SDValue.
6474 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6475   switch (V.getOpcode()) {
6476   default: break;
6477   case ISD::Constant: {
6478     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6479     assert(CV && "Const value should be ConstSDNode.");
6480     const APInt &CVal = CV->getAPIntValue();
6481     APInt NewVal = CVal & Mask;
6482     if (NewVal != CVal)
6483       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6484     break;
6485   }
6486   case ISD::OR:
6487   case ISD::XOR:
6488     // If the LHS or RHS don't contribute bits to the or, drop them.
6489     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6490       return V.getOperand(1);
6491     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6492       return V.getOperand(0);
6493     break;
6494   case ISD::SRL:
6495     // Only look at single-use SRLs.
6496     if (!V.getNode()->hasOneUse())
6497       break;
6498     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6499       // See if we can recursively simplify the LHS.
6500       unsigned Amt = RHSC->getZExtValue();
6501
6502       // Watch out for shift count overflow though.
6503       if (Amt >= Mask.getBitWidth()) break;
6504       APInt NewMask = Mask << Amt;
6505       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6506       if (SimplifyLHS.getNode())
6507         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6508                            SimplifyLHS, V.getOperand(1));
6509     }
6510   }
6511   return SDValue();
6512 }
6513
6514 /// If the result of a wider load is shifted to right of N  bits and then
6515 /// truncated to a narrower type and where N is a multiple of number of bits of
6516 /// the narrower type, transform it to a narrower load from address + N / num of
6517 /// bits of new type. If the result is to be extended, also fold the extension
6518 /// to form a extending load.
6519 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6520   unsigned Opc = N->getOpcode();
6521
6522   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6523   SDValue N0 = N->getOperand(0);
6524   EVT VT = N->getValueType(0);
6525   EVT ExtVT = VT;
6526
6527   // This transformation isn't valid for vector loads.
6528   if (VT.isVector())
6529     return SDValue();
6530
6531   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6532   // extended to VT.
6533   if (Opc == ISD::SIGN_EXTEND_INREG) {
6534     ExtType = ISD::SEXTLOAD;
6535     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6536   } else if (Opc == ISD::SRL) {
6537     // Another special-case: SRL is basically zero-extending a narrower value.
6538     ExtType = ISD::ZEXTLOAD;
6539     N0 = SDValue(N, 0);
6540     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6541     if (!N01) return SDValue();
6542     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6543                               VT.getSizeInBits() - N01->getZExtValue());
6544   }
6545   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6546     return SDValue();
6547
6548   unsigned EVTBits = ExtVT.getSizeInBits();
6549
6550   // Do not generate loads of non-round integer types since these can
6551   // be expensive (and would be wrong if the type is not byte sized).
6552   if (!ExtVT.isRound())
6553     return SDValue();
6554
6555   unsigned ShAmt = 0;
6556   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6557     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6558       ShAmt = N01->getZExtValue();
6559       // Is the shift amount a multiple of size of VT?
6560       if ((ShAmt & (EVTBits-1)) == 0) {
6561         N0 = N0.getOperand(0);
6562         // Is the load width a multiple of size of VT?
6563         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6564           return SDValue();
6565       }
6566
6567       // At this point, we must have a load or else we can't do the transform.
6568       if (!isa<LoadSDNode>(N0)) return SDValue();
6569
6570       // Because a SRL must be assumed to *need* to zero-extend the high bits
6571       // (as opposed to anyext the high bits), we can't combine the zextload
6572       // lowering of SRL and an sextload.
6573       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6574         return SDValue();
6575
6576       // If the shift amount is larger than the input type then we're not
6577       // accessing any of the loaded bytes.  If the load was a zextload/extload
6578       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6579       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6580         return SDValue();
6581     }
6582   }
6583
6584   // If the load is shifted left (and the result isn't shifted back right),
6585   // we can fold the truncate through the shift.
6586   unsigned ShLeftAmt = 0;
6587   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6588       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6589     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6590       ShLeftAmt = N01->getZExtValue();
6591       N0 = N0.getOperand(0);
6592     }
6593   }
6594
6595   // If we haven't found a load, we can't narrow it.  Don't transform one with
6596   // multiple uses, this would require adding a new load.
6597   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6598     return SDValue();
6599
6600   // Don't change the width of a volatile load.
6601   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6602   if (LN0->isVolatile())
6603     return SDValue();
6604
6605   // Verify that we are actually reducing a load width here.
6606   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6607     return SDValue();
6608
6609   // For the transform to be legal, the load must produce only two values
6610   // (the value loaded and the chain).  Don't transform a pre-increment
6611   // load, for example, which produces an extra value.  Otherwise the
6612   // transformation is not equivalent, and the downstream logic to replace
6613   // uses gets things wrong.
6614   if (LN0->getNumValues() > 2)
6615     return SDValue();
6616
6617   // If the load that we're shrinking is an extload and we're not just
6618   // discarding the extension we can't simply shrink the load. Bail.
6619   // TODO: It would be possible to merge the extensions in some cases.
6620   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6621       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6622     return SDValue();
6623
6624   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6625     return SDValue();
6626
6627   EVT PtrType = N0.getOperand(1).getValueType();
6628
6629   if (PtrType == MVT::Untyped || PtrType.isExtended())
6630     // It's not possible to generate a constant of extended or untyped type.
6631     return SDValue();
6632
6633   // For big endian targets, we need to adjust the offset to the pointer to
6634   // load the correct bytes.
6635   if (TLI.isBigEndian()) {
6636     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6637     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6638     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6639   }
6640
6641   uint64_t PtrOff = ShAmt / 8;
6642   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6643   SDLoc DL(LN0);
6644   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6645                                PtrType, LN0->getBasePtr(),
6646                                DAG.getConstant(PtrOff, DL, PtrType));
6647   AddToWorklist(NewPtr.getNode());
6648
6649   SDValue Load;
6650   if (ExtType == ISD::NON_EXTLOAD)
6651     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6652                         LN0->getPointerInfo().getWithOffset(PtrOff),
6653                         LN0->isVolatile(), LN0->isNonTemporal(),
6654                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6655   else
6656     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6657                           LN0->getPointerInfo().getWithOffset(PtrOff),
6658                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6659                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6660
6661   // Replace the old load's chain with the new load's chain.
6662   WorklistRemover DeadNodes(*this);
6663   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6664
6665   // Shift the result left, if we've swallowed a left shift.
6666   SDValue Result = Load;
6667   if (ShLeftAmt != 0) {
6668     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6669     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6670       ShImmTy = VT;
6671     // If the shift amount is as large as the result size (but, presumably,
6672     // no larger than the source) then the useful bits of the result are
6673     // zero; we can't simply return the shortened shift, because the result
6674     // of that operation is undefined.
6675     SDLoc DL(N0);
6676     if (ShLeftAmt >= VT.getSizeInBits())
6677       Result = DAG.getConstant(0, DL, VT);
6678     else
6679       Result = DAG.getNode(ISD::SHL, DL, VT,
6680                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6681   }
6682
6683   // Return the new loaded value.
6684   return Result;
6685 }
6686
6687 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6688   SDValue N0 = N->getOperand(0);
6689   SDValue N1 = N->getOperand(1);
6690   EVT VT = N->getValueType(0);
6691   EVT EVT = cast<VTSDNode>(N1)->getVT();
6692   unsigned VTBits = VT.getScalarType().getSizeInBits();
6693   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6694
6695   // fold (sext_in_reg c1) -> c1
6696   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6697     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6698
6699   // If the input is already sign extended, just drop the extension.
6700   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6701     return N0;
6702
6703   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6704   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6705       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6706     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6707                        N0.getOperand(0), N1);
6708
6709   // fold (sext_in_reg (sext x)) -> (sext x)
6710   // fold (sext_in_reg (aext x)) -> (sext x)
6711   // if x is small enough.
6712   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6713     SDValue N00 = N0.getOperand(0);
6714     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6715         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6716       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6717   }
6718
6719   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6720   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6721     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6722
6723   // fold operands of sext_in_reg based on knowledge that the top bits are not
6724   // demanded.
6725   if (SimplifyDemandedBits(SDValue(N, 0)))
6726     return SDValue(N, 0);
6727
6728   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6729   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6730   SDValue NarrowLoad = ReduceLoadWidth(N);
6731   if (NarrowLoad.getNode())
6732     return NarrowLoad;
6733
6734   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6735   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6736   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6737   if (N0.getOpcode() == ISD::SRL) {
6738     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6739       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6740         // We can turn this into an SRA iff the input to the SRL is already sign
6741         // extended enough.
6742         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6743         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6744           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6745                              N0.getOperand(0), N0.getOperand(1));
6746       }
6747   }
6748
6749   // fold (sext_inreg (extload x)) -> (sextload x)
6750   if (ISD::isEXTLoad(N0.getNode()) &&
6751       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6752       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6753       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6754        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6755     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6756     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6757                                      LN0->getChain(),
6758                                      LN0->getBasePtr(), EVT,
6759                                      LN0->getMemOperand());
6760     CombineTo(N, ExtLoad);
6761     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6762     AddToWorklist(ExtLoad.getNode());
6763     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6764   }
6765   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6766   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6767       N0.hasOneUse() &&
6768       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6769       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6770        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6771     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6772     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6773                                      LN0->getChain(),
6774                                      LN0->getBasePtr(), EVT,
6775                                      LN0->getMemOperand());
6776     CombineTo(N, ExtLoad);
6777     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6778     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6779   }
6780
6781   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6782   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6783     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6784                                        N0.getOperand(1), false);
6785     if (BSwap.getNode())
6786       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6787                          BSwap, N1);
6788   }
6789
6790   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6791   // into a build_vector.
6792   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6793     SmallVector<SDValue, 8> Elts;
6794     unsigned NumElts = N0->getNumOperands();
6795     unsigned ShAmt = VTBits - EVTBits;
6796
6797     for (unsigned i = 0; i != NumElts; ++i) {
6798       SDValue Op = N0->getOperand(i);
6799       if (Op->getOpcode() == ISD::UNDEF) {
6800         Elts.push_back(Op);
6801         continue;
6802       }
6803
6804       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6805       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6806       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6807                                      SDLoc(Op), Op.getValueType()));
6808     }
6809
6810     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6811   }
6812
6813   return SDValue();
6814 }
6815
6816 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6817   SDValue N0 = N->getOperand(0);
6818   EVT VT = N->getValueType(0);
6819
6820   if (N0.getOpcode() == ISD::UNDEF)
6821     return DAG.getUNDEF(VT);
6822
6823   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6824                                               LegalOperations))
6825     return SDValue(Res, 0);
6826
6827   return SDValue();
6828 }
6829
6830 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6831   SDValue N0 = N->getOperand(0);
6832   EVT VT = N->getValueType(0);
6833   bool isLE = TLI.isLittleEndian();
6834
6835   // noop truncate
6836   if (N0.getValueType() == N->getValueType(0))
6837     return N0;
6838   // fold (truncate c1) -> c1
6839   if (isConstantIntBuildVectorOrConstantInt(N0))
6840     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6841   // fold (truncate (truncate x)) -> (truncate x)
6842   if (N0.getOpcode() == ISD::TRUNCATE)
6843     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6844   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6845   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6846       N0.getOpcode() == ISD::SIGN_EXTEND ||
6847       N0.getOpcode() == ISD::ANY_EXTEND) {
6848     if (N0.getOperand(0).getValueType().bitsLT(VT))
6849       // if the source is smaller than the dest, we still need an extend
6850       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6851                          N0.getOperand(0));
6852     if (N0.getOperand(0).getValueType().bitsGT(VT))
6853       // if the source is larger than the dest, than we just need the truncate
6854       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6855     // if the source and dest are the same type, we can drop both the extend
6856     // and the truncate.
6857     return N0.getOperand(0);
6858   }
6859
6860   // Fold extract-and-trunc into a narrow extract. For example:
6861   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6862   //   i32 y = TRUNCATE(i64 x)
6863   //        -- becomes --
6864   //   v16i8 b = BITCAST (v2i64 val)
6865   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6866   //
6867   // Note: We only run this optimization after type legalization (which often
6868   // creates this pattern) and before operation legalization after which
6869   // we need to be more careful about the vector instructions that we generate.
6870   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6871       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6872
6873     EVT VecTy = N0.getOperand(0).getValueType();
6874     EVT ExTy = N0.getValueType();
6875     EVT TrTy = N->getValueType(0);
6876
6877     unsigned NumElem = VecTy.getVectorNumElements();
6878     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6879
6880     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6881     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6882
6883     SDValue EltNo = N0->getOperand(1);
6884     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6885       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6886       EVT IndexTy = TLI.getVectorIdxTy();
6887       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6888
6889       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6890                               NVT, N0.getOperand(0));
6891
6892       SDLoc DL(N);
6893       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6894                          DL, TrTy, V,
6895                          DAG.getConstant(Index, DL, IndexTy));
6896     }
6897   }
6898
6899   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6900   if (N0.getOpcode() == ISD::SELECT) {
6901     EVT SrcVT = N0.getValueType();
6902     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6903         TLI.isTruncateFree(SrcVT, VT)) {
6904       SDLoc SL(N0);
6905       SDValue Cond = N0.getOperand(0);
6906       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6907       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6908       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6909     }
6910   }
6911
6912   // Fold a series of buildvector, bitcast, and truncate if possible.
6913   // For example fold
6914   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6915   //   (2xi32 (buildvector x, y)).
6916   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6917       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6918       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6919       N0.getOperand(0).hasOneUse()) {
6920
6921     SDValue BuildVect = N0.getOperand(0);
6922     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6923     EVT TruncVecEltTy = VT.getVectorElementType();
6924
6925     // Check that the element types match.
6926     if (BuildVectEltTy == TruncVecEltTy) {
6927       // Now we only need to compute the offset of the truncated elements.
6928       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6929       unsigned TruncVecNumElts = VT.getVectorNumElements();
6930       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6931
6932       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6933              "Invalid number of elements");
6934
6935       SmallVector<SDValue, 8> Opnds;
6936       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6937         Opnds.push_back(BuildVect.getOperand(i));
6938
6939       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6940     }
6941   }
6942
6943   // See if we can simplify the input to this truncate through knowledge that
6944   // only the low bits are being used.
6945   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6946   // Currently we only perform this optimization on scalars because vectors
6947   // may have different active low bits.
6948   if (!VT.isVector()) {
6949     SDValue Shorter =
6950       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6951                                                VT.getSizeInBits()));
6952     if (Shorter.getNode())
6953       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6954   }
6955   // fold (truncate (load x)) -> (smaller load x)
6956   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6957   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6958     SDValue Reduced = ReduceLoadWidth(N);
6959     if (Reduced.getNode())
6960       return Reduced;
6961     // Handle the case where the load remains an extending load even
6962     // after truncation.
6963     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6964       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6965       if (!LN0->isVolatile() &&
6966           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6967         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6968                                          VT, LN0->getChain(), LN0->getBasePtr(),
6969                                          LN0->getMemoryVT(),
6970                                          LN0->getMemOperand());
6971         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6972         return NewLoad;
6973       }
6974     }
6975   }
6976   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6977   // where ... are all 'undef'.
6978   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6979     SmallVector<EVT, 8> VTs;
6980     SDValue V;
6981     unsigned Idx = 0;
6982     unsigned NumDefs = 0;
6983
6984     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6985       SDValue X = N0.getOperand(i);
6986       if (X.getOpcode() != ISD::UNDEF) {
6987         V = X;
6988         Idx = i;
6989         NumDefs++;
6990       }
6991       // Stop if more than one members are non-undef.
6992       if (NumDefs > 1)
6993         break;
6994       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6995                                      VT.getVectorElementType(),
6996                                      X.getValueType().getVectorNumElements()));
6997     }
6998
6999     if (NumDefs == 0)
7000       return DAG.getUNDEF(VT);
7001
7002     if (NumDefs == 1) {
7003       assert(V.getNode() && "The single defined operand is empty!");
7004       SmallVector<SDValue, 8> Opnds;
7005       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7006         if (i != Idx) {
7007           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7008           continue;
7009         }
7010         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7011         AddToWorklist(NV.getNode());
7012         Opnds.push_back(NV);
7013       }
7014       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7015     }
7016   }
7017
7018   // Simplify the operands using demanded-bits information.
7019   if (!VT.isVector() &&
7020       SimplifyDemandedBits(SDValue(N, 0)))
7021     return SDValue(N, 0);
7022
7023   return SDValue();
7024 }
7025
7026 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7027   SDValue Elt = N->getOperand(i);
7028   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7029     return Elt.getNode();
7030   return Elt.getOperand(Elt.getResNo()).getNode();
7031 }
7032
7033 /// build_pair (load, load) -> load
7034 /// if load locations are consecutive.
7035 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7036   assert(N->getOpcode() == ISD::BUILD_PAIR);
7037
7038   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7039   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7040   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7041       LD1->getAddressSpace() != LD2->getAddressSpace())
7042     return SDValue();
7043   EVT LD1VT = LD1->getValueType(0);
7044
7045   if (ISD::isNON_EXTLoad(LD2) &&
7046       LD2->hasOneUse() &&
7047       // If both are volatile this would reduce the number of volatile loads.
7048       // If one is volatile it might be ok, but play conservative and bail out.
7049       !LD1->isVolatile() &&
7050       !LD2->isVolatile() &&
7051       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7052     unsigned Align = LD1->getAlignment();
7053     unsigned NewAlign = TLI.getDataLayout()->
7054       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7055
7056     if (NewAlign <= Align &&
7057         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7058       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7059                          LD1->getBasePtr(), LD1->getPointerInfo(),
7060                          false, false, false, Align);
7061   }
7062
7063   return SDValue();
7064 }
7065
7066 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7067   SDValue N0 = N->getOperand(0);
7068   EVT VT = N->getValueType(0);
7069
7070   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7071   // Only do this before legalize, since afterward the target may be depending
7072   // on the bitconvert.
7073   // First check to see if this is all constant.
7074   if (!LegalTypes &&
7075       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7076       VT.isVector()) {
7077     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7078
7079     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7080     assert(!DestEltVT.isVector() &&
7081            "Element type of vector ValueType must not be vector!");
7082     if (isSimple)
7083       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7084   }
7085
7086   // If the input is a constant, let getNode fold it.
7087   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7088     // If we can't allow illegal operations, we need to check that this is just
7089     // a fp -> int or int -> conversion and that the resulting operation will
7090     // be legal.
7091     if (!LegalOperations ||
7092         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7093          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7094         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7095          TLI.isOperationLegal(ISD::Constant, VT)))
7096       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7097   }
7098
7099   // (conv (conv x, t1), t2) -> (conv x, t2)
7100   if (N0.getOpcode() == ISD::BITCAST)
7101     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7102                        N0.getOperand(0));
7103
7104   // fold (conv (load x)) -> (load (conv*)x)
7105   // If the resultant load doesn't need a higher alignment than the original!
7106   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7107       // Do not change the width of a volatile load.
7108       !cast<LoadSDNode>(N0)->isVolatile() &&
7109       // Do not remove the cast if the types differ in endian layout.
7110       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7111       TLI.hasBigEndianPartOrdering(VT) &&
7112       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7113       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7114     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7115     unsigned Align = TLI.getDataLayout()->
7116       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7117     unsigned OrigAlign = LN0->getAlignment();
7118
7119     if (Align <= OrigAlign) {
7120       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7121                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7122                                  LN0->isVolatile(), LN0->isNonTemporal(),
7123                                  LN0->isInvariant(), OrigAlign,
7124                                  LN0->getAAInfo());
7125       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7126       return Load;
7127     }
7128   }
7129
7130   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7131   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7132   // This often reduces constant pool loads.
7133   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7134        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7135       N0.getNode()->hasOneUse() && VT.isInteger() &&
7136       !VT.isVector() && !N0.getValueType().isVector()) {
7137     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7138                                   N0.getOperand(0));
7139     AddToWorklist(NewConv.getNode());
7140
7141     SDLoc DL(N);
7142     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7143     if (N0.getOpcode() == ISD::FNEG)
7144       return DAG.getNode(ISD::XOR, DL, VT,
7145                          NewConv, DAG.getConstant(SignBit, DL, VT));
7146     assert(N0.getOpcode() == ISD::FABS);
7147     return DAG.getNode(ISD::AND, DL, VT,
7148                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7149   }
7150
7151   // fold (bitconvert (fcopysign cst, x)) ->
7152   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7153   // Note that we don't handle (copysign x, cst) because this can always be
7154   // folded to an fneg or fabs.
7155   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7156       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7157       VT.isInteger() && !VT.isVector()) {
7158     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7159     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7160     if (isTypeLegal(IntXVT)) {
7161       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7162                               IntXVT, N0.getOperand(1));
7163       AddToWorklist(X.getNode());
7164
7165       // If X has a different width than the result/lhs, sext it or truncate it.
7166       unsigned VTWidth = VT.getSizeInBits();
7167       if (OrigXWidth < VTWidth) {
7168         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7169         AddToWorklist(X.getNode());
7170       } else if (OrigXWidth > VTWidth) {
7171         // To get the sign bit in the right place, we have to shift it right
7172         // before truncating.
7173         SDLoc DL(X);
7174         X = DAG.getNode(ISD::SRL, DL,
7175                         X.getValueType(), X,
7176                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7177                                         X.getValueType()));
7178         AddToWorklist(X.getNode());
7179         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7180         AddToWorklist(X.getNode());
7181       }
7182
7183       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7184       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7185                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7186       AddToWorklist(X.getNode());
7187
7188       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7189                                 VT, N0.getOperand(0));
7190       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7191                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7192       AddToWorklist(Cst.getNode());
7193
7194       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7195     }
7196   }
7197
7198   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7199   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7200     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7201     if (CombineLD.getNode())
7202       return CombineLD;
7203   }
7204
7205   // Remove double bitcasts from shuffles - this is often a legacy of
7206   // XformToShuffleWithZero being used to combine bitmaskings (of
7207   // float vectors bitcast to integer vectors) into shuffles.
7208   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7209   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7210       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7211       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7212       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7213     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7214
7215     // If operands are a bitcast, peek through if it casts the original VT.
7216     // If operands are a UNDEF or constant, just bitcast back to original VT.
7217     auto PeekThroughBitcast = [&](SDValue Op) {
7218       if (Op.getOpcode() == ISD::BITCAST &&
7219           Op.getOperand(0)->getValueType(0) == VT)
7220         return SDValue(Op.getOperand(0));
7221       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7222           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7223         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7224       return SDValue();
7225     };
7226
7227     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7228     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7229     if (!(SV0 && SV1))
7230       return SDValue();
7231
7232     int MaskScale =
7233         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7234     SmallVector<int, 8> NewMask;
7235     for (int M : SVN->getMask())
7236       for (int i = 0; i != MaskScale; ++i)
7237         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7238
7239     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7240     if (!LegalMask) {
7241       std::swap(SV0, SV1);
7242       ShuffleVectorSDNode::commuteMask(NewMask);
7243       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7244     }
7245
7246     if (LegalMask)
7247       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7248   }
7249
7250   return SDValue();
7251 }
7252
7253 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7254   EVT VT = N->getValueType(0);
7255   return CombineConsecutiveLoads(N, VT);
7256 }
7257
7258 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7259 /// operands. DstEltVT indicates the destination element value type.
7260 SDValue DAGCombiner::
7261 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7262   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7263
7264   // If this is already the right type, we're done.
7265   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7266
7267   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7268   unsigned DstBitSize = DstEltVT.getSizeInBits();
7269
7270   // If this is a conversion of N elements of one type to N elements of another
7271   // type, convert each element.  This handles FP<->INT cases.
7272   if (SrcBitSize == DstBitSize) {
7273     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7274                               BV->getValueType(0).getVectorNumElements());
7275
7276     // Due to the FP element handling below calling this routine recursively,
7277     // we can end up with a scalar-to-vector node here.
7278     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7279       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7280                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7281                                      DstEltVT, BV->getOperand(0)));
7282
7283     SmallVector<SDValue, 8> Ops;
7284     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7285       SDValue Op = BV->getOperand(i);
7286       // If the vector element type is not legal, the BUILD_VECTOR operands
7287       // are promoted and implicitly truncated.  Make that explicit here.
7288       if (Op.getValueType() != SrcEltVT)
7289         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7290       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7291                                 DstEltVT, Op));
7292       AddToWorklist(Ops.back().getNode());
7293     }
7294     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7295   }
7296
7297   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7298   // handle annoying details of growing/shrinking FP values, we convert them to
7299   // int first.
7300   if (SrcEltVT.isFloatingPoint()) {
7301     // Convert the input float vector to a int vector where the elements are the
7302     // same sizes.
7303     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7304     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7305     SrcEltVT = IntVT;
7306   }
7307
7308   // Now we know the input is an integer vector.  If the output is a FP type,
7309   // convert to integer first, then to FP of the right size.
7310   if (DstEltVT.isFloatingPoint()) {
7311     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7312     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7313
7314     // Next, convert to FP elements of the same size.
7315     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7316   }
7317
7318   SDLoc DL(BV);
7319
7320   // Okay, we know the src/dst types are both integers of differing types.
7321   // Handling growing first.
7322   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7323   if (SrcBitSize < DstBitSize) {
7324     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7325
7326     SmallVector<SDValue, 8> Ops;
7327     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7328          i += NumInputsPerOutput) {
7329       bool isLE = TLI.isLittleEndian();
7330       APInt NewBits = APInt(DstBitSize, 0);
7331       bool EltIsUndef = true;
7332       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7333         // Shift the previously computed bits over.
7334         NewBits <<= SrcBitSize;
7335         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7336         if (Op.getOpcode() == ISD::UNDEF) continue;
7337         EltIsUndef = false;
7338
7339         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7340                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7341       }
7342
7343       if (EltIsUndef)
7344         Ops.push_back(DAG.getUNDEF(DstEltVT));
7345       else
7346         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7347     }
7348
7349     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7350     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7351   }
7352
7353   // Finally, this must be the case where we are shrinking elements: each input
7354   // turns into multiple outputs.
7355   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7356   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7357                             NumOutputsPerInput*BV->getNumOperands());
7358   SmallVector<SDValue, 8> Ops;
7359
7360   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7361     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7362       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7363       continue;
7364     }
7365
7366     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7367                   getAPIntValue().zextOrTrunc(SrcBitSize);
7368
7369     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7370       APInt ThisVal = OpVal.trunc(DstBitSize);
7371       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7372       OpVal = OpVal.lshr(DstBitSize);
7373     }
7374
7375     // For big endian targets, swap the order of the pieces of each element.
7376     if (TLI.isBigEndian())
7377       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7378   }
7379
7380   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7381 }
7382
7383 /// Try to perform FMA combining on a given FADD node.
7384 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7385   SDValue N0 = N->getOperand(0);
7386   SDValue N1 = N->getOperand(1);
7387   EVT VT = N->getValueType(0);
7388   SDLoc SL(N);
7389
7390   const TargetOptions &Options = DAG.getTarget().Options;
7391   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7392                        Options.UnsafeFPMath);
7393
7394   // Floating-point multiply-add with intermediate rounding.
7395   bool HasFMAD = (LegalOperations &&
7396                   TLI.isOperationLegal(ISD::FMAD, VT));
7397
7398   // Floating-point multiply-add without intermediate rounding.
7399   bool HasFMA = ((!LegalOperations ||
7400                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7401                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7402                  UnsafeFPMath);
7403
7404   // No valid opcode, do not combine.
7405   if (!HasFMAD && !HasFMA)
7406     return SDValue();
7407
7408   // Always prefer FMAD to FMA for precision.
7409   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7410   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7411   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7412
7413   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7414   if (N0.getOpcode() == ISD::FMUL &&
7415       (Aggressive || N0->hasOneUse())) {
7416     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7417                        N0.getOperand(0), N0.getOperand(1), N1);
7418   }
7419
7420   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7421   // Note: Commutes FADD operands.
7422   if (N1.getOpcode() == ISD::FMUL &&
7423       (Aggressive || N1->hasOneUse())) {
7424     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7425                        N1.getOperand(0), N1.getOperand(1), N0);
7426   }
7427
7428   // Look through FP_EXTEND nodes to do more combining.
7429   if (UnsafeFPMath && LookThroughFPExt) {
7430     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7431     if (N0.getOpcode() == ISD::FP_EXTEND) {
7432       SDValue N00 = N0.getOperand(0);
7433       if (N00.getOpcode() == ISD::FMUL)
7434         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7435                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7436                                        N00.getOperand(0)),
7437                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7438                                        N00.getOperand(1)), N1);
7439     }
7440
7441     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7442     // Note: Commutes FADD operands.
7443     if (N1.getOpcode() == ISD::FP_EXTEND) {
7444       SDValue N10 = N1.getOperand(0);
7445       if (N10.getOpcode() == ISD::FMUL)
7446         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7447                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7448                                        N10.getOperand(0)),
7449                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7450                                        N10.getOperand(1)), N0);
7451     }
7452   }
7453
7454   // More folding opportunities when target permits.
7455   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7456     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7457     if (N0.getOpcode() == PreferredFusedOpcode &&
7458         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7459       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7460                          N0.getOperand(0), N0.getOperand(1),
7461                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7462                                      N0.getOperand(2).getOperand(0),
7463                                      N0.getOperand(2).getOperand(1),
7464                                      N1));
7465     }
7466
7467     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7468     if (N1->getOpcode() == PreferredFusedOpcode &&
7469         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7470       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7471                          N1.getOperand(0), N1.getOperand(1),
7472                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7473                                      N1.getOperand(2).getOperand(0),
7474                                      N1.getOperand(2).getOperand(1),
7475                                      N0));
7476     }
7477
7478     if (UnsafeFPMath && LookThroughFPExt) {
7479       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7480       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7481       auto FoldFAddFMAFPExtFMul = [&] (
7482           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7483         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7484                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7485                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7486                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7487                                        Z));
7488       };
7489       if (N0.getOpcode() == PreferredFusedOpcode) {
7490         SDValue N02 = N0.getOperand(2);
7491         if (N02.getOpcode() == ISD::FP_EXTEND) {
7492           SDValue N020 = N02.getOperand(0);
7493           if (N020.getOpcode() == ISD::FMUL)
7494             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7495                                         N020.getOperand(0), N020.getOperand(1),
7496                                         N1);
7497         }
7498       }
7499
7500       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7501       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7502       // FIXME: This turns two single-precision and one double-precision
7503       // operation into two double-precision operations, which might not be
7504       // interesting for all targets, especially GPUs.
7505       auto FoldFAddFPExtFMAFMul = [&] (
7506           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7507         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7508                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7509                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7510                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7511                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7512                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7513                                        Z));
7514       };
7515       if (N0.getOpcode() == ISD::FP_EXTEND) {
7516         SDValue N00 = N0.getOperand(0);
7517         if (N00.getOpcode() == PreferredFusedOpcode) {
7518           SDValue N002 = N00.getOperand(2);
7519           if (N002.getOpcode() == ISD::FMUL)
7520             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7521                                         N002.getOperand(0), N002.getOperand(1),
7522                                         N1);
7523         }
7524       }
7525
7526       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7527       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7528       if (N1.getOpcode() == PreferredFusedOpcode) {
7529         SDValue N12 = N1.getOperand(2);
7530         if (N12.getOpcode() == ISD::FP_EXTEND) {
7531           SDValue N120 = N12.getOperand(0);
7532           if (N120.getOpcode() == ISD::FMUL)
7533             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7534                                         N120.getOperand(0), N120.getOperand(1),
7535                                         N0);
7536         }
7537       }
7538
7539       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7540       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7541       // FIXME: This turns two single-precision and one double-precision
7542       // operation into two double-precision operations, which might not be
7543       // interesting for all targets, especially GPUs.
7544       if (N1.getOpcode() == ISD::FP_EXTEND) {
7545         SDValue N10 = N1.getOperand(0);
7546         if (N10.getOpcode() == PreferredFusedOpcode) {
7547           SDValue N102 = N10.getOperand(2);
7548           if (N102.getOpcode() == ISD::FMUL)
7549             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7550                                         N102.getOperand(0), N102.getOperand(1),
7551                                         N0);
7552         }
7553       }
7554     }
7555   }
7556
7557   return SDValue();
7558 }
7559
7560 /// Try to perform FMA combining on a given FSUB node.
7561 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7562   SDValue N0 = N->getOperand(0);
7563   SDValue N1 = N->getOperand(1);
7564   EVT VT = N->getValueType(0);
7565   SDLoc SL(N);
7566
7567   const TargetOptions &Options = DAG.getTarget().Options;
7568   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7569                        Options.UnsafeFPMath);
7570
7571   // Floating-point multiply-add with intermediate rounding.
7572   bool HasFMAD = (LegalOperations &&
7573                   TLI.isOperationLegal(ISD::FMAD, VT));
7574
7575   // Floating-point multiply-add without intermediate rounding.
7576   bool HasFMA = ((!LegalOperations ||
7577                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7578                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7579                  UnsafeFPMath);
7580
7581   // No valid opcode, do not combine.
7582   if (!HasFMAD && !HasFMA)
7583     return SDValue();
7584
7585   // Always prefer FMAD to FMA for precision.
7586   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7587   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7588   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7589
7590   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7591   if (N0.getOpcode() == ISD::FMUL &&
7592       (Aggressive || N0->hasOneUse())) {
7593     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7594                        N0.getOperand(0), N0.getOperand(1),
7595                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7596   }
7597
7598   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7599   // Note: Commutes FSUB operands.
7600   if (N1.getOpcode() == ISD::FMUL &&
7601       (Aggressive || N1->hasOneUse()))
7602     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7603                        DAG.getNode(ISD::FNEG, SL, VT,
7604                                    N1.getOperand(0)),
7605                        N1.getOperand(1), N0);
7606
7607   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7608   if (N0.getOpcode() == ISD::FNEG &&
7609       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7610       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7611     SDValue N00 = N0.getOperand(0).getOperand(0);
7612     SDValue N01 = N0.getOperand(0).getOperand(1);
7613     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7614                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7615                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7616   }
7617
7618   // Look through FP_EXTEND nodes to do more combining.
7619   if (UnsafeFPMath && LookThroughFPExt) {
7620     // fold (fsub (fpext (fmul x, y)), z)
7621     //   -> (fma (fpext x), (fpext y), (fneg z))
7622     if (N0.getOpcode() == ISD::FP_EXTEND) {
7623       SDValue N00 = N0.getOperand(0);
7624       if (N00.getOpcode() == ISD::FMUL)
7625         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7626                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7627                                        N00.getOperand(0)),
7628                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7629                                        N00.getOperand(1)),
7630                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7631     }
7632
7633     // fold (fsub x, (fpext (fmul y, z)))
7634     //   -> (fma (fneg (fpext y)), (fpext z), x)
7635     // Note: Commutes FSUB operands.
7636     if (N1.getOpcode() == ISD::FP_EXTEND) {
7637       SDValue N10 = N1.getOperand(0);
7638       if (N10.getOpcode() == ISD::FMUL)
7639         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7640                            DAG.getNode(ISD::FNEG, SL, VT,
7641                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7642                                                    N10.getOperand(0))),
7643                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7644                                        N10.getOperand(1)),
7645                            N0);
7646     }
7647
7648     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7649     //   -> (fneg (fma (fpext x), (fpext y), z))
7650     // Note: This could be removed with appropriate canonicalization of the
7651     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7652     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7653     // from implementing the canonicalization in visitFSUB.
7654     if (N0.getOpcode() == ISD::FP_EXTEND) {
7655       SDValue N00 = N0.getOperand(0);
7656       if (N00.getOpcode() == ISD::FNEG) {
7657         SDValue N000 = N00.getOperand(0);
7658         if (N000.getOpcode() == ISD::FMUL) {
7659           return DAG.getNode(ISD::FNEG, SL, VT,
7660                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7661                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7662                                                      N000.getOperand(0)),
7663                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7664                                                      N000.getOperand(1)),
7665                                          N1));
7666         }
7667       }
7668     }
7669
7670     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7671     //   -> (fneg (fma (fpext x)), (fpext y), z)
7672     // Note: This could be removed with appropriate canonicalization of the
7673     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7674     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7675     // from implementing the canonicalization in visitFSUB.
7676     if (N0.getOpcode() == ISD::FNEG) {
7677       SDValue N00 = N0.getOperand(0);
7678       if (N00.getOpcode() == ISD::FP_EXTEND) {
7679         SDValue N000 = N00.getOperand(0);
7680         if (N000.getOpcode() == ISD::FMUL) {
7681           return DAG.getNode(ISD::FNEG, SL, VT,
7682                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7683                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7684                                                      N000.getOperand(0)),
7685                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7686                                                      N000.getOperand(1)),
7687                                          N1));
7688         }
7689       }
7690     }
7691
7692   }
7693
7694   // More folding opportunities when target permits.
7695   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7696     // fold (fsub (fma x, y, (fmul u, v)), z)
7697     //   -> (fma x, y (fma u, v, (fneg z)))
7698     if (N0.getOpcode() == PreferredFusedOpcode &&
7699         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7700       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7701                          N0.getOperand(0), N0.getOperand(1),
7702                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7703                                      N0.getOperand(2).getOperand(0),
7704                                      N0.getOperand(2).getOperand(1),
7705                                      DAG.getNode(ISD::FNEG, SL, VT,
7706                                                  N1)));
7707     }
7708
7709     // fold (fsub x, (fma y, z, (fmul u, v)))
7710     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7711     if (N1.getOpcode() == PreferredFusedOpcode &&
7712         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7713       SDValue N20 = N1.getOperand(2).getOperand(0);
7714       SDValue N21 = N1.getOperand(2).getOperand(1);
7715       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7716                          DAG.getNode(ISD::FNEG, SL, VT,
7717                                      N1.getOperand(0)),
7718                          N1.getOperand(1),
7719                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7720                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7721
7722                                      N21, N0));
7723     }
7724
7725     if (UnsafeFPMath && LookThroughFPExt) {
7726       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7727       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7728       if (N0.getOpcode() == PreferredFusedOpcode) {
7729         SDValue N02 = N0.getOperand(2);
7730         if (N02.getOpcode() == ISD::FP_EXTEND) {
7731           SDValue N020 = N02.getOperand(0);
7732           if (N020.getOpcode() == ISD::FMUL)
7733             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7734                                N0.getOperand(0), N0.getOperand(1),
7735                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7736                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7737                                                        N020.getOperand(0)),
7738                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7739                                                        N020.getOperand(1)),
7740                                            DAG.getNode(ISD::FNEG, SL, VT,
7741                                                        N1)));
7742         }
7743       }
7744
7745       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7746       //   -> (fma (fpext x), (fpext y),
7747       //           (fma (fpext u), (fpext v), (fneg z)))
7748       // FIXME: This turns two single-precision and one double-precision
7749       // operation into two double-precision operations, which might not be
7750       // interesting for all targets, especially GPUs.
7751       if (N0.getOpcode() == ISD::FP_EXTEND) {
7752         SDValue N00 = N0.getOperand(0);
7753         if (N00.getOpcode() == PreferredFusedOpcode) {
7754           SDValue N002 = N00.getOperand(2);
7755           if (N002.getOpcode() == ISD::FMUL)
7756             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7757                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7758                                            N00.getOperand(0)),
7759                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7760                                            N00.getOperand(1)),
7761                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7762                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7763                                                        N002.getOperand(0)),
7764                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7765                                                        N002.getOperand(1)),
7766                                            DAG.getNode(ISD::FNEG, SL, VT,
7767                                                        N1)));
7768         }
7769       }
7770
7771       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7772       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7773       if (N1.getOpcode() == PreferredFusedOpcode &&
7774         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7775         SDValue N120 = N1.getOperand(2).getOperand(0);
7776         if (N120.getOpcode() == ISD::FMUL) {
7777           SDValue N1200 = N120.getOperand(0);
7778           SDValue N1201 = N120.getOperand(1);
7779           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7780                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7781                              N1.getOperand(1),
7782                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7783                                          DAG.getNode(ISD::FNEG, SL, VT,
7784                                              DAG.getNode(ISD::FP_EXTEND, SL,
7785                                                          VT, N1200)),
7786                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7787                                                      N1201),
7788                                          N0));
7789         }
7790       }
7791
7792       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7793       //   -> (fma (fneg (fpext y)), (fpext z),
7794       //           (fma (fneg (fpext u)), (fpext v), x))
7795       // FIXME: This turns two single-precision and one double-precision
7796       // operation into two double-precision operations, which might not be
7797       // interesting for all targets, especially GPUs.
7798       if (N1.getOpcode() == ISD::FP_EXTEND &&
7799         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7800         SDValue N100 = N1.getOperand(0).getOperand(0);
7801         SDValue N101 = N1.getOperand(0).getOperand(1);
7802         SDValue N102 = N1.getOperand(0).getOperand(2);
7803         if (N102.getOpcode() == ISD::FMUL) {
7804           SDValue N1020 = N102.getOperand(0);
7805           SDValue N1021 = N102.getOperand(1);
7806           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7807                              DAG.getNode(ISD::FNEG, SL, VT,
7808                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7809                                                      N100)),
7810                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7811                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7812                                          DAG.getNode(ISD::FNEG, SL, VT,
7813                                              DAG.getNode(ISD::FP_EXTEND, SL,
7814                                                          VT, N1020)),
7815                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7816                                                      N1021),
7817                                          N0));
7818         }
7819       }
7820     }
7821   }
7822
7823   return SDValue();
7824 }
7825
7826 SDValue DAGCombiner::visitFADD(SDNode *N) {
7827   SDValue N0 = N->getOperand(0);
7828   SDValue N1 = N->getOperand(1);
7829   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7830   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7831   EVT VT = N->getValueType(0);
7832   SDLoc DL(N);
7833   const TargetOptions &Options = DAG.getTarget().Options;
7834
7835   // fold vector ops
7836   if (VT.isVector())
7837     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7838       return FoldedVOp;
7839
7840   // fold (fadd c1, c2) -> c1 + c2
7841   if (N0CFP && N1CFP)
7842     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7843
7844   // canonicalize constant to RHS
7845   if (N0CFP && !N1CFP)
7846     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7847
7848   // fold (fadd A, (fneg B)) -> (fsub A, B)
7849   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7850       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7851     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7852                        GetNegatedExpression(N1, DAG, LegalOperations));
7853
7854   // fold (fadd (fneg A), B) -> (fsub B, A)
7855   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7856       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7857     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7858                        GetNegatedExpression(N0, DAG, LegalOperations));
7859
7860   // If 'unsafe math' is enabled, fold lots of things.
7861   if (Options.UnsafeFPMath) {
7862     // No FP constant should be created after legalization as Instruction
7863     // Selection pass has a hard time dealing with FP constants.
7864     bool AllowNewConst = (Level < AfterLegalizeDAG);
7865
7866     // fold (fadd A, 0) -> A
7867     if (N1CFP && N1CFP->getValueAPF().isZero())
7868       return N0;
7869
7870     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7871     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7872         isa<ConstantFPSDNode>(N0.getOperand(1)))
7873       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7874                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7875
7876     // If allowed, fold (fadd (fneg x), x) -> 0.0
7877     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7878       return DAG.getConstantFP(0.0, DL, VT);
7879
7880     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7881     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7882       return DAG.getConstantFP(0.0, DL, VT);
7883
7884     // We can fold chains of FADD's of the same value into multiplications.
7885     // This transform is not safe in general because we are reducing the number
7886     // of rounding steps.
7887     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7888       if (N0.getOpcode() == ISD::FMUL) {
7889         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7890         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7891
7892         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7893         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7894           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7895                                        DAG.getConstantFP(1.0, DL, VT));
7896           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7897         }
7898
7899         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7900         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7901             N1.getOperand(0) == N1.getOperand(1) &&
7902             N0.getOperand(0) == N1.getOperand(0)) {
7903           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7904                                        DAG.getConstantFP(2.0, DL, VT));
7905           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7906         }
7907       }
7908
7909       if (N1.getOpcode() == ISD::FMUL) {
7910         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7911         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7912
7913         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7914         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7915           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7916                                        DAG.getConstantFP(1.0, DL, VT));
7917           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7918         }
7919
7920         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7921         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7922             N0.getOperand(0) == N0.getOperand(1) &&
7923             N1.getOperand(0) == N0.getOperand(0)) {
7924           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7925                                        DAG.getConstantFP(2.0, DL, VT));
7926           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7927         }
7928       }
7929
7930       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7931         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7932         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7933         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7934             (N0.getOperand(0) == N1)) {
7935           return DAG.getNode(ISD::FMUL, DL, VT,
7936                              N1, DAG.getConstantFP(3.0, DL, VT));
7937         }
7938       }
7939
7940       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7941         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7942         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7943         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7944             N1.getOperand(0) == N0) {
7945           return DAG.getNode(ISD::FMUL, DL, VT,
7946                              N0, DAG.getConstantFP(3.0, DL, VT));
7947         }
7948       }
7949
7950       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7951       if (AllowNewConst &&
7952           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7953           N0.getOperand(0) == N0.getOperand(1) &&
7954           N1.getOperand(0) == N1.getOperand(1) &&
7955           N0.getOperand(0) == N1.getOperand(0)) {
7956         return DAG.getNode(ISD::FMUL, DL, VT,
7957                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7958       }
7959     }
7960   } // enable-unsafe-fp-math
7961
7962   // FADD -> FMA combines:
7963   SDValue Fused = visitFADDForFMACombine(N);
7964   if (Fused) {
7965     AddToWorklist(Fused.getNode());
7966     return Fused;
7967   }
7968
7969   return SDValue();
7970 }
7971
7972 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7973   SDValue N0 = N->getOperand(0);
7974   SDValue N1 = N->getOperand(1);
7975   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7976   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7977   EVT VT = N->getValueType(0);
7978   SDLoc dl(N);
7979   const TargetOptions &Options = DAG.getTarget().Options;
7980
7981   // fold vector ops
7982   if (VT.isVector())
7983     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7984       return FoldedVOp;
7985
7986   // fold (fsub c1, c2) -> c1-c2
7987   if (N0CFP && N1CFP)
7988     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7989
7990   // fold (fsub A, (fneg B)) -> (fadd A, B)
7991   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7992     return DAG.getNode(ISD::FADD, dl, VT, N0,
7993                        GetNegatedExpression(N1, DAG, LegalOperations));
7994
7995   // If 'unsafe math' is enabled, fold lots of things.
7996   if (Options.UnsafeFPMath) {
7997     // (fsub A, 0) -> A
7998     if (N1CFP && N1CFP->getValueAPF().isZero())
7999       return N0;
8000
8001     // (fsub 0, B) -> -B
8002     if (N0CFP && N0CFP->getValueAPF().isZero()) {
8003       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8004         return GetNegatedExpression(N1, DAG, LegalOperations);
8005       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8006         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8007     }
8008
8009     // (fsub x, x) -> 0.0
8010     if (N0 == N1)
8011       return DAG.getConstantFP(0.0f, dl, VT);
8012
8013     // (fsub x, (fadd x, y)) -> (fneg y)
8014     // (fsub x, (fadd y, x)) -> (fneg y)
8015     if (N1.getOpcode() == ISD::FADD) {
8016       SDValue N10 = N1->getOperand(0);
8017       SDValue N11 = N1->getOperand(1);
8018
8019       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8020         return GetNegatedExpression(N11, DAG, LegalOperations);
8021
8022       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8023         return GetNegatedExpression(N10, DAG, LegalOperations);
8024     }
8025   }
8026
8027   // FSUB -> FMA combines:
8028   SDValue Fused = visitFSUBForFMACombine(N);
8029   if (Fused) {
8030     AddToWorklist(Fused.getNode());
8031     return Fused;
8032   }
8033
8034   return SDValue();
8035 }
8036
8037 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8038   SDValue N0 = N->getOperand(0);
8039   SDValue N1 = N->getOperand(1);
8040   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8041   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8042   EVT VT = N->getValueType(0);
8043   SDLoc DL(N);
8044   const TargetOptions &Options = DAG.getTarget().Options;
8045
8046   // fold vector ops
8047   if (VT.isVector()) {
8048     // This just handles C1 * C2 for vectors. Other vector folds are below.
8049     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8050       return FoldedVOp;
8051   }
8052
8053   // fold (fmul c1, c2) -> c1*c2
8054   if (N0CFP && N1CFP)
8055     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8056
8057   // canonicalize constant to RHS
8058   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8059      !isConstantFPBuildVectorOrConstantFP(N1))
8060     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8061
8062   // fold (fmul A, 1.0) -> A
8063   if (N1CFP && N1CFP->isExactlyValue(1.0))
8064     return N0;
8065
8066   if (Options.UnsafeFPMath) {
8067     // fold (fmul A, 0) -> 0
8068     if (N1CFP && N1CFP->getValueAPF().isZero())
8069       return N1;
8070
8071     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8072     if (N0.getOpcode() == ISD::FMUL) {
8073       // Fold scalars or any vector constants (not just splats).
8074       // This fold is done in general by InstCombine, but extra fmul insts
8075       // may have been generated during lowering.
8076       SDValue N00 = N0.getOperand(0);
8077       SDValue N01 = N0.getOperand(1);
8078       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8079       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8080       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8081       
8082       // Check 1: Make sure that the first operand of the inner multiply is NOT
8083       // a constant. Otherwise, we may induce infinite looping.
8084       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8085         // Check 2: Make sure that the second operand of the inner multiply and
8086         // the second operand of the outer multiply are constants.
8087         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8088             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8089           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8090           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8091         }
8092       }
8093     }
8094
8095     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8096     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8097     // during an early run of DAGCombiner can prevent folding with fmuls
8098     // inserted during lowering.
8099     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8100       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8101       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8102       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8103     }
8104   }
8105
8106   // fold (fmul X, 2.0) -> (fadd X, X)
8107   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8108     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8109
8110   // fold (fmul X, -1.0) -> (fneg X)
8111   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8112     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8113       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8114
8115   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8116   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8117     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8118       // Both can be negated for free, check to see if at least one is cheaper
8119       // negated.
8120       if (LHSNeg == 2 || RHSNeg == 2)
8121         return DAG.getNode(ISD::FMUL, DL, VT,
8122                            GetNegatedExpression(N0, DAG, LegalOperations),
8123                            GetNegatedExpression(N1, DAG, LegalOperations));
8124     }
8125   }
8126
8127   return SDValue();
8128 }
8129
8130 SDValue DAGCombiner::visitFMA(SDNode *N) {
8131   SDValue N0 = N->getOperand(0);
8132   SDValue N1 = N->getOperand(1);
8133   SDValue N2 = N->getOperand(2);
8134   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8135   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8136   EVT VT = N->getValueType(0);
8137   SDLoc dl(N);
8138   const TargetOptions &Options = DAG.getTarget().Options;
8139
8140   // Constant fold FMA.
8141   if (isa<ConstantFPSDNode>(N0) &&
8142       isa<ConstantFPSDNode>(N1) &&
8143       isa<ConstantFPSDNode>(N2)) {
8144     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8145   }
8146
8147   if (Options.UnsafeFPMath) {
8148     if (N0CFP && N0CFP->isZero())
8149       return N2;
8150     if (N1CFP && N1CFP->isZero())
8151       return N2;
8152   }
8153   if (N0CFP && N0CFP->isExactlyValue(1.0))
8154     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8155   if (N1CFP && N1CFP->isExactlyValue(1.0))
8156     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8157
8158   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8159   if (N0CFP && !N1CFP)
8160     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8161
8162   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8163   if (Options.UnsafeFPMath && N1CFP &&
8164       N2.getOpcode() == ISD::FMUL &&
8165       N0 == N2.getOperand(0) &&
8166       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8167     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8168                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8169   }
8170
8171
8172   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8173   if (Options.UnsafeFPMath &&
8174       N0.getOpcode() == ISD::FMUL && N1CFP &&
8175       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8176     return DAG.getNode(ISD::FMA, dl, VT,
8177                        N0.getOperand(0),
8178                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8179                        N2);
8180   }
8181
8182   // (fma x, 1, y) -> (fadd x, y)
8183   // (fma x, -1, y) -> (fadd (fneg x), y)
8184   if (N1CFP) {
8185     if (N1CFP->isExactlyValue(1.0))
8186       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8187
8188     if (N1CFP->isExactlyValue(-1.0) &&
8189         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8190       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8191       AddToWorklist(RHSNeg.getNode());
8192       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8193     }
8194   }
8195
8196   // (fma x, c, x) -> (fmul x, (c+1))
8197   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8198     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8199                        DAG.getNode(ISD::FADD, dl, VT,
8200                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8201
8202   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8203   if (Options.UnsafeFPMath && N1CFP &&
8204       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8205     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8206                        DAG.getNode(ISD::FADD, dl, VT,
8207                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8208
8209
8210   return SDValue();
8211 }
8212
8213 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8214   SDValue N0 = N->getOperand(0);
8215   SDValue N1 = N->getOperand(1);
8216   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8217   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8218   EVT VT = N->getValueType(0);
8219   SDLoc DL(N);
8220   const TargetOptions &Options = DAG.getTarget().Options;
8221
8222   // fold vector ops
8223   if (VT.isVector())
8224     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8225       return FoldedVOp;
8226
8227   // fold (fdiv c1, c2) -> c1/c2
8228   if (N0CFP && N1CFP)
8229     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8230
8231   if (Options.UnsafeFPMath) {
8232     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8233     if (N1CFP) {
8234       // Compute the reciprocal 1.0 / c2.
8235       APFloat N1APF = N1CFP->getValueAPF();
8236       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8237       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8238       // Only do the transform if the reciprocal is a legal fp immediate that
8239       // isn't too nasty (eg NaN, denormal, ...).
8240       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8241           (!LegalOperations ||
8242            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8243            // backend)... we should handle this gracefully after Legalize.
8244            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8245            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8246            TLI.isFPImmLegal(Recip, VT)))
8247         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8248                            DAG.getConstantFP(Recip, DL, VT));
8249     }
8250
8251     // If this FDIV is part of a reciprocal square root, it may be folded
8252     // into a target-specific square root estimate instruction.
8253     if (N1.getOpcode() == ISD::FSQRT) {
8254       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8255         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8256       }
8257     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8258                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8259       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8260         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8261         AddToWorklist(RV.getNode());
8262         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8263       }
8264     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8265                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8266       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8267         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8268         AddToWorklist(RV.getNode());
8269         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8270       }
8271     } else if (N1.getOpcode() == ISD::FMUL) {
8272       // Look through an FMUL. Even though this won't remove the FDIV directly,
8273       // it's still worthwhile to get rid of the FSQRT if possible.
8274       SDValue SqrtOp;
8275       SDValue OtherOp;
8276       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8277         SqrtOp = N1.getOperand(0);
8278         OtherOp = N1.getOperand(1);
8279       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8280         SqrtOp = N1.getOperand(1);
8281         OtherOp = N1.getOperand(0);
8282       }
8283       if (SqrtOp.getNode()) {
8284         // We found a FSQRT, so try to make this fold:
8285         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8286         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8287           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8288           AddToWorklist(RV.getNode());
8289           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8290         }
8291       }
8292     }
8293
8294     // Fold into a reciprocal estimate and multiply instead of a real divide.
8295     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8296       AddToWorklist(RV.getNode());
8297       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8298     }
8299   }
8300
8301   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8302   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8303     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8304       // Both can be negated for free, check to see if at least one is cheaper
8305       // negated.
8306       if (LHSNeg == 2 || RHSNeg == 2)
8307         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8308                            GetNegatedExpression(N0, DAG, LegalOperations),
8309                            GetNegatedExpression(N1, DAG, LegalOperations));
8310     }
8311   }
8312
8313   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8314   // reciprocal.
8315   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8316   // Notice that this is not always beneficial. One reason is different target
8317   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8318   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8319   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8320   if (Options.UnsafeFPMath) {
8321     // Skip if current node is a reciprocal.
8322     if (N0CFP && N0CFP->isExactlyValue(1.0))
8323       return SDValue();
8324
8325     SmallVector<SDNode *, 4> Users;
8326     // Find all FDIV users of the same divisor.
8327     for (auto *U : N1->uses()) {
8328       if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8329         Users.push_back(U);
8330     }
8331
8332     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8333       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8334       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8335
8336       // Dividend / Divisor -> Dividend * Reciprocal
8337       for (auto *U : Users) {
8338         SDValue Dividend = U->getOperand(0);
8339         if (Dividend != FPOne) {
8340           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8341                                         Reciprocal);
8342           DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8343         }
8344       }
8345       return SDValue();
8346     }
8347   }
8348
8349   return SDValue();
8350 }
8351
8352 SDValue DAGCombiner::visitFREM(SDNode *N) {
8353   SDValue N0 = N->getOperand(0);
8354   SDValue N1 = N->getOperand(1);
8355   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8356   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8357   EVT VT = N->getValueType(0);
8358
8359   // fold (frem c1, c2) -> fmod(c1,c2)
8360   if (N0CFP && N1CFP)
8361     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8362
8363   return SDValue();
8364 }
8365
8366 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8367   if (DAG.getTarget().Options.UnsafeFPMath &&
8368       !TLI.isFsqrtCheap()) {
8369     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8370     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8371       EVT VT = RV.getValueType();
8372       SDLoc DL(N);
8373       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8374       AddToWorklist(RV.getNode());
8375
8376       // Unfortunately, RV is now NaN if the input was exactly 0.
8377       // Select out this case and force the answer to 0.
8378       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8379       SDValue ZeroCmp =
8380         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8381                      N->getOperand(0), Zero, ISD::SETEQ);
8382       AddToWorklist(ZeroCmp.getNode());
8383       AddToWorklist(RV.getNode());
8384
8385       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8386                        DL, VT, ZeroCmp, Zero, RV);
8387       return RV;
8388     }
8389   }
8390   return SDValue();
8391 }
8392
8393 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8394   SDValue N0 = N->getOperand(0);
8395   SDValue N1 = N->getOperand(1);
8396   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8397   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8398   EVT VT = N->getValueType(0);
8399
8400   if (N0CFP && N1CFP)  // Constant fold
8401     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8402
8403   if (N1CFP) {
8404     const APFloat& V = N1CFP->getValueAPF();
8405     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8406     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8407     if (!V.isNegative()) {
8408       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8409         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8410     } else {
8411       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8412         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8413                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8414     }
8415   }
8416
8417   // copysign(fabs(x), y) -> copysign(x, y)
8418   // copysign(fneg(x), y) -> copysign(x, y)
8419   // copysign(copysign(x,z), y) -> copysign(x, y)
8420   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8421       N0.getOpcode() == ISD::FCOPYSIGN)
8422     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8423                        N0.getOperand(0), N1);
8424
8425   // copysign(x, abs(y)) -> abs(x)
8426   if (N1.getOpcode() == ISD::FABS)
8427     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8428
8429   // copysign(x, copysign(y,z)) -> copysign(x, z)
8430   if (N1.getOpcode() == ISD::FCOPYSIGN)
8431     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8432                        N0, N1.getOperand(1));
8433
8434   // copysign(x, fp_extend(y)) -> copysign(x, y)
8435   // copysign(x, fp_round(y)) -> copysign(x, y)
8436   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8437     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8438                        N0, N1.getOperand(0));
8439
8440   return SDValue();
8441 }
8442
8443 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8444   SDValue N0 = N->getOperand(0);
8445   EVT VT = N->getValueType(0);
8446   EVT OpVT = N0.getValueType();
8447
8448   // fold (sint_to_fp c1) -> c1fp
8449   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8450       // ...but only if the target supports immediate floating-point values
8451       (!LegalOperations ||
8452        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8453     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8454
8455   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8456   // but UINT_TO_FP is legal on this target, try to convert.
8457   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8458       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8459     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8460     if (DAG.SignBitIsZero(N0))
8461       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8462   }
8463
8464   // The next optimizations are desirable only if SELECT_CC can be lowered.
8465   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8466     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8467     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8468         !VT.isVector() &&
8469         (!LegalOperations ||
8470          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8471       SDLoc DL(N);
8472       SDValue Ops[] =
8473         { N0.getOperand(0), N0.getOperand(1),
8474           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8475           N0.getOperand(2) };
8476       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8477     }
8478
8479     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8480     //      (select_cc x, y, 1.0, 0.0,, cc)
8481     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8482         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8483         (!LegalOperations ||
8484          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8485       SDLoc DL(N);
8486       SDValue Ops[] =
8487         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8488           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8489           N0.getOperand(0).getOperand(2) };
8490       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8491     }
8492   }
8493
8494   return SDValue();
8495 }
8496
8497 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8498   SDValue N0 = N->getOperand(0);
8499   EVT VT = N->getValueType(0);
8500   EVT OpVT = N0.getValueType();
8501
8502   // fold (uint_to_fp c1) -> c1fp
8503   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8504       // ...but only if the target supports immediate floating-point values
8505       (!LegalOperations ||
8506        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8507     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8508
8509   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8510   // but SINT_TO_FP is legal on this target, try to convert.
8511   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8512       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8513     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8514     if (DAG.SignBitIsZero(N0))
8515       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8516   }
8517
8518   // The next optimizations are desirable only if SELECT_CC can be lowered.
8519   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8520     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8521
8522     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8523         (!LegalOperations ||
8524          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8525       SDLoc DL(N);
8526       SDValue Ops[] =
8527         { N0.getOperand(0), N0.getOperand(1),
8528           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8529           N0.getOperand(2) };
8530       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8531     }
8532   }
8533
8534   return SDValue();
8535 }
8536
8537 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8538 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8539   SDValue N0 = N->getOperand(0);
8540   EVT VT = N->getValueType(0);
8541
8542   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8543     return SDValue();
8544
8545   SDValue Src = N0.getOperand(0);
8546   EVT SrcVT = Src.getValueType();
8547   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8548   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8549
8550   // We can safely assume the conversion won't overflow the output range,
8551   // because (for example) (uint8_t)18293.f is undefined behavior.
8552
8553   // Since we can assume the conversion won't overflow, our decision as to
8554   // whether the input will fit in the float should depend on the minimum
8555   // of the input range and output range.
8556
8557   // This means this is also safe for a signed input and unsigned output, since
8558   // a negative input would lead to undefined behavior.
8559   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8560   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8561   unsigned ActualSize = std::min(InputSize, OutputSize);
8562   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8563
8564   // We can only fold away the float conversion if the input range can be
8565   // represented exactly in the float range.
8566   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8567     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8568       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8569                                                        : ISD::ZERO_EXTEND;
8570       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8571     }
8572     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8573       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8574     if (SrcVT == VT)
8575       return Src;
8576     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8577   }
8578   return SDValue();
8579 }
8580
8581 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8582   SDValue N0 = N->getOperand(0);
8583   EVT VT = N->getValueType(0);
8584
8585   // fold (fp_to_sint c1fp) -> c1
8586   if (isConstantFPBuildVectorOrConstantFP(N0))
8587     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8588
8589   return FoldIntToFPToInt(N, DAG);
8590 }
8591
8592 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8593   SDValue N0 = N->getOperand(0);
8594   EVT VT = N->getValueType(0);
8595
8596   // fold (fp_to_uint c1fp) -> c1
8597   if (isConstantFPBuildVectorOrConstantFP(N0))
8598     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8599
8600   return FoldIntToFPToInt(N, DAG);
8601 }
8602
8603 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8604   SDValue N0 = N->getOperand(0);
8605   SDValue N1 = N->getOperand(1);
8606   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8607   EVT VT = N->getValueType(0);
8608
8609   // fold (fp_round c1fp) -> c1fp
8610   if (N0CFP)
8611     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8612
8613   // fold (fp_round (fp_extend x)) -> x
8614   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8615     return N0.getOperand(0);
8616
8617   // fold (fp_round (fp_round x)) -> (fp_round x)
8618   if (N0.getOpcode() == ISD::FP_ROUND) {
8619     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8620     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8621     // If the first fp_round isn't a value preserving truncation, it might
8622     // introduce a tie in the second fp_round, that wouldn't occur in the
8623     // single-step fp_round we want to fold to.
8624     // In other words, double rounding isn't the same as rounding.
8625     // Also, this is a value preserving truncation iff both fp_round's are.
8626     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8627       SDLoc DL(N);
8628       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8629                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8630     }
8631   }
8632
8633   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8634   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8635     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8636                               N0.getOperand(0), N1);
8637     AddToWorklist(Tmp.getNode());
8638     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8639                        Tmp, N0.getOperand(1));
8640   }
8641
8642   return SDValue();
8643 }
8644
8645 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8646   SDValue N0 = N->getOperand(0);
8647   EVT VT = N->getValueType(0);
8648   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8649   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8650
8651   // fold (fp_round_inreg c1fp) -> c1fp
8652   if (N0CFP && isTypeLegal(EVT)) {
8653     SDLoc DL(N);
8654     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8655     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8656   }
8657
8658   return SDValue();
8659 }
8660
8661 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8662   SDValue N0 = N->getOperand(0);
8663   EVT VT = N->getValueType(0);
8664
8665   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8666   if (N->hasOneUse() &&
8667       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8668     return SDValue();
8669
8670   // fold (fp_extend c1fp) -> c1fp
8671   if (isConstantFPBuildVectorOrConstantFP(N0))
8672     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8673
8674   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8675   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8676       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8677     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8678
8679   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8680   // value of X.
8681   if (N0.getOpcode() == ISD::FP_ROUND
8682       && N0.getNode()->getConstantOperandVal(1) == 1) {
8683     SDValue In = N0.getOperand(0);
8684     if (In.getValueType() == VT) return In;
8685     if (VT.bitsLT(In.getValueType()))
8686       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8687                          In, N0.getOperand(1));
8688     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8689   }
8690
8691   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8692   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8693        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8694     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8695     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8696                                      LN0->getChain(),
8697                                      LN0->getBasePtr(), N0.getValueType(),
8698                                      LN0->getMemOperand());
8699     CombineTo(N, ExtLoad);
8700     CombineTo(N0.getNode(),
8701               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8702                           N0.getValueType(), ExtLoad,
8703                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8704               ExtLoad.getValue(1));
8705     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8706   }
8707
8708   return SDValue();
8709 }
8710
8711 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8712   SDValue N0 = N->getOperand(0);
8713   EVT VT = N->getValueType(0);
8714
8715   // fold (fceil c1) -> fceil(c1)
8716   if (isConstantFPBuildVectorOrConstantFP(N0))
8717     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8718
8719   return SDValue();
8720 }
8721
8722 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8723   SDValue N0 = N->getOperand(0);
8724   EVT VT = N->getValueType(0);
8725
8726   // fold (ftrunc c1) -> ftrunc(c1)
8727   if (isConstantFPBuildVectorOrConstantFP(N0))
8728     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8729
8730   return SDValue();
8731 }
8732
8733 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8734   SDValue N0 = N->getOperand(0);
8735   EVT VT = N->getValueType(0);
8736
8737   // fold (ffloor c1) -> ffloor(c1)
8738   if (isConstantFPBuildVectorOrConstantFP(N0))
8739     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8740
8741   return SDValue();
8742 }
8743
8744 // FIXME: FNEG and FABS have a lot in common; refactor.
8745 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8746   SDValue N0 = N->getOperand(0);
8747   EVT VT = N->getValueType(0);
8748
8749   // Constant fold FNEG.
8750   if (isConstantFPBuildVectorOrConstantFP(N0))
8751     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8752
8753   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8754                          &DAG.getTarget().Options))
8755     return GetNegatedExpression(N0, DAG, LegalOperations);
8756
8757   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8758   // constant pool values.
8759   if (!TLI.isFNegFree(VT) &&
8760       N0.getOpcode() == ISD::BITCAST &&
8761       N0.getNode()->hasOneUse()) {
8762     SDValue Int = N0.getOperand(0);
8763     EVT IntVT = Int.getValueType();
8764     if (IntVT.isInteger() && !IntVT.isVector()) {
8765       APInt SignMask;
8766       if (N0.getValueType().isVector()) {
8767         // For a vector, get a mask such as 0x80... per scalar element
8768         // and splat it.
8769         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8770         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8771       } else {
8772         // For a scalar, just generate 0x80...
8773         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8774       }
8775       SDLoc DL0(N0);
8776       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8777                         DAG.getConstant(SignMask, DL0, IntVT));
8778       AddToWorklist(Int.getNode());
8779       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8780     }
8781   }
8782
8783   // (fneg (fmul c, x)) -> (fmul -c, x)
8784   if (N0.getOpcode() == ISD::FMUL) {
8785     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8786     if (CFP1) {
8787       APFloat CVal = CFP1->getValueAPF();
8788       CVal.changeSign();
8789       if (Level >= AfterLegalizeDAG &&
8790           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8791            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8792         return DAG.getNode(
8793             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8794             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8795     }
8796   }
8797
8798   return SDValue();
8799 }
8800
8801 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8802   SDValue N0 = N->getOperand(0);
8803   SDValue N1 = N->getOperand(1);
8804   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8805   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8806
8807   if (N0CFP && N1CFP) {
8808     const APFloat &C0 = N0CFP->getValueAPF();
8809     const APFloat &C1 = N1CFP->getValueAPF();
8810     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8811   }
8812
8813   if (N0CFP) {
8814     EVT VT = N->getValueType(0);
8815     // Canonicalize to constant on RHS.
8816     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8817   }
8818
8819   return SDValue();
8820 }
8821
8822 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8823   SDValue N0 = N->getOperand(0);
8824   SDValue N1 = N->getOperand(1);
8825   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8826   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8827
8828   if (N0CFP && N1CFP) {
8829     const APFloat &C0 = N0CFP->getValueAPF();
8830     const APFloat &C1 = N1CFP->getValueAPF();
8831     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8832   }
8833
8834   if (N0CFP) {
8835     EVT VT = N->getValueType(0);
8836     // Canonicalize to constant on RHS.
8837     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8838   }
8839
8840   return SDValue();
8841 }
8842
8843 SDValue DAGCombiner::visitFABS(SDNode *N) {
8844   SDValue N0 = N->getOperand(0);
8845   EVT VT = N->getValueType(0);
8846
8847   // fold (fabs c1) -> fabs(c1)
8848   if (isConstantFPBuildVectorOrConstantFP(N0))
8849     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8850
8851   // fold (fabs (fabs x)) -> (fabs x)
8852   if (N0.getOpcode() == ISD::FABS)
8853     return N->getOperand(0);
8854
8855   // fold (fabs (fneg x)) -> (fabs x)
8856   // fold (fabs (fcopysign x, y)) -> (fabs x)
8857   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8858     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8859
8860   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8861   // constant pool values.
8862   if (!TLI.isFAbsFree(VT) &&
8863       N0.getOpcode() == ISD::BITCAST &&
8864       N0.getNode()->hasOneUse()) {
8865     SDValue Int = N0.getOperand(0);
8866     EVT IntVT = Int.getValueType();
8867     if (IntVT.isInteger() && !IntVT.isVector()) {
8868       APInt SignMask;
8869       if (N0.getValueType().isVector()) {
8870         // For a vector, get a mask such as 0x7f... per scalar element
8871         // and splat it.
8872         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8873         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8874       } else {
8875         // For a scalar, just generate 0x7f...
8876         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8877       }
8878       SDLoc DL(N0);
8879       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8880                         DAG.getConstant(SignMask, DL, IntVT));
8881       AddToWorklist(Int.getNode());
8882       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8883     }
8884   }
8885
8886   return SDValue();
8887 }
8888
8889 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8890   SDValue Chain = N->getOperand(0);
8891   SDValue N1 = N->getOperand(1);
8892   SDValue N2 = N->getOperand(2);
8893
8894   // If N is a constant we could fold this into a fallthrough or unconditional
8895   // branch. However that doesn't happen very often in normal code, because
8896   // Instcombine/SimplifyCFG should have handled the available opportunities.
8897   // If we did this folding here, it would be necessary to update the
8898   // MachineBasicBlock CFG, which is awkward.
8899
8900   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8901   // on the target.
8902   if (N1.getOpcode() == ISD::SETCC &&
8903       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8904                                    N1.getOperand(0).getValueType())) {
8905     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8906                        Chain, N1.getOperand(2),
8907                        N1.getOperand(0), N1.getOperand(1), N2);
8908   }
8909
8910   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8911       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8912        (N1.getOperand(0).hasOneUse() &&
8913         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8914     SDNode *Trunc = nullptr;
8915     if (N1.getOpcode() == ISD::TRUNCATE) {
8916       // Look pass the truncate.
8917       Trunc = N1.getNode();
8918       N1 = N1.getOperand(0);
8919     }
8920
8921     // Match this pattern so that we can generate simpler code:
8922     //
8923     //   %a = ...
8924     //   %b = and i32 %a, 2
8925     //   %c = srl i32 %b, 1
8926     //   brcond i32 %c ...
8927     //
8928     // into
8929     //
8930     //   %a = ...
8931     //   %b = and i32 %a, 2
8932     //   %c = setcc eq %b, 0
8933     //   brcond %c ...
8934     //
8935     // This applies only when the AND constant value has one bit set and the
8936     // SRL constant is equal to the log2 of the AND constant. The back-end is
8937     // smart enough to convert the result into a TEST/JMP sequence.
8938     SDValue Op0 = N1.getOperand(0);
8939     SDValue Op1 = N1.getOperand(1);
8940
8941     if (Op0.getOpcode() == ISD::AND &&
8942         Op1.getOpcode() == ISD::Constant) {
8943       SDValue AndOp1 = Op0.getOperand(1);
8944
8945       if (AndOp1.getOpcode() == ISD::Constant) {
8946         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8947
8948         if (AndConst.isPowerOf2() &&
8949             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8950           SDLoc DL(N);
8951           SDValue SetCC =
8952             DAG.getSetCC(DL,
8953                          getSetCCResultType(Op0.getValueType()),
8954                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8955                          ISD::SETNE);
8956
8957           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8958                                           MVT::Other, Chain, SetCC, N2);
8959           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8960           // will convert it back to (X & C1) >> C2.
8961           CombineTo(N, NewBRCond, false);
8962           // Truncate is dead.
8963           if (Trunc)
8964             deleteAndRecombine(Trunc);
8965           // Replace the uses of SRL with SETCC
8966           WorklistRemover DeadNodes(*this);
8967           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8968           deleteAndRecombine(N1.getNode());
8969           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8970         }
8971       }
8972     }
8973
8974     if (Trunc)
8975       // Restore N1 if the above transformation doesn't match.
8976       N1 = N->getOperand(1);
8977   }
8978
8979   // Transform br(xor(x, y)) -> br(x != y)
8980   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8981   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8982     SDNode *TheXor = N1.getNode();
8983     SDValue Op0 = TheXor->getOperand(0);
8984     SDValue Op1 = TheXor->getOperand(1);
8985     if (Op0.getOpcode() == Op1.getOpcode()) {
8986       // Avoid missing important xor optimizations.
8987       SDValue Tmp = visitXOR(TheXor);
8988       if (Tmp.getNode()) {
8989         if (Tmp.getNode() != TheXor) {
8990           DEBUG(dbgs() << "\nReplacing.8 ";
8991                 TheXor->dump(&DAG);
8992                 dbgs() << "\nWith: ";
8993                 Tmp.getNode()->dump(&DAG);
8994                 dbgs() << '\n');
8995           WorklistRemover DeadNodes(*this);
8996           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8997           deleteAndRecombine(TheXor);
8998           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8999                              MVT::Other, Chain, Tmp, N2);
9000         }
9001
9002         // visitXOR has changed XOR's operands or replaced the XOR completely,
9003         // bail out.
9004         return SDValue(N, 0);
9005       }
9006     }
9007
9008     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9009       bool Equal = false;
9010       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9011           Op0.getOpcode() == ISD::XOR) {
9012         TheXor = Op0.getNode();
9013         Equal = true;
9014       }
9015
9016       EVT SetCCVT = N1.getValueType();
9017       if (LegalTypes)
9018         SetCCVT = getSetCCResultType(SetCCVT);
9019       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9020                                    SetCCVT,
9021                                    Op0, Op1,
9022                                    Equal ? ISD::SETEQ : ISD::SETNE);
9023       // Replace the uses of XOR with SETCC
9024       WorklistRemover DeadNodes(*this);
9025       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9026       deleteAndRecombine(N1.getNode());
9027       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9028                          MVT::Other, Chain, SetCC, N2);
9029     }
9030   }
9031
9032   return SDValue();
9033 }
9034
9035 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9036 //
9037 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9038   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9039   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9040
9041   // If N is a constant we could fold this into a fallthrough or unconditional
9042   // branch. However that doesn't happen very often in normal code, because
9043   // Instcombine/SimplifyCFG should have handled the available opportunities.
9044   // If we did this folding here, it would be necessary to update the
9045   // MachineBasicBlock CFG, which is awkward.
9046
9047   // Use SimplifySetCC to simplify SETCC's.
9048   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9049                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9050                                false);
9051   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9052
9053   // fold to a simpler setcc
9054   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9055     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9056                        N->getOperand(0), Simp.getOperand(2),
9057                        Simp.getOperand(0), Simp.getOperand(1),
9058                        N->getOperand(4));
9059
9060   return SDValue();
9061 }
9062
9063 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9064 /// and that N may be folded in the load / store addressing mode.
9065 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9066                                     SelectionDAG &DAG,
9067                                     const TargetLowering &TLI) {
9068   EVT VT;
9069   unsigned AS;
9070
9071   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9072     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9073       return false;
9074     VT = LD->getMemoryVT();
9075     AS = LD->getAddressSpace();
9076   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9077     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9078       return false;
9079     VT = ST->getMemoryVT();
9080     AS = ST->getAddressSpace();
9081   } else
9082     return false;
9083
9084   TargetLowering::AddrMode AM;
9085   if (N->getOpcode() == ISD::ADD) {
9086     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9087     if (Offset)
9088       // [reg +/- imm]
9089       AM.BaseOffs = Offset->getSExtValue();
9090     else
9091       // [reg +/- reg]
9092       AM.Scale = 1;
9093   } else if (N->getOpcode() == ISD::SUB) {
9094     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9095     if (Offset)
9096       // [reg +/- imm]
9097       AM.BaseOffs = -Offset->getSExtValue();
9098     else
9099       // [reg +/- reg]
9100       AM.Scale = 1;
9101   } else
9102     return false;
9103
9104   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()), AS);
9105 }
9106
9107 /// Try turning a load/store into a pre-indexed load/store when the base
9108 /// pointer is an add or subtract and it has other uses besides the load/store.
9109 /// After the transformation, the new indexed load/store has effectively folded
9110 /// the add/subtract in and all of its other uses are redirected to the
9111 /// new load/store.
9112 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9113   if (Level < AfterLegalizeDAG)
9114     return false;
9115
9116   bool isLoad = true;
9117   SDValue Ptr;
9118   EVT VT;
9119   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9120     if (LD->isIndexed())
9121       return false;
9122     VT = LD->getMemoryVT();
9123     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9124         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9125       return false;
9126     Ptr = LD->getBasePtr();
9127   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9128     if (ST->isIndexed())
9129       return false;
9130     VT = ST->getMemoryVT();
9131     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9132         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9133       return false;
9134     Ptr = ST->getBasePtr();
9135     isLoad = false;
9136   } else {
9137     return false;
9138   }
9139
9140   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9141   // out.  There is no reason to make this a preinc/predec.
9142   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9143       Ptr.getNode()->hasOneUse())
9144     return false;
9145
9146   // Ask the target to do addressing mode selection.
9147   SDValue BasePtr;
9148   SDValue Offset;
9149   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9150   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9151     return false;
9152
9153   // Backends without true r+i pre-indexed forms may need to pass a
9154   // constant base with a variable offset so that constant coercion
9155   // will work with the patterns in canonical form.
9156   bool Swapped = false;
9157   if (isa<ConstantSDNode>(BasePtr)) {
9158     std::swap(BasePtr, Offset);
9159     Swapped = true;
9160   }
9161
9162   // Don't create a indexed load / store with zero offset.
9163   if (isNullConstant(Offset))
9164     return false;
9165
9166   // Try turning it into a pre-indexed load / store except when:
9167   // 1) The new base ptr is a frame index.
9168   // 2) If N is a store and the new base ptr is either the same as or is a
9169   //    predecessor of the value being stored.
9170   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9171   //    that would create a cycle.
9172   // 4) All uses are load / store ops that use it as old base ptr.
9173
9174   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9175   // (plus the implicit offset) to a register to preinc anyway.
9176   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9177     return false;
9178
9179   // Check #2.
9180   if (!isLoad) {
9181     SDValue Val = cast<StoreSDNode>(N)->getValue();
9182     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9183       return false;
9184   }
9185
9186   // If the offset is a constant, there may be other adds of constants that
9187   // can be folded with this one. We should do this to avoid having to keep
9188   // a copy of the original base pointer.
9189   SmallVector<SDNode *, 16> OtherUses;
9190   if (isa<ConstantSDNode>(Offset))
9191     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9192                               UE = BasePtr.getNode()->use_end();
9193          UI != UE; ++UI) {
9194       SDUse &Use = UI.getUse();
9195       // Skip the use that is Ptr and uses of other results from BasePtr's
9196       // node (important for nodes that return multiple results).
9197       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9198         continue;
9199
9200       if (Use.getUser()->isPredecessorOf(N))
9201         continue;
9202
9203       if (Use.getUser()->getOpcode() != ISD::ADD &&
9204           Use.getUser()->getOpcode() != ISD::SUB) {
9205         OtherUses.clear();
9206         break;
9207       }
9208
9209       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9210       if (!isa<ConstantSDNode>(Op1)) {
9211         OtherUses.clear();
9212         break;
9213       }
9214
9215       // FIXME: In some cases, we can be smarter about this.
9216       if (Op1.getValueType() != Offset.getValueType()) {
9217         OtherUses.clear();
9218         break;
9219       }
9220
9221       OtherUses.push_back(Use.getUser());
9222     }
9223
9224   if (Swapped)
9225     std::swap(BasePtr, Offset);
9226
9227   // Now check for #3 and #4.
9228   bool RealUse = false;
9229
9230   // Caches for hasPredecessorHelper
9231   SmallPtrSet<const SDNode *, 32> Visited;
9232   SmallVector<const SDNode *, 16> Worklist;
9233
9234   for (SDNode *Use : Ptr.getNode()->uses()) {
9235     if (Use == N)
9236       continue;
9237     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9238       return false;
9239
9240     // If Ptr may be folded in addressing mode of other use, then it's
9241     // not profitable to do this transformation.
9242     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9243       RealUse = true;
9244   }
9245
9246   if (!RealUse)
9247     return false;
9248
9249   SDValue Result;
9250   if (isLoad)
9251     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9252                                 BasePtr, Offset, AM);
9253   else
9254     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9255                                  BasePtr, Offset, AM);
9256   ++PreIndexedNodes;
9257   ++NodesCombined;
9258   DEBUG(dbgs() << "\nReplacing.4 ";
9259         N->dump(&DAG);
9260         dbgs() << "\nWith: ";
9261         Result.getNode()->dump(&DAG);
9262         dbgs() << '\n');
9263   WorklistRemover DeadNodes(*this);
9264   if (isLoad) {
9265     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9266     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9267   } else {
9268     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9269   }
9270
9271   // Finally, since the node is now dead, remove it from the graph.
9272   deleteAndRecombine(N);
9273
9274   if (Swapped)
9275     std::swap(BasePtr, Offset);
9276
9277   // Replace other uses of BasePtr that can be updated to use Ptr
9278   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9279     unsigned OffsetIdx = 1;
9280     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9281       OffsetIdx = 0;
9282     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9283            BasePtr.getNode() && "Expected BasePtr operand");
9284
9285     // We need to replace ptr0 in the following expression:
9286     //   x0 * offset0 + y0 * ptr0 = t0
9287     // knowing that
9288     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9289     //
9290     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9291     // indexed load/store and the expresion that needs to be re-written.
9292     //
9293     // Therefore, we have:
9294     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9295
9296     ConstantSDNode *CN =
9297       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9298     int X0, X1, Y0, Y1;
9299     APInt Offset0 = CN->getAPIntValue();
9300     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9301
9302     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9303     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9304     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9305     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9306
9307     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9308
9309     APInt CNV = Offset0;
9310     if (X0 < 0) CNV = -CNV;
9311     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9312     else CNV = CNV - Offset1;
9313
9314     SDLoc DL(OtherUses[i]);
9315
9316     // We can now generate the new expression.
9317     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9318     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9319
9320     SDValue NewUse = DAG.getNode(Opcode,
9321                                  DL,
9322                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9323     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9324     deleteAndRecombine(OtherUses[i]);
9325   }
9326
9327   // Replace the uses of Ptr with uses of the updated base value.
9328   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9329   deleteAndRecombine(Ptr.getNode());
9330
9331   return true;
9332 }
9333
9334 /// Try to combine a load/store with a add/sub of the base pointer node into a
9335 /// post-indexed load/store. The transformation folded the add/subtract into the
9336 /// new indexed load/store effectively and all of its uses are redirected to the
9337 /// new load/store.
9338 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9339   if (Level < AfterLegalizeDAG)
9340     return false;
9341
9342   bool isLoad = true;
9343   SDValue Ptr;
9344   EVT VT;
9345   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9346     if (LD->isIndexed())
9347       return false;
9348     VT = LD->getMemoryVT();
9349     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9350         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9351       return false;
9352     Ptr = LD->getBasePtr();
9353   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9354     if (ST->isIndexed())
9355       return false;
9356     VT = ST->getMemoryVT();
9357     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9358         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9359       return false;
9360     Ptr = ST->getBasePtr();
9361     isLoad = false;
9362   } else {
9363     return false;
9364   }
9365
9366   if (Ptr.getNode()->hasOneUse())
9367     return false;
9368
9369   for (SDNode *Op : Ptr.getNode()->uses()) {
9370     if (Op == N ||
9371         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9372       continue;
9373
9374     SDValue BasePtr;
9375     SDValue Offset;
9376     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9377     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9378       // Don't create a indexed load / store with zero offset.
9379       if (isNullConstant(Offset))
9380         continue;
9381
9382       // Try turning it into a post-indexed load / store except when
9383       // 1) All uses are load / store ops that use it as base ptr (and
9384       //    it may be folded as addressing mmode).
9385       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9386       //    nor a successor of N. Otherwise, if Op is folded that would
9387       //    create a cycle.
9388
9389       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9390         continue;
9391
9392       // Check for #1.
9393       bool TryNext = false;
9394       for (SDNode *Use : BasePtr.getNode()->uses()) {
9395         if (Use == Ptr.getNode())
9396           continue;
9397
9398         // If all the uses are load / store addresses, then don't do the
9399         // transformation.
9400         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9401           bool RealUse = false;
9402           for (SDNode *UseUse : Use->uses()) {
9403             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9404               RealUse = true;
9405           }
9406
9407           if (!RealUse) {
9408             TryNext = true;
9409             break;
9410           }
9411         }
9412       }
9413
9414       if (TryNext)
9415         continue;
9416
9417       // Check for #2
9418       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9419         SDValue Result = isLoad
9420           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9421                                BasePtr, Offset, AM)
9422           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9423                                 BasePtr, Offset, AM);
9424         ++PostIndexedNodes;
9425         ++NodesCombined;
9426         DEBUG(dbgs() << "\nReplacing.5 ";
9427               N->dump(&DAG);
9428               dbgs() << "\nWith: ";
9429               Result.getNode()->dump(&DAG);
9430               dbgs() << '\n');
9431         WorklistRemover DeadNodes(*this);
9432         if (isLoad) {
9433           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9434           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9435         } else {
9436           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9437         }
9438
9439         // Finally, since the node is now dead, remove it from the graph.
9440         deleteAndRecombine(N);
9441
9442         // Replace the uses of Use with uses of the updated base value.
9443         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9444                                       Result.getValue(isLoad ? 1 : 0));
9445         deleteAndRecombine(Op);
9446         return true;
9447       }
9448     }
9449   }
9450
9451   return false;
9452 }
9453
9454 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9455 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9456   ISD::MemIndexedMode AM = LD->getAddressingMode();
9457   assert(AM != ISD::UNINDEXED);
9458   SDValue BP = LD->getOperand(1);
9459   SDValue Inc = LD->getOperand(2);
9460
9461   // Some backends use TargetConstants for load offsets, but don't expect
9462   // TargetConstants in general ADD nodes. We can convert these constants into
9463   // regular Constants (if the constant is not opaque).
9464   assert((Inc.getOpcode() != ISD::TargetConstant ||
9465           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9466          "Cannot split out indexing using opaque target constants");
9467   if (Inc.getOpcode() == ISD::TargetConstant) {
9468     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9469     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9470                           ConstInc->getValueType(0));
9471   }
9472
9473   unsigned Opc =
9474       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9475   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9476 }
9477
9478 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9479   LoadSDNode *LD  = cast<LoadSDNode>(N);
9480   SDValue Chain = LD->getChain();
9481   SDValue Ptr   = LD->getBasePtr();
9482
9483   // If load is not volatile and there are no uses of the loaded value (and
9484   // the updated indexed value in case of indexed loads), change uses of the
9485   // chain value into uses of the chain input (i.e. delete the dead load).
9486   if (!LD->isVolatile()) {
9487     if (N->getValueType(1) == MVT::Other) {
9488       // Unindexed loads.
9489       if (!N->hasAnyUseOfValue(0)) {
9490         // It's not safe to use the two value CombineTo variant here. e.g.
9491         // v1, chain2 = load chain1, loc
9492         // v2, chain3 = load chain2, loc
9493         // v3         = add v2, c
9494         // Now we replace use of chain2 with chain1.  This makes the second load
9495         // isomorphic to the one we are deleting, and thus makes this load live.
9496         DEBUG(dbgs() << "\nReplacing.6 ";
9497               N->dump(&DAG);
9498               dbgs() << "\nWith chain: ";
9499               Chain.getNode()->dump(&DAG);
9500               dbgs() << "\n");
9501         WorklistRemover DeadNodes(*this);
9502         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9503
9504         if (N->use_empty())
9505           deleteAndRecombine(N);
9506
9507         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9508       }
9509     } else {
9510       // Indexed loads.
9511       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9512
9513       // If this load has an opaque TargetConstant offset, then we cannot split
9514       // the indexing into an add/sub directly (that TargetConstant may not be
9515       // valid for a different type of node, and we cannot convert an opaque
9516       // target constant into a regular constant).
9517       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9518                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9519
9520       if (!N->hasAnyUseOfValue(0) &&
9521           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9522         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9523         SDValue Index;
9524         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9525           Index = SplitIndexingFromLoad(LD);
9526           // Try to fold the base pointer arithmetic into subsequent loads and
9527           // stores.
9528           AddUsersToWorklist(N);
9529         } else
9530           Index = DAG.getUNDEF(N->getValueType(1));
9531         DEBUG(dbgs() << "\nReplacing.7 ";
9532               N->dump(&DAG);
9533               dbgs() << "\nWith: ";
9534               Undef.getNode()->dump(&DAG);
9535               dbgs() << " and 2 other values\n");
9536         WorklistRemover DeadNodes(*this);
9537         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9538         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9539         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9540         deleteAndRecombine(N);
9541         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9542       }
9543     }
9544   }
9545
9546   // If this load is directly stored, replace the load value with the stored
9547   // value.
9548   // TODO: Handle store large -> read small portion.
9549   // TODO: Handle TRUNCSTORE/LOADEXT
9550   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9551     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9552       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9553       if (PrevST->getBasePtr() == Ptr &&
9554           PrevST->getValue().getValueType() == N->getValueType(0))
9555       return CombineTo(N, Chain.getOperand(1), Chain);
9556     }
9557   }
9558
9559   // Try to infer better alignment information than the load already has.
9560   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9561     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9562       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9563         SDValue NewLoad =
9564                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9565                               LD->getValueType(0),
9566                               Chain, Ptr, LD->getPointerInfo(),
9567                               LD->getMemoryVT(),
9568                               LD->isVolatile(), LD->isNonTemporal(),
9569                               LD->isInvariant(), Align, LD->getAAInfo());
9570         if (NewLoad.getNode() != N)
9571           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9572       }
9573     }
9574   }
9575
9576   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9577                                                   : DAG.getSubtarget().useAA();
9578 #ifndef NDEBUG
9579   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9580       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9581     UseAA = false;
9582 #endif
9583   if (UseAA && LD->isUnindexed()) {
9584     // Walk up chain skipping non-aliasing memory nodes.
9585     SDValue BetterChain = FindBetterChain(N, Chain);
9586
9587     // If there is a better chain.
9588     if (Chain != BetterChain) {
9589       SDValue ReplLoad;
9590
9591       // Replace the chain to void dependency.
9592       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9593         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9594                                BetterChain, Ptr, LD->getMemOperand());
9595       } else {
9596         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9597                                   LD->getValueType(0),
9598                                   BetterChain, Ptr, LD->getMemoryVT(),
9599                                   LD->getMemOperand());
9600       }
9601
9602       // Create token factor to keep old chain connected.
9603       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9604                                   MVT::Other, Chain, ReplLoad.getValue(1));
9605
9606       // Make sure the new and old chains are cleaned up.
9607       AddToWorklist(Token.getNode());
9608
9609       // Replace uses with load result and token factor. Don't add users
9610       // to work list.
9611       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9612     }
9613   }
9614
9615   // Try transforming N to an indexed load.
9616   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9617     return SDValue(N, 0);
9618
9619   // Try to slice up N to more direct loads if the slices are mapped to
9620   // different register banks or pairing can take place.
9621   if (SliceUpLoad(N))
9622     return SDValue(N, 0);
9623
9624   return SDValue();
9625 }
9626
9627 namespace {
9628 /// \brief Helper structure used to slice a load in smaller loads.
9629 /// Basically a slice is obtained from the following sequence:
9630 /// Origin = load Ty1, Base
9631 /// Shift = srl Ty1 Origin, CstTy Amount
9632 /// Inst = trunc Shift to Ty2
9633 ///
9634 /// Then, it will be rewriten into:
9635 /// Slice = load SliceTy, Base + SliceOffset
9636 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9637 ///
9638 /// SliceTy is deduced from the number of bits that are actually used to
9639 /// build Inst.
9640 struct LoadedSlice {
9641   /// \brief Helper structure used to compute the cost of a slice.
9642   struct Cost {
9643     /// Are we optimizing for code size.
9644     bool ForCodeSize;
9645     /// Various cost.
9646     unsigned Loads;
9647     unsigned Truncates;
9648     unsigned CrossRegisterBanksCopies;
9649     unsigned ZExts;
9650     unsigned Shift;
9651
9652     Cost(bool ForCodeSize = false)
9653         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9654           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9655
9656     /// \brief Get the cost of one isolated slice.
9657     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9658         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9659           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9660       EVT TruncType = LS.Inst->getValueType(0);
9661       EVT LoadedType = LS.getLoadedType();
9662       if (TruncType != LoadedType &&
9663           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9664         ZExts = 1;
9665     }
9666
9667     /// \brief Account for slicing gain in the current cost.
9668     /// Slicing provide a few gains like removing a shift or a
9669     /// truncate. This method allows to grow the cost of the original
9670     /// load with the gain from this slice.
9671     void addSliceGain(const LoadedSlice &LS) {
9672       // Each slice saves a truncate.
9673       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9674       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9675                               LS.Inst->getOperand(0).getValueType()))
9676         ++Truncates;
9677       // If there is a shift amount, this slice gets rid of it.
9678       if (LS.Shift)
9679         ++Shift;
9680       // If this slice can merge a cross register bank copy, account for it.
9681       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9682         ++CrossRegisterBanksCopies;
9683     }
9684
9685     Cost &operator+=(const Cost &RHS) {
9686       Loads += RHS.Loads;
9687       Truncates += RHS.Truncates;
9688       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9689       ZExts += RHS.ZExts;
9690       Shift += RHS.Shift;
9691       return *this;
9692     }
9693
9694     bool operator==(const Cost &RHS) const {
9695       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9696              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9697              ZExts == RHS.ZExts && Shift == RHS.Shift;
9698     }
9699
9700     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9701
9702     bool operator<(const Cost &RHS) const {
9703       // Assume cross register banks copies are as expensive as loads.
9704       // FIXME: Do we want some more target hooks?
9705       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9706       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9707       // Unless we are optimizing for code size, consider the
9708       // expensive operation first.
9709       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9710         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9711       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9712              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9713     }
9714
9715     bool operator>(const Cost &RHS) const { return RHS < *this; }
9716
9717     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9718
9719     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9720   };
9721   // The last instruction that represent the slice. This should be a
9722   // truncate instruction.
9723   SDNode *Inst;
9724   // The original load instruction.
9725   LoadSDNode *Origin;
9726   // The right shift amount in bits from the original load.
9727   unsigned Shift;
9728   // The DAG from which Origin came from.
9729   // This is used to get some contextual information about legal types, etc.
9730   SelectionDAG *DAG;
9731
9732   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9733               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9734       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9735
9736   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9737   /// \return Result is \p BitWidth and has used bits set to 1 and
9738   ///         not used bits set to 0.
9739   APInt getUsedBits() const {
9740     // Reproduce the trunc(lshr) sequence:
9741     // - Start from the truncated value.
9742     // - Zero extend to the desired bit width.
9743     // - Shift left.
9744     assert(Origin && "No original load to compare against.");
9745     unsigned BitWidth = Origin->getValueSizeInBits(0);
9746     assert(Inst && "This slice is not bound to an instruction");
9747     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9748            "Extracted slice is bigger than the whole type!");
9749     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9750     UsedBits.setAllBits();
9751     UsedBits = UsedBits.zext(BitWidth);
9752     UsedBits <<= Shift;
9753     return UsedBits;
9754   }
9755
9756   /// \brief Get the size of the slice to be loaded in bytes.
9757   unsigned getLoadedSize() const {
9758     unsigned SliceSize = getUsedBits().countPopulation();
9759     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9760     return SliceSize / 8;
9761   }
9762
9763   /// \brief Get the type that will be loaded for this slice.
9764   /// Note: This may not be the final type for the slice.
9765   EVT getLoadedType() const {
9766     assert(DAG && "Missing context");
9767     LLVMContext &Ctxt = *DAG->getContext();
9768     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9769   }
9770
9771   /// \brief Get the alignment of the load used for this slice.
9772   unsigned getAlignment() const {
9773     unsigned Alignment = Origin->getAlignment();
9774     unsigned Offset = getOffsetFromBase();
9775     if (Offset != 0)
9776       Alignment = MinAlign(Alignment, Alignment + Offset);
9777     return Alignment;
9778   }
9779
9780   /// \brief Check if this slice can be rewritten with legal operations.
9781   bool isLegal() const {
9782     // An invalid slice is not legal.
9783     if (!Origin || !Inst || !DAG)
9784       return false;
9785
9786     // Offsets are for indexed load only, we do not handle that.
9787     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9788       return false;
9789
9790     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9791
9792     // Check that the type is legal.
9793     EVT SliceType = getLoadedType();
9794     if (!TLI.isTypeLegal(SliceType))
9795       return false;
9796
9797     // Check that the load is legal for this type.
9798     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9799       return false;
9800
9801     // Check that the offset can be computed.
9802     // 1. Check its type.
9803     EVT PtrType = Origin->getBasePtr().getValueType();
9804     if (PtrType == MVT::Untyped || PtrType.isExtended())
9805       return false;
9806
9807     // 2. Check that it fits in the immediate.
9808     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9809       return false;
9810
9811     // 3. Check that the computation is legal.
9812     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9813       return false;
9814
9815     // Check that the zext is legal if it needs one.
9816     EVT TruncateType = Inst->getValueType(0);
9817     if (TruncateType != SliceType &&
9818         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9819       return false;
9820
9821     return true;
9822   }
9823
9824   /// \brief Get the offset in bytes of this slice in the original chunk of
9825   /// bits.
9826   /// \pre DAG != nullptr.
9827   uint64_t getOffsetFromBase() const {
9828     assert(DAG && "Missing context.");
9829     bool IsBigEndian =
9830         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9831     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9832     uint64_t Offset = Shift / 8;
9833     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9834     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9835            "The size of the original loaded type is not a multiple of a"
9836            " byte.");
9837     // If Offset is bigger than TySizeInBytes, it means we are loading all
9838     // zeros. This should have been optimized before in the process.
9839     assert(TySizeInBytes > Offset &&
9840            "Invalid shift amount for given loaded size");
9841     if (IsBigEndian)
9842       Offset = TySizeInBytes - Offset - getLoadedSize();
9843     return Offset;
9844   }
9845
9846   /// \brief Generate the sequence of instructions to load the slice
9847   /// represented by this object and redirect the uses of this slice to
9848   /// this new sequence of instructions.
9849   /// \pre this->Inst && this->Origin are valid Instructions and this
9850   /// object passed the legal check: LoadedSlice::isLegal returned true.
9851   /// \return The last instruction of the sequence used to load the slice.
9852   SDValue loadSlice() const {
9853     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9854     const SDValue &OldBaseAddr = Origin->getBasePtr();
9855     SDValue BaseAddr = OldBaseAddr;
9856     // Get the offset in that chunk of bytes w.r.t. the endianess.
9857     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9858     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9859     if (Offset) {
9860       // BaseAddr = BaseAddr + Offset.
9861       EVT ArithType = BaseAddr.getValueType();
9862       SDLoc DL(Origin);
9863       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9864                               DAG->getConstant(Offset, DL, ArithType));
9865     }
9866
9867     // Create the type of the loaded slice according to its size.
9868     EVT SliceType = getLoadedType();
9869
9870     // Create the load for the slice.
9871     SDValue LastInst = DAG->getLoad(
9872         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9873         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9874         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9875     // If the final type is not the same as the loaded type, this means that
9876     // we have to pad with zero. Create a zero extend for that.
9877     EVT FinalType = Inst->getValueType(0);
9878     if (SliceType != FinalType)
9879       LastInst =
9880           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9881     return LastInst;
9882   }
9883
9884   /// \brief Check if this slice can be merged with an expensive cross register
9885   /// bank copy. E.g.,
9886   /// i = load i32
9887   /// f = bitcast i32 i to float
9888   bool canMergeExpensiveCrossRegisterBankCopy() const {
9889     if (!Inst || !Inst->hasOneUse())
9890       return false;
9891     SDNode *Use = *Inst->use_begin();
9892     if (Use->getOpcode() != ISD::BITCAST)
9893       return false;
9894     assert(DAG && "Missing context");
9895     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9896     EVT ResVT = Use->getValueType(0);
9897     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9898     const TargetRegisterClass *ArgRC =
9899         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9900     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9901       return false;
9902
9903     // At this point, we know that we perform a cross-register-bank copy.
9904     // Check if it is expensive.
9905     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9906     // Assume bitcasts are cheap, unless both register classes do not
9907     // explicitly share a common sub class.
9908     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9909       return false;
9910
9911     // Check if it will be merged with the load.
9912     // 1. Check the alignment constraint.
9913     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9914         ResVT.getTypeForEVT(*DAG->getContext()));
9915
9916     if (RequiredAlignment > getAlignment())
9917       return false;
9918
9919     // 2. Check that the load is a legal operation for that type.
9920     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9921       return false;
9922
9923     // 3. Check that we do not have a zext in the way.
9924     if (Inst->getValueType(0) != getLoadedType())
9925       return false;
9926
9927     return true;
9928   }
9929 };
9930 }
9931
9932 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9933 /// \p UsedBits looks like 0..0 1..1 0..0.
9934 static bool areUsedBitsDense(const APInt &UsedBits) {
9935   // If all the bits are one, this is dense!
9936   if (UsedBits.isAllOnesValue())
9937     return true;
9938
9939   // Get rid of the unused bits on the right.
9940   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9941   // Get rid of the unused bits on the left.
9942   if (NarrowedUsedBits.countLeadingZeros())
9943     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9944   // Check that the chunk of bits is completely used.
9945   return NarrowedUsedBits.isAllOnesValue();
9946 }
9947
9948 /// \brief Check whether or not \p First and \p Second are next to each other
9949 /// in memory. This means that there is no hole between the bits loaded
9950 /// by \p First and the bits loaded by \p Second.
9951 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9952                                      const LoadedSlice &Second) {
9953   assert(First.Origin == Second.Origin && First.Origin &&
9954          "Unable to match different memory origins.");
9955   APInt UsedBits = First.getUsedBits();
9956   assert((UsedBits & Second.getUsedBits()) == 0 &&
9957          "Slices are not supposed to overlap.");
9958   UsedBits |= Second.getUsedBits();
9959   return areUsedBitsDense(UsedBits);
9960 }
9961
9962 /// \brief Adjust the \p GlobalLSCost according to the target
9963 /// paring capabilities and the layout of the slices.
9964 /// \pre \p GlobalLSCost should account for at least as many loads as
9965 /// there is in the slices in \p LoadedSlices.
9966 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9967                                  LoadedSlice::Cost &GlobalLSCost) {
9968   unsigned NumberOfSlices = LoadedSlices.size();
9969   // If there is less than 2 elements, no pairing is possible.
9970   if (NumberOfSlices < 2)
9971     return;
9972
9973   // Sort the slices so that elements that are likely to be next to each
9974   // other in memory are next to each other in the list.
9975   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9976             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9977     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9978     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9979   });
9980   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9981   // First (resp. Second) is the first (resp. Second) potentially candidate
9982   // to be placed in a paired load.
9983   const LoadedSlice *First = nullptr;
9984   const LoadedSlice *Second = nullptr;
9985   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9986                 // Set the beginning of the pair.
9987                                                            First = Second) {
9988
9989     Second = &LoadedSlices[CurrSlice];
9990
9991     // If First is NULL, it means we start a new pair.
9992     // Get to the next slice.
9993     if (!First)
9994       continue;
9995
9996     EVT LoadedType = First->getLoadedType();
9997
9998     // If the types of the slices are different, we cannot pair them.
9999     if (LoadedType != Second->getLoadedType())
10000       continue;
10001
10002     // Check if the target supplies paired loads for this type.
10003     unsigned RequiredAlignment = 0;
10004     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10005       // move to the next pair, this type is hopeless.
10006       Second = nullptr;
10007       continue;
10008     }
10009     // Check if we meet the alignment requirement.
10010     if (RequiredAlignment > First->getAlignment())
10011       continue;
10012
10013     // Check that both loads are next to each other in memory.
10014     if (!areSlicesNextToEachOther(*First, *Second))
10015       continue;
10016
10017     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10018     --GlobalLSCost.Loads;
10019     // Move to the next pair.
10020     Second = nullptr;
10021   }
10022 }
10023
10024 /// \brief Check the profitability of all involved LoadedSlice.
10025 /// Currently, it is considered profitable if there is exactly two
10026 /// involved slices (1) which are (2) next to each other in memory, and
10027 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10028 ///
10029 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10030 /// the elements themselves.
10031 ///
10032 /// FIXME: When the cost model will be mature enough, we can relax
10033 /// constraints (1) and (2).
10034 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10035                                 const APInt &UsedBits, bool ForCodeSize) {
10036   unsigned NumberOfSlices = LoadedSlices.size();
10037   if (StressLoadSlicing)
10038     return NumberOfSlices > 1;
10039
10040   // Check (1).
10041   if (NumberOfSlices != 2)
10042     return false;
10043
10044   // Check (2).
10045   if (!areUsedBitsDense(UsedBits))
10046     return false;
10047
10048   // Check (3).
10049   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10050   // The original code has one big load.
10051   OrigCost.Loads = 1;
10052   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10053     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10054     // Accumulate the cost of all the slices.
10055     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10056     GlobalSlicingCost += SliceCost;
10057
10058     // Account as cost in the original configuration the gain obtained
10059     // with the current slices.
10060     OrigCost.addSliceGain(LS);
10061   }
10062
10063   // If the target supports paired load, adjust the cost accordingly.
10064   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10065   return OrigCost > GlobalSlicingCost;
10066 }
10067
10068 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10069 /// operations, split it in the various pieces being extracted.
10070 ///
10071 /// This sort of thing is introduced by SROA.
10072 /// This slicing takes care not to insert overlapping loads.
10073 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10074 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10075   if (Level < AfterLegalizeDAG)
10076     return false;
10077
10078   LoadSDNode *LD = cast<LoadSDNode>(N);
10079   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10080       !LD->getValueType(0).isInteger())
10081     return false;
10082
10083   // Keep track of already used bits to detect overlapping values.
10084   // In that case, we will just abort the transformation.
10085   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10086
10087   SmallVector<LoadedSlice, 4> LoadedSlices;
10088
10089   // Check if this load is used as several smaller chunks of bits.
10090   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10091   // of computation for each trunc.
10092   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10093        UI != UIEnd; ++UI) {
10094     // Skip the uses of the chain.
10095     if (UI.getUse().getResNo() != 0)
10096       continue;
10097
10098     SDNode *User = *UI;
10099     unsigned Shift = 0;
10100
10101     // Check if this is a trunc(lshr).
10102     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10103         isa<ConstantSDNode>(User->getOperand(1))) {
10104       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10105       User = *User->use_begin();
10106     }
10107
10108     // At this point, User is a Truncate, iff we encountered, trunc or
10109     // trunc(lshr).
10110     if (User->getOpcode() != ISD::TRUNCATE)
10111       return false;
10112
10113     // The width of the type must be a power of 2 and greater than 8-bits.
10114     // Otherwise the load cannot be represented in LLVM IR.
10115     // Moreover, if we shifted with a non-8-bits multiple, the slice
10116     // will be across several bytes. We do not support that.
10117     unsigned Width = User->getValueSizeInBits(0);
10118     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10119       return 0;
10120
10121     // Build the slice for this chain of computations.
10122     LoadedSlice LS(User, LD, Shift, &DAG);
10123     APInt CurrentUsedBits = LS.getUsedBits();
10124
10125     // Check if this slice overlaps with another.
10126     if ((CurrentUsedBits & UsedBits) != 0)
10127       return false;
10128     // Update the bits used globally.
10129     UsedBits |= CurrentUsedBits;
10130
10131     // Check if the new slice would be legal.
10132     if (!LS.isLegal())
10133       return false;
10134
10135     // Record the slice.
10136     LoadedSlices.push_back(LS);
10137   }
10138
10139   // Abort slicing if it does not seem to be profitable.
10140   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10141     return false;
10142
10143   ++SlicedLoads;
10144
10145   // Rewrite each chain to use an independent load.
10146   // By construction, each chain can be represented by a unique load.
10147
10148   // Prepare the argument for the new token factor for all the slices.
10149   SmallVector<SDValue, 8> ArgChains;
10150   for (SmallVectorImpl<LoadedSlice>::const_iterator
10151            LSIt = LoadedSlices.begin(),
10152            LSItEnd = LoadedSlices.end();
10153        LSIt != LSItEnd; ++LSIt) {
10154     SDValue SliceInst = LSIt->loadSlice();
10155     CombineTo(LSIt->Inst, SliceInst, true);
10156     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10157       SliceInst = SliceInst.getOperand(0);
10158     assert(SliceInst->getOpcode() == ISD::LOAD &&
10159            "It takes more than a zext to get to the loaded slice!!");
10160     ArgChains.push_back(SliceInst.getValue(1));
10161   }
10162
10163   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10164                               ArgChains);
10165   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10166   return true;
10167 }
10168
10169 /// Check to see if V is (and load (ptr), imm), where the load is having
10170 /// specific bytes cleared out.  If so, return the byte size being masked out
10171 /// and the shift amount.
10172 static std::pair<unsigned, unsigned>
10173 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10174   std::pair<unsigned, unsigned> Result(0, 0);
10175
10176   // Check for the structure we're looking for.
10177   if (V->getOpcode() != ISD::AND ||
10178       !isa<ConstantSDNode>(V->getOperand(1)) ||
10179       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10180     return Result;
10181
10182   // Check the chain and pointer.
10183   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10184   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10185
10186   // The store should be chained directly to the load or be an operand of a
10187   // tokenfactor.
10188   if (LD == Chain.getNode())
10189     ; // ok.
10190   else if (Chain->getOpcode() != ISD::TokenFactor)
10191     return Result; // Fail.
10192   else {
10193     bool isOk = false;
10194     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10195       if (Chain->getOperand(i).getNode() == LD) {
10196         isOk = true;
10197         break;
10198       }
10199     if (!isOk) return Result;
10200   }
10201
10202   // This only handles simple types.
10203   if (V.getValueType() != MVT::i16 &&
10204       V.getValueType() != MVT::i32 &&
10205       V.getValueType() != MVT::i64)
10206     return Result;
10207
10208   // Check the constant mask.  Invert it so that the bits being masked out are
10209   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10210   // follow the sign bit for uniformity.
10211   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10212   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10213   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10214   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10215   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10216   if (NotMaskLZ == 64) return Result;  // All zero mask.
10217
10218   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10219   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10220     return Result;
10221
10222   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10223   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10224     NotMaskLZ -= 64-V.getValueSizeInBits();
10225
10226   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10227   switch (MaskedBytes) {
10228   case 1:
10229   case 2:
10230   case 4: break;
10231   default: return Result; // All one mask, or 5-byte mask.
10232   }
10233
10234   // Verify that the first bit starts at a multiple of mask so that the access
10235   // is aligned the same as the access width.
10236   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10237
10238   Result.first = MaskedBytes;
10239   Result.second = NotMaskTZ/8;
10240   return Result;
10241 }
10242
10243
10244 /// Check to see if IVal is something that provides a value as specified by
10245 /// MaskInfo. If so, replace the specified store with a narrower store of
10246 /// truncated IVal.
10247 static SDNode *
10248 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10249                                 SDValue IVal, StoreSDNode *St,
10250                                 DAGCombiner *DC) {
10251   unsigned NumBytes = MaskInfo.first;
10252   unsigned ByteShift = MaskInfo.second;
10253   SelectionDAG &DAG = DC->getDAG();
10254
10255   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10256   // that uses this.  If not, this is not a replacement.
10257   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10258                                   ByteShift*8, (ByteShift+NumBytes)*8);
10259   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10260
10261   // Check that it is legal on the target to do this.  It is legal if the new
10262   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10263   // legalization.
10264   MVT VT = MVT::getIntegerVT(NumBytes*8);
10265   if (!DC->isTypeLegal(VT))
10266     return nullptr;
10267
10268   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10269   // shifted by ByteShift and truncated down to NumBytes.
10270   if (ByteShift) {
10271     SDLoc DL(IVal);
10272     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10273                        DAG.getConstant(ByteShift*8, DL,
10274                                     DC->getShiftAmountTy(IVal.getValueType())));
10275   }
10276
10277   // Figure out the offset for the store and the alignment of the access.
10278   unsigned StOffset;
10279   unsigned NewAlign = St->getAlignment();
10280
10281   if (DAG.getTargetLoweringInfo().isLittleEndian())
10282     StOffset = ByteShift;
10283   else
10284     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10285
10286   SDValue Ptr = St->getBasePtr();
10287   if (StOffset) {
10288     SDLoc DL(IVal);
10289     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10290                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10291     NewAlign = MinAlign(NewAlign, StOffset);
10292   }
10293
10294   // Truncate down to the new size.
10295   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10296
10297   ++OpsNarrowed;
10298   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10299                       St->getPointerInfo().getWithOffset(StOffset),
10300                       false, false, NewAlign).getNode();
10301 }
10302
10303
10304 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10305 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10306 /// narrowing the load and store if it would end up being a win for performance
10307 /// or code size.
10308 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10309   StoreSDNode *ST  = cast<StoreSDNode>(N);
10310   if (ST->isVolatile())
10311     return SDValue();
10312
10313   SDValue Chain = ST->getChain();
10314   SDValue Value = ST->getValue();
10315   SDValue Ptr   = ST->getBasePtr();
10316   EVT VT = Value.getValueType();
10317
10318   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10319     return SDValue();
10320
10321   unsigned Opc = Value.getOpcode();
10322
10323   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10324   // is a byte mask indicating a consecutive number of bytes, check to see if
10325   // Y is known to provide just those bytes.  If so, we try to replace the
10326   // load + replace + store sequence with a single (narrower) store, which makes
10327   // the load dead.
10328   if (Opc == ISD::OR) {
10329     std::pair<unsigned, unsigned> MaskedLoad;
10330     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10331     if (MaskedLoad.first)
10332       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10333                                                   Value.getOperand(1), ST,this))
10334         return SDValue(NewST, 0);
10335
10336     // Or is commutative, so try swapping X and Y.
10337     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10338     if (MaskedLoad.first)
10339       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10340                                                   Value.getOperand(0), ST,this))
10341         return SDValue(NewST, 0);
10342   }
10343
10344   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10345       Value.getOperand(1).getOpcode() != ISD::Constant)
10346     return SDValue();
10347
10348   SDValue N0 = Value.getOperand(0);
10349   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10350       Chain == SDValue(N0.getNode(), 1)) {
10351     LoadSDNode *LD = cast<LoadSDNode>(N0);
10352     if (LD->getBasePtr() != Ptr ||
10353         LD->getPointerInfo().getAddrSpace() !=
10354         ST->getPointerInfo().getAddrSpace())
10355       return SDValue();
10356
10357     // Find the type to narrow it the load / op / store to.
10358     SDValue N1 = Value.getOperand(1);
10359     unsigned BitWidth = N1.getValueSizeInBits();
10360     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10361     if (Opc == ISD::AND)
10362       Imm ^= APInt::getAllOnesValue(BitWidth);
10363     if (Imm == 0 || Imm.isAllOnesValue())
10364       return SDValue();
10365     unsigned ShAmt = Imm.countTrailingZeros();
10366     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10367     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10368     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10369     // The narrowing should be profitable, the load/store operation should be
10370     // legal (or custom) and the store size should be equal to the NewVT width.
10371     while (NewBW < BitWidth &&
10372            (NewVT.getStoreSizeInBits() != NewBW ||
10373             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10374             !TLI.isNarrowingProfitable(VT, NewVT))) {
10375       NewBW = NextPowerOf2(NewBW);
10376       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10377     }
10378     if (NewBW >= BitWidth)
10379       return SDValue();
10380
10381     // If the lsb changed does not start at the type bitwidth boundary,
10382     // start at the previous one.
10383     if (ShAmt % NewBW)
10384       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10385     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10386                                    std::min(BitWidth, ShAmt + NewBW));
10387     if ((Imm & Mask) == Imm) {
10388       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10389       if (Opc == ISD::AND)
10390         NewImm ^= APInt::getAllOnesValue(NewBW);
10391       uint64_t PtrOff = ShAmt / 8;
10392       // For big endian targets, we need to adjust the offset to the pointer to
10393       // load the correct bytes.
10394       if (TLI.isBigEndian())
10395         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10396
10397       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10398       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10399       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10400         return SDValue();
10401
10402       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10403                                    Ptr.getValueType(), Ptr,
10404                                    DAG.getConstant(PtrOff, SDLoc(LD),
10405                                                    Ptr.getValueType()));
10406       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10407                                   LD->getChain(), NewPtr,
10408                                   LD->getPointerInfo().getWithOffset(PtrOff),
10409                                   LD->isVolatile(), LD->isNonTemporal(),
10410                                   LD->isInvariant(), NewAlign,
10411                                   LD->getAAInfo());
10412       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10413                                    DAG.getConstant(NewImm, SDLoc(Value),
10414                                                    NewVT));
10415       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10416                                    NewVal, NewPtr,
10417                                    ST->getPointerInfo().getWithOffset(PtrOff),
10418                                    false, false, NewAlign);
10419
10420       AddToWorklist(NewPtr.getNode());
10421       AddToWorklist(NewLD.getNode());
10422       AddToWorklist(NewVal.getNode());
10423       WorklistRemover DeadNodes(*this);
10424       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10425       ++OpsNarrowed;
10426       return NewST;
10427     }
10428   }
10429
10430   return SDValue();
10431 }
10432
10433 /// For a given floating point load / store pair, if the load value isn't used
10434 /// by any other operations, then consider transforming the pair to integer
10435 /// load / store operations if the target deems the transformation profitable.
10436 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10437   StoreSDNode *ST  = cast<StoreSDNode>(N);
10438   SDValue Chain = ST->getChain();
10439   SDValue Value = ST->getValue();
10440   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10441       Value.hasOneUse() &&
10442       Chain == SDValue(Value.getNode(), 1)) {
10443     LoadSDNode *LD = cast<LoadSDNode>(Value);
10444     EVT VT = LD->getMemoryVT();
10445     if (!VT.isFloatingPoint() ||
10446         VT != ST->getMemoryVT() ||
10447         LD->isNonTemporal() ||
10448         ST->isNonTemporal() ||
10449         LD->getPointerInfo().getAddrSpace() != 0 ||
10450         ST->getPointerInfo().getAddrSpace() != 0)
10451       return SDValue();
10452
10453     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10454     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10455         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10456         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10457         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10458       return SDValue();
10459
10460     unsigned LDAlign = LD->getAlignment();
10461     unsigned STAlign = ST->getAlignment();
10462     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10463     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10464     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10465       return SDValue();
10466
10467     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10468                                 LD->getChain(), LD->getBasePtr(),
10469                                 LD->getPointerInfo(),
10470                                 false, false, false, LDAlign);
10471
10472     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10473                                  NewLD, ST->getBasePtr(),
10474                                  ST->getPointerInfo(),
10475                                  false, false, STAlign);
10476
10477     AddToWorklist(NewLD.getNode());
10478     AddToWorklist(NewST.getNode());
10479     WorklistRemover DeadNodes(*this);
10480     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10481     ++LdStFP2Int;
10482     return NewST;
10483   }
10484
10485   return SDValue();
10486 }
10487
10488 namespace {
10489 /// Helper struct to parse and store a memory address as base + index + offset.
10490 /// We ignore sign extensions when it is safe to do so.
10491 /// The following two expressions are not equivalent. To differentiate we need
10492 /// to store whether there was a sign extension involved in the index
10493 /// computation.
10494 ///  (load (i64 add (i64 copyfromreg %c)
10495 ///                 (i64 signextend (add (i8 load %index)
10496 ///                                      (i8 1))))
10497 /// vs
10498 ///
10499 /// (load (i64 add (i64 copyfromreg %c)
10500 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10501 ///                                         (i32 1)))))
10502 struct BaseIndexOffset {
10503   SDValue Base;
10504   SDValue Index;
10505   int64_t Offset;
10506   bool IsIndexSignExt;
10507
10508   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10509
10510   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10511                   bool IsIndexSignExt) :
10512     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10513
10514   bool equalBaseIndex(const BaseIndexOffset &Other) {
10515     return Other.Base == Base && Other.Index == Index &&
10516       Other.IsIndexSignExt == IsIndexSignExt;
10517   }
10518
10519   /// Parses tree in Ptr for base, index, offset addresses.
10520   static BaseIndexOffset match(SDValue Ptr) {
10521     bool IsIndexSignExt = false;
10522
10523     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10524     // instruction, then it could be just the BASE or everything else we don't
10525     // know how to handle. Just use Ptr as BASE and give up.
10526     if (Ptr->getOpcode() != ISD::ADD)
10527       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10528
10529     // We know that we have at least an ADD instruction. Try to pattern match
10530     // the simple case of BASE + OFFSET.
10531     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10532       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10533       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10534                               IsIndexSignExt);
10535     }
10536
10537     // Inside a loop the current BASE pointer is calculated using an ADD and a
10538     // MUL instruction. In this case Ptr is the actual BASE pointer.
10539     // (i64 add (i64 %array_ptr)
10540     //          (i64 mul (i64 %induction_var)
10541     //                   (i64 %element_size)))
10542     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10543       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10544
10545     // Look at Base + Index + Offset cases.
10546     SDValue Base = Ptr->getOperand(0);
10547     SDValue IndexOffset = Ptr->getOperand(1);
10548
10549     // Skip signextends.
10550     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10551       IndexOffset = IndexOffset->getOperand(0);
10552       IsIndexSignExt = true;
10553     }
10554
10555     // Either the case of Base + Index (no offset) or something else.
10556     if (IndexOffset->getOpcode() != ISD::ADD)
10557       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10558
10559     // Now we have the case of Base + Index + offset.
10560     SDValue Index = IndexOffset->getOperand(0);
10561     SDValue Offset = IndexOffset->getOperand(1);
10562
10563     if (!isa<ConstantSDNode>(Offset))
10564       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10565
10566     // Ignore signextends.
10567     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10568       Index = Index->getOperand(0);
10569       IsIndexSignExt = true;
10570     } else IsIndexSignExt = false;
10571
10572     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10573     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10574   }
10575 };
10576 } // namespace
10577
10578 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10579                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10580                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10581   // Make sure we have something to merge.
10582   if (NumElem < 2)
10583     return false;
10584
10585   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10586   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10587   unsigned LatestNodeUsed = 0;
10588
10589   for (unsigned i=0; i < NumElem; ++i) {
10590     // Find a chain for the new wide-store operand. Notice that some
10591     // of the store nodes that we found may not be selected for inclusion
10592     // in the wide store. The chain we use needs to be the chain of the
10593     // latest store node which is *used* and replaced by the wide store.
10594     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10595       LatestNodeUsed = i;
10596   }
10597
10598   // The latest Node in the DAG.
10599   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10600   SDLoc DL(StoreNodes[0].MemNode);
10601
10602   SDValue StoredVal;
10603   if (UseVector) {
10604     // Find a legal type for the vector store.
10605     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10606     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10607     if (IsConstantSrc) {
10608       // A vector store with a constant source implies that the constant is
10609       // zero; we only handle merging stores of constant zeros because the zero
10610       // can be materialized without a load.
10611       // It may be beneficial to loosen this restriction to allow non-zero
10612       // store merging.
10613       StoredVal = DAG.getConstant(0, DL, Ty);
10614     } else {
10615       SmallVector<SDValue, 8> Ops;
10616       for (unsigned i = 0; i < NumElem ; ++i) {
10617         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10618         SDValue Val = St->getValue();
10619         // All of the operands of a BUILD_VECTOR must have the same type.
10620         if (Val.getValueType() != MemVT)
10621           return false;
10622         Ops.push_back(Val);
10623       }
10624
10625       // Build the extracted vector elements back into a vector.
10626       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10627     }
10628   } else {
10629     // We should always use a vector store when merging extracted vector
10630     // elements, so this path implies a store of constants.
10631     assert(IsConstantSrc && "Merged vector elements should use vector store");
10632
10633     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10634     APInt StoreInt(StoreBW, 0);
10635
10636     // Construct a single integer constant which is made of the smaller
10637     // constant inputs.
10638     bool IsLE = TLI.isLittleEndian();
10639     for (unsigned i = 0; i < NumElem ; ++i) {
10640       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10641       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10642       SDValue Val = St->getValue();
10643       StoreInt <<= ElementSizeBytes*8;
10644       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10645         StoreInt |= C->getAPIntValue().zext(StoreBW);
10646       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10647         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10648       } else {
10649         llvm_unreachable("Invalid constant element type");
10650       }
10651     }
10652
10653     // Create the new Load and Store operations.
10654     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10655     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10656   }
10657
10658   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10659                                   FirstInChain->getBasePtr(),
10660                                   FirstInChain->getPointerInfo(),
10661                                   false, false,
10662                                   FirstInChain->getAlignment());
10663
10664   // Replace the last store with the new store
10665   CombineTo(LatestOp, NewStore);
10666   // Erase all other stores.
10667   for (unsigned i = 0; i < NumElem ; ++i) {
10668     if (StoreNodes[i].MemNode == LatestOp)
10669       continue;
10670     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10671     // ReplaceAllUsesWith will replace all uses that existed when it was
10672     // called, but graph optimizations may cause new ones to appear. For
10673     // example, the case in pr14333 looks like
10674     //
10675     //  St's chain -> St -> another store -> X
10676     //
10677     // And the only difference from St to the other store is the chain.
10678     // When we change it's chain to be St's chain they become identical,
10679     // get CSEed and the net result is that X is now a use of St.
10680     // Since we know that St is redundant, just iterate.
10681     while (!St->use_empty())
10682       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10683     deleteAndRecombine(St);
10684   }
10685
10686   return true;
10687 }
10688
10689 static bool allowableAlignment(const SelectionDAG &DAG,
10690                                const TargetLowering &TLI, EVT EVTTy,
10691                                unsigned AS, unsigned Align) {
10692   if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10693     return true;
10694
10695   Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10696   unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10697   return (Align >= ABIAlignment);
10698 }
10699
10700 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10701   if (OptLevel == CodeGenOpt::None)
10702     return false;
10703
10704   EVT MemVT = St->getMemoryVT();
10705   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10706   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10707       Attribute::NoImplicitFloat);
10708
10709   // This function cannot currently deal with non-byte-sized memory sizes.
10710   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10711     return false;
10712
10713   // Don't merge vectors into wider inputs.
10714   if (MemVT.isVector() || !MemVT.isSimple())
10715     return false;
10716
10717   // Perform an early exit check. Do not bother looking at stored values that
10718   // are not constants, loads, or extracted vector elements.
10719   SDValue StoredVal = St->getValue();
10720   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10721   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10722                        isa<ConstantFPSDNode>(StoredVal);
10723   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10724
10725   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10726     return false;
10727
10728   // Only look at ends of store sequences.
10729   SDValue Chain = SDValue(St, 0);
10730   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10731     return false;
10732
10733   // This holds the base pointer, index, and the offset in bytes from the base
10734   // pointer.
10735   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10736
10737   // We must have a base and an offset.
10738   if (!BasePtr.Base.getNode())
10739     return false;
10740
10741   // Do not handle stores to undef base pointers.
10742   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10743     return false;
10744
10745   // Save the LoadSDNodes that we find in the chain.
10746   // We need to make sure that these nodes do not interfere with
10747   // any of the store nodes.
10748   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10749
10750   // Save the StoreSDNodes that we find in the chain.
10751   SmallVector<MemOpLink, 8> StoreNodes;
10752
10753   // Walk up the chain and look for nodes with offsets from the same
10754   // base pointer. Stop when reaching an instruction with a different kind
10755   // or instruction which has a different base pointer.
10756   unsigned Seq = 0;
10757   StoreSDNode *Index = St;
10758   while (Index) {
10759     // If the chain has more than one use, then we can't reorder the mem ops.
10760     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10761       break;
10762
10763     // Find the base pointer and offset for this memory node.
10764     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10765
10766     // Check that the base pointer is the same as the original one.
10767     if (!Ptr.equalBaseIndex(BasePtr))
10768       break;
10769
10770     // The memory operands must not be volatile.
10771     if (Index->isVolatile() || Index->isIndexed())
10772       break;
10773
10774     // No truncation.
10775     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10776       if (St->isTruncatingStore())
10777         break;
10778
10779     // The stored memory type must be the same.
10780     if (Index->getMemoryVT() != MemVT)
10781       break;
10782
10783     // We found a potential memory operand to merge.
10784     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10785
10786     // Find the next memory operand in the chain. If the next operand in the
10787     // chain is a store then move up and continue the scan with the next
10788     // memory operand. If the next operand is a load save it and use alias
10789     // information to check if it interferes with anything.
10790     SDNode *NextInChain = Index->getChain().getNode();
10791     while (1) {
10792       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10793         // We found a store node. Use it for the next iteration.
10794         Index = STn;
10795         break;
10796       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10797         if (Ldn->isVolatile()) {
10798           Index = nullptr;
10799           break;
10800         }
10801
10802         // Save the load node for later. Continue the scan.
10803         AliasLoadNodes.push_back(Ldn);
10804         NextInChain = Ldn->getChain().getNode();
10805         continue;
10806       } else {
10807         Index = nullptr;
10808         break;
10809       }
10810     }
10811   }
10812
10813   // Check if there is anything to merge.
10814   if (StoreNodes.size() < 2)
10815     return false;
10816
10817   // Sort the memory operands according to their distance from the base pointer.
10818   std::sort(StoreNodes.begin(), StoreNodes.end(),
10819             [](MemOpLink LHS, MemOpLink RHS) {
10820     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10821            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10822             LHS.SequenceNum > RHS.SequenceNum);
10823   });
10824
10825   // Scan the memory operations on the chain and find the first non-consecutive
10826   // store memory address.
10827   unsigned LastConsecutiveStore = 0;
10828   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10829   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10830
10831     // Check that the addresses are consecutive starting from the second
10832     // element in the list of stores.
10833     if (i > 0) {
10834       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10835       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10836         break;
10837     }
10838
10839     bool Alias = false;
10840     // Check if this store interferes with any of the loads that we found.
10841     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10842       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10843         Alias = true;
10844         break;
10845       }
10846     // We found a load that alias with this store. Stop the sequence.
10847     if (Alias)
10848       break;
10849
10850     // Mark this node as useful.
10851     LastConsecutiveStore = i;
10852   }
10853
10854   // The node with the lowest store address.
10855   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10856   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10857   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10858
10859   // Store the constants into memory as one consecutive store.
10860   if (IsConstantSrc) {
10861     unsigned LastLegalType = 0;
10862     unsigned LastLegalVectorType = 0;
10863     bool NonZero = false;
10864     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10865       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10866       SDValue StoredVal = St->getValue();
10867
10868       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10869         NonZero |= !C->isNullValue();
10870       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10871         NonZero |= !C->getConstantFPValue()->isNullValue();
10872       } else {
10873         // Non-constant.
10874         break;
10875       }
10876
10877       // Find a legal type for the constant store.
10878       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10879       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10880       if (TLI.isTypeLegal(StoreTy) &&
10881           allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10882                              FirstStoreAlign)) {
10883         LastLegalType = i+1;
10884       // Or check whether a truncstore is legal.
10885       } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10886                  TargetLowering::TypePromoteInteger) {
10887         EVT LegalizedStoredValueTy =
10888           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10889         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10890             allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10891                                FirstStoreAlign)) {
10892           LastLegalType = i + 1;
10893         }
10894       }
10895
10896       // Find a legal type for the vector store.
10897       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10898       if (TLI.isTypeLegal(Ty) &&
10899           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10900         LastLegalVectorType = i + 1;
10901       }
10902     }
10903
10904
10905     // We only use vectors if the constant is known to be zero or the target
10906     // allows it and the function is not marked with the noimplicitfloat
10907     // attribute.
10908     if (NoVectors) {
10909       LastLegalVectorType = 0;
10910     } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10911                                                             LastLegalVectorType,
10912                                                             FirstStoreAS)) {
10913       LastLegalVectorType = 0;
10914     }
10915
10916     // Check if we found a legal integer type to store.
10917     if (LastLegalType == 0 && LastLegalVectorType == 0)
10918       return false;
10919
10920     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10921     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10922
10923     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10924                                            true, UseVector);
10925   }
10926
10927   // When extracting multiple vector elements, try to store them
10928   // in one vector store rather than a sequence of scalar stores.
10929   if (IsExtractVecEltSrc) {
10930     unsigned NumElem = 0;
10931     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10932       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10933       SDValue StoredVal = St->getValue();
10934       // This restriction could be loosened.
10935       // Bail out if any stored values are not elements extracted from a vector.
10936       // It should be possible to handle mixed sources, but load sources need
10937       // more careful handling (see the block of code below that handles
10938       // consecutive loads).
10939       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10940         return false;
10941
10942       // Find a legal type for the vector store.
10943       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10944       if (TLI.isTypeLegal(Ty) &&
10945           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10946         NumElem = i + 1;
10947     }
10948
10949     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10950                                            false, true);
10951   }
10952
10953   // Below we handle the case of multiple consecutive stores that
10954   // come from multiple consecutive loads. We merge them into a single
10955   // wide load and a single wide store.
10956
10957   // Look for load nodes which are used by the stored values.
10958   SmallVector<MemOpLink, 8> LoadNodes;
10959
10960   // Find acceptable loads. Loads need to have the same chain (token factor),
10961   // must not be zext, volatile, indexed, and they must be consecutive.
10962   BaseIndexOffset LdBasePtr;
10963   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10964     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10965     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10966     if (!Ld) break;
10967
10968     // Loads must only have one use.
10969     if (!Ld->hasNUsesOfValue(1, 0))
10970       break;
10971
10972     // The memory operands must not be volatile.
10973     if (Ld->isVolatile() || Ld->isIndexed())
10974       break;
10975
10976     // We do not accept ext loads.
10977     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10978       break;
10979
10980     // The stored memory type must be the same.
10981     if (Ld->getMemoryVT() != MemVT)
10982       break;
10983
10984     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10985     // If this is not the first ptr that we check.
10986     if (LdBasePtr.Base.getNode()) {
10987       // The base ptr must be the same.
10988       if (!LdPtr.equalBaseIndex(LdBasePtr))
10989         break;
10990     } else {
10991       // Check that all other base pointers are the same as this one.
10992       LdBasePtr = LdPtr;
10993     }
10994
10995     // We found a potential memory operand to merge.
10996     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10997   }
10998
10999   if (LoadNodes.size() < 2)
11000     return false;
11001
11002   // If we have load/store pair instructions and we only have two values,
11003   // don't bother.
11004   unsigned RequiredAlignment;
11005   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11006       St->getAlignment() >= RequiredAlignment)
11007     return false;
11008
11009   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11010   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11011   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11012
11013   // Scan the memory operations on the chain and find the first non-consecutive
11014   // load memory address. These variables hold the index in the store node
11015   // array.
11016   unsigned LastConsecutiveLoad = 0;
11017   // This variable refers to the size and not index in the array.
11018   unsigned LastLegalVectorType = 0;
11019   unsigned LastLegalIntegerType = 0;
11020   StartAddress = LoadNodes[0].OffsetFromBase;
11021   SDValue FirstChain = FirstLoad->getChain();
11022   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11023     // All loads much share the same chain.
11024     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11025       break;
11026
11027     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11028     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11029       break;
11030     LastConsecutiveLoad = i;
11031
11032     // Find a legal type for the vector store.
11033     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11034     if (TLI.isTypeLegal(StoreTy) &&
11035         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11036         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11037       LastLegalVectorType = i + 1;
11038     }
11039
11040     // Find a legal type for the integer store.
11041     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
11042     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11043     if (TLI.isTypeLegal(StoreTy) &&
11044         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11045         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11046       LastLegalIntegerType = i + 1;
11047     // Or check whether a truncstore and extload is legal.
11048     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11049              TargetLowering::TypePromoteInteger) {
11050       EVT LegalizedStoredValueTy =
11051         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11052       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11053           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11054           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11055           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11056           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11057                              FirstStoreAlign) &&
11058           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11059                              FirstLoadAlign))
11060         LastLegalIntegerType = i+1;
11061     }
11062   }
11063
11064   // Only use vector types if the vector type is larger than the integer type.
11065   // If they are the same, use integers.
11066   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11067   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11068
11069   // We add +1 here because the LastXXX variables refer to location while
11070   // the NumElem refers to array/index size.
11071   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11072   NumElem = std::min(LastLegalType, NumElem);
11073
11074   if (NumElem < 2)
11075     return false;
11076
11077   // The latest Node in the DAG.
11078   unsigned LatestNodeUsed = 0;
11079   for (unsigned i=1; i<NumElem; ++i) {
11080     // Find a chain for the new wide-store operand. Notice that some
11081     // of the store nodes that we found may not be selected for inclusion
11082     // in the wide store. The chain we use needs to be the chain of the
11083     // latest store node which is *used* and replaced by the wide store.
11084     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11085       LatestNodeUsed = i;
11086   }
11087
11088   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11089
11090   // Find if it is better to use vectors or integers to load and store
11091   // to memory.
11092   EVT JointMemOpVT;
11093   if (UseVectorTy) {
11094     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11095   } else {
11096     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11097     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11098   }
11099
11100   SDLoc LoadDL(LoadNodes[0].MemNode);
11101   SDLoc StoreDL(StoreNodes[0].MemNode);
11102
11103   SDValue NewLoad = DAG.getLoad(
11104       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11105       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11106
11107   SDValue NewStore = DAG.getStore(
11108       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11109       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11110
11111   // Replace one of the loads with the new load.
11112   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11113   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11114                                 SDValue(NewLoad.getNode(), 1));
11115
11116   // Remove the rest of the load chains.
11117   for (unsigned i = 1; i < NumElem ; ++i) {
11118     // Replace all chain users of the old load nodes with the chain of the new
11119     // load node.
11120     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11121     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11122   }
11123
11124   // Replace the last store with the new store.
11125   CombineTo(LatestOp, NewStore);
11126   // Erase all other stores.
11127   for (unsigned i = 0; i < NumElem ; ++i) {
11128     // Remove all Store nodes.
11129     if (StoreNodes[i].MemNode == LatestOp)
11130       continue;
11131     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11132     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11133     deleteAndRecombine(St);
11134   }
11135
11136   return true;
11137 }
11138
11139 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11140   StoreSDNode *ST  = cast<StoreSDNode>(N);
11141   SDValue Chain = ST->getChain();
11142   SDValue Value = ST->getValue();
11143   SDValue Ptr   = ST->getBasePtr();
11144
11145   // If this is a store of a bit convert, store the input value if the
11146   // resultant store does not need a higher alignment than the original.
11147   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11148       ST->isUnindexed()) {
11149     unsigned OrigAlign = ST->getAlignment();
11150     EVT SVT = Value.getOperand(0).getValueType();
11151     unsigned Align = TLI.getDataLayout()->
11152       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11153     if (Align <= OrigAlign &&
11154         ((!LegalOperations && !ST->isVolatile()) ||
11155          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11156       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11157                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11158                           ST->isNonTemporal(), OrigAlign,
11159                           ST->getAAInfo());
11160   }
11161
11162   // Turn 'store undef, Ptr' -> nothing.
11163   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11164     return Chain;
11165
11166   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11167   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11168     // NOTE: If the original store is volatile, this transform must not increase
11169     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11170     // processor operation but an i64 (which is not legal) requires two.  So the
11171     // transform should not be done in this case.
11172     if (Value.getOpcode() != ISD::TargetConstantFP) {
11173       SDValue Tmp;
11174       switch (CFP->getSimpleValueType(0).SimpleTy) {
11175       default: llvm_unreachable("Unknown FP type");
11176       case MVT::f16:    // We don't do this for these yet.
11177       case MVT::f80:
11178       case MVT::f128:
11179       case MVT::ppcf128:
11180         break;
11181       case MVT::f32:
11182         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11183             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11184           ;
11185           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11186                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11187                               MVT::i32);
11188           return DAG.getStore(Chain, SDLoc(N), Tmp,
11189                               Ptr, ST->getMemOperand());
11190         }
11191         break;
11192       case MVT::f64:
11193         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11194              !ST->isVolatile()) ||
11195             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11196           ;
11197           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11198                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11199           return DAG.getStore(Chain, SDLoc(N), Tmp,
11200                               Ptr, ST->getMemOperand());
11201         }
11202
11203         if (!ST->isVolatile() &&
11204             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11205           // Many FP stores are not made apparent until after legalize, e.g. for
11206           // argument passing.  Since this is so common, custom legalize the
11207           // 64-bit integer store into two 32-bit stores.
11208           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11209           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11210           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11211           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11212
11213           unsigned Alignment = ST->getAlignment();
11214           bool isVolatile = ST->isVolatile();
11215           bool isNonTemporal = ST->isNonTemporal();
11216           AAMDNodes AAInfo = ST->getAAInfo();
11217
11218           SDLoc DL(N);
11219
11220           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11221                                      Ptr, ST->getPointerInfo(),
11222                                      isVolatile, isNonTemporal,
11223                                      ST->getAlignment(), AAInfo);
11224           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11225                             DAG.getConstant(4, DL, Ptr.getValueType()));
11226           Alignment = MinAlign(Alignment, 4U);
11227           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11228                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11229                                      isVolatile, isNonTemporal,
11230                                      Alignment, AAInfo);
11231           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11232                              St0, St1);
11233         }
11234
11235         break;
11236       }
11237     }
11238   }
11239
11240   // Try to infer better alignment information than the store already has.
11241   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11242     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11243       if (Align > ST->getAlignment()) {
11244         SDValue NewStore =
11245                DAG.getTruncStore(Chain, SDLoc(N), Value,
11246                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11247                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11248                                  ST->getAAInfo());
11249         if (NewStore.getNode() != N)
11250           return CombineTo(ST, NewStore, true);
11251       }
11252     }
11253   }
11254
11255   // Try transforming a pair floating point load / store ops to integer
11256   // load / store ops.
11257   SDValue NewST = TransformFPLoadStorePair(N);
11258   if (NewST.getNode())
11259     return NewST;
11260
11261   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11262                                                   : DAG.getSubtarget().useAA();
11263 #ifndef NDEBUG
11264   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11265       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11266     UseAA = false;
11267 #endif
11268   if (UseAA && ST->isUnindexed()) {
11269     // Walk up chain skipping non-aliasing memory nodes.
11270     SDValue BetterChain = FindBetterChain(N, Chain);
11271
11272     // If there is a better chain.
11273     if (Chain != BetterChain) {
11274       SDValue ReplStore;
11275
11276       // Replace the chain to avoid dependency.
11277       if (ST->isTruncatingStore()) {
11278         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11279                                       ST->getMemoryVT(), ST->getMemOperand());
11280       } else {
11281         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11282                                  ST->getMemOperand());
11283       }
11284
11285       // Create token to keep both nodes around.
11286       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11287                                   MVT::Other, Chain, ReplStore);
11288
11289       // Make sure the new and old chains are cleaned up.
11290       AddToWorklist(Token.getNode());
11291
11292       // Don't add users to work list.
11293       return CombineTo(N, Token, false);
11294     }
11295   }
11296
11297   // Try transforming N to an indexed store.
11298   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11299     return SDValue(N, 0);
11300
11301   // FIXME: is there such a thing as a truncating indexed store?
11302   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11303       Value.getValueType().isInteger()) {
11304     // See if we can simplify the input to this truncstore with knowledge that
11305     // only the low bits are being used.  For example:
11306     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11307     SDValue Shorter =
11308       GetDemandedBits(Value,
11309                       APInt::getLowBitsSet(
11310                         Value.getValueType().getScalarType().getSizeInBits(),
11311                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11312     AddToWorklist(Value.getNode());
11313     if (Shorter.getNode())
11314       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11315                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11316
11317     // Otherwise, see if we can simplify the operation with
11318     // SimplifyDemandedBits, which only works if the value has a single use.
11319     if (SimplifyDemandedBits(Value,
11320                         APInt::getLowBitsSet(
11321                           Value.getValueType().getScalarType().getSizeInBits(),
11322                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11323       return SDValue(N, 0);
11324   }
11325
11326   // If this is a load followed by a store to the same location, then the store
11327   // is dead/noop.
11328   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11329     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11330         ST->isUnindexed() && !ST->isVolatile() &&
11331         // There can't be any side effects between the load and store, such as
11332         // a call or store.
11333         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11334       // The store is dead, remove it.
11335       return Chain;
11336     }
11337   }
11338
11339   // If this is a store followed by a store with the same value to the same
11340   // location, then the store is dead/noop.
11341   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11342     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11343         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11344         ST1->isUnindexed() && !ST1->isVolatile()) {
11345       // The store is dead, remove it.
11346       return Chain;
11347     }
11348   }
11349
11350   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11351   // truncating store.  We can do this even if this is already a truncstore.
11352   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11353       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11354       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11355                             ST->getMemoryVT())) {
11356     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11357                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11358   }
11359
11360   // Only perform this optimization before the types are legal, because we
11361   // don't want to perform this optimization on every DAGCombine invocation.
11362   if (!LegalTypes) {
11363     bool EverChanged = false;
11364
11365     do {
11366       // There can be multiple store sequences on the same chain.
11367       // Keep trying to merge store sequences until we are unable to do so
11368       // or until we merge the last store on the chain.
11369       bool Changed = MergeConsecutiveStores(ST);
11370       EverChanged |= Changed;
11371       if (!Changed) break;
11372     } while (ST->getOpcode() != ISD::DELETED_NODE);
11373
11374     if (EverChanged)
11375       return SDValue(N, 0);
11376   }
11377
11378   return ReduceLoadOpStoreWidth(N);
11379 }
11380
11381 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11382   SDValue InVec = N->getOperand(0);
11383   SDValue InVal = N->getOperand(1);
11384   SDValue EltNo = N->getOperand(2);
11385   SDLoc dl(N);
11386
11387   // If the inserted element is an UNDEF, just use the input vector.
11388   if (InVal.getOpcode() == ISD::UNDEF)
11389     return InVec;
11390
11391   EVT VT = InVec.getValueType();
11392
11393   // If we can't generate a legal BUILD_VECTOR, exit
11394   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11395     return SDValue();
11396
11397   // Check that we know which element is being inserted
11398   if (!isa<ConstantSDNode>(EltNo))
11399     return SDValue();
11400   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11401
11402   // Canonicalize insert_vector_elt dag nodes.
11403   // Example:
11404   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11405   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11406   //
11407   // Do this only if the child insert_vector node has one use; also
11408   // do this only if indices are both constants and Idx1 < Idx0.
11409   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11410       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11411     unsigned OtherElt =
11412       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11413     if (Elt < OtherElt) {
11414       // Swap nodes.
11415       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11416                                   InVec.getOperand(0), InVal, EltNo);
11417       AddToWorklist(NewOp.getNode());
11418       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11419                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11420     }
11421   }
11422
11423   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11424   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11425   // vector elements.
11426   SmallVector<SDValue, 8> Ops;
11427   // Do not combine these two vectors if the output vector will not replace
11428   // the input vector.
11429   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11430     Ops.append(InVec.getNode()->op_begin(),
11431                InVec.getNode()->op_end());
11432   } else if (InVec.getOpcode() == ISD::UNDEF) {
11433     unsigned NElts = VT.getVectorNumElements();
11434     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11435   } else {
11436     return SDValue();
11437   }
11438
11439   // Insert the element
11440   if (Elt < Ops.size()) {
11441     // All the operands of BUILD_VECTOR must have the same type;
11442     // we enforce that here.
11443     EVT OpVT = Ops[0].getValueType();
11444     if (InVal.getValueType() != OpVT)
11445       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11446                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11447                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11448     Ops[Elt] = InVal;
11449   }
11450
11451   // Return the new vector
11452   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11453 }
11454
11455 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11456     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11457   EVT ResultVT = EVE->getValueType(0);
11458   EVT VecEltVT = InVecVT.getVectorElementType();
11459   unsigned Align = OriginalLoad->getAlignment();
11460   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11461       VecEltVT.getTypeForEVT(*DAG.getContext()));
11462
11463   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11464     return SDValue();
11465
11466   Align = NewAlign;
11467
11468   SDValue NewPtr = OriginalLoad->getBasePtr();
11469   SDValue Offset;
11470   EVT PtrType = NewPtr.getValueType();
11471   MachinePointerInfo MPI;
11472   SDLoc DL(EVE);
11473   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11474     int Elt = ConstEltNo->getZExtValue();
11475     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11476     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11477     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11478   } else {
11479     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11480     Offset = DAG.getNode(
11481         ISD::MUL, DL, PtrType, Offset,
11482         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11483     MPI = OriginalLoad->getPointerInfo();
11484   }
11485   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11486
11487   // The replacement we need to do here is a little tricky: we need to
11488   // replace an extractelement of a load with a load.
11489   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11490   // Note that this replacement assumes that the extractvalue is the only
11491   // use of the load; that's okay because we don't want to perform this
11492   // transformation in other cases anyway.
11493   SDValue Load;
11494   SDValue Chain;
11495   if (ResultVT.bitsGT(VecEltVT)) {
11496     // If the result type of vextract is wider than the load, then issue an
11497     // extending load instead.
11498     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11499                                                   VecEltVT)
11500                                    ? ISD::ZEXTLOAD
11501                                    : ISD::EXTLOAD;
11502     Load = DAG.getExtLoad(
11503         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11504         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11505         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11506     Chain = Load.getValue(1);
11507   } else {
11508     Load = DAG.getLoad(
11509         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11510         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11511         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11512     Chain = Load.getValue(1);
11513     if (ResultVT.bitsLT(VecEltVT))
11514       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11515     else
11516       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11517   }
11518   WorklistRemover DeadNodes(*this);
11519   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11520   SDValue To[] = { Load, Chain };
11521   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11522   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11523   // worklist explicitly as well.
11524   AddToWorklist(Load.getNode());
11525   AddUsersToWorklist(Load.getNode()); // Add users too
11526   // Make sure to revisit this node to clean it up; it will usually be dead.
11527   AddToWorklist(EVE);
11528   ++OpsNarrowed;
11529   return SDValue(EVE, 0);
11530 }
11531
11532 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11533   // (vextract (scalar_to_vector val, 0) -> val
11534   SDValue InVec = N->getOperand(0);
11535   EVT VT = InVec.getValueType();
11536   EVT NVT = N->getValueType(0);
11537
11538   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11539     // Check if the result type doesn't match the inserted element type. A
11540     // SCALAR_TO_VECTOR may truncate the inserted element and the
11541     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11542     SDValue InOp = InVec.getOperand(0);
11543     if (InOp.getValueType() != NVT) {
11544       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11545       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11546     }
11547     return InOp;
11548   }
11549
11550   SDValue EltNo = N->getOperand(1);
11551   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11552
11553   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11554   // We only perform this optimization before the op legalization phase because
11555   // we may introduce new vector instructions which are not backed by TD
11556   // patterns. For example on AVX, extracting elements from a wide vector
11557   // without using extract_subvector. However, if we can find an underlying
11558   // scalar value, then we can always use that.
11559   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11560       && ConstEltNo) {
11561     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11562     int NumElem = VT.getVectorNumElements();
11563     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11564     // Find the new index to extract from.
11565     int OrigElt = SVOp->getMaskElt(Elt);
11566
11567     // Extracting an undef index is undef.
11568     if (OrigElt == -1)
11569       return DAG.getUNDEF(NVT);
11570
11571     // Select the right vector half to extract from.
11572     SDValue SVInVec;
11573     if (OrigElt < NumElem) {
11574       SVInVec = InVec->getOperand(0);
11575     } else {
11576       SVInVec = InVec->getOperand(1);
11577       OrigElt -= NumElem;
11578     }
11579
11580     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11581       SDValue InOp = SVInVec.getOperand(OrigElt);
11582       if (InOp.getValueType() != NVT) {
11583         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11584         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11585       }
11586
11587       return InOp;
11588     }
11589
11590     // FIXME: We should handle recursing on other vector shuffles and
11591     // scalar_to_vector here as well.
11592
11593     if (!LegalOperations) {
11594       EVT IndexTy = TLI.getVectorIdxTy();
11595       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11596                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11597     }
11598   }
11599
11600   bool BCNumEltsChanged = false;
11601   EVT ExtVT = VT.getVectorElementType();
11602   EVT LVT = ExtVT;
11603
11604   // If the result of load has to be truncated, then it's not necessarily
11605   // profitable.
11606   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11607     return SDValue();
11608
11609   if (InVec.getOpcode() == ISD::BITCAST) {
11610     // Don't duplicate a load with other uses.
11611     if (!InVec.hasOneUse())
11612       return SDValue();
11613
11614     EVT BCVT = InVec.getOperand(0).getValueType();
11615     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11616       return SDValue();
11617     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11618       BCNumEltsChanged = true;
11619     InVec = InVec.getOperand(0);
11620     ExtVT = BCVT.getVectorElementType();
11621   }
11622
11623   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11624   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11625       ISD::isNormalLoad(InVec.getNode()) &&
11626       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11627     SDValue Index = N->getOperand(1);
11628     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11629       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11630                                                            OrigLoad);
11631   }
11632
11633   // Perform only after legalization to ensure build_vector / vector_shuffle
11634   // optimizations have already been done.
11635   if (!LegalOperations) return SDValue();
11636
11637   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11638   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11639   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11640
11641   if (ConstEltNo) {
11642     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11643
11644     LoadSDNode *LN0 = nullptr;
11645     const ShuffleVectorSDNode *SVN = nullptr;
11646     if (ISD::isNormalLoad(InVec.getNode())) {
11647       LN0 = cast<LoadSDNode>(InVec);
11648     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11649                InVec.getOperand(0).getValueType() == ExtVT &&
11650                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11651       // Don't duplicate a load with other uses.
11652       if (!InVec.hasOneUse())
11653         return SDValue();
11654
11655       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11656     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11657       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11658       // =>
11659       // (load $addr+1*size)
11660
11661       // Don't duplicate a load with other uses.
11662       if (!InVec.hasOneUse())
11663         return SDValue();
11664
11665       // If the bit convert changed the number of elements, it is unsafe
11666       // to examine the mask.
11667       if (BCNumEltsChanged)
11668         return SDValue();
11669
11670       // Select the input vector, guarding against out of range extract vector.
11671       unsigned NumElems = VT.getVectorNumElements();
11672       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11673       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11674
11675       if (InVec.getOpcode() == ISD::BITCAST) {
11676         // Don't duplicate a load with other uses.
11677         if (!InVec.hasOneUse())
11678           return SDValue();
11679
11680         InVec = InVec.getOperand(0);
11681       }
11682       if (ISD::isNormalLoad(InVec.getNode())) {
11683         LN0 = cast<LoadSDNode>(InVec);
11684         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11685         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11686       }
11687     }
11688
11689     // Make sure we found a non-volatile load and the extractelement is
11690     // the only use.
11691     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11692       return SDValue();
11693
11694     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11695     if (Elt == -1)
11696       return DAG.getUNDEF(LVT);
11697
11698     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11699   }
11700
11701   return SDValue();
11702 }
11703
11704 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11705 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11706   // We perform this optimization post type-legalization because
11707   // the type-legalizer often scalarizes integer-promoted vectors.
11708   // Performing this optimization before may create bit-casts which
11709   // will be type-legalized to complex code sequences.
11710   // We perform this optimization only before the operation legalizer because we
11711   // may introduce illegal operations.
11712   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11713     return SDValue();
11714
11715   unsigned NumInScalars = N->getNumOperands();
11716   SDLoc dl(N);
11717   EVT VT = N->getValueType(0);
11718
11719   // Check to see if this is a BUILD_VECTOR of a bunch of values
11720   // which come from any_extend or zero_extend nodes. If so, we can create
11721   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11722   // optimizations. We do not handle sign-extend because we can't fill the sign
11723   // using shuffles.
11724   EVT SourceType = MVT::Other;
11725   bool AllAnyExt = true;
11726
11727   for (unsigned i = 0; i != NumInScalars; ++i) {
11728     SDValue In = N->getOperand(i);
11729     // Ignore undef inputs.
11730     if (In.getOpcode() == ISD::UNDEF) continue;
11731
11732     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11733     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11734
11735     // Abort if the element is not an extension.
11736     if (!ZeroExt && !AnyExt) {
11737       SourceType = MVT::Other;
11738       break;
11739     }
11740
11741     // The input is a ZeroExt or AnyExt. Check the original type.
11742     EVT InTy = In.getOperand(0).getValueType();
11743
11744     // Check that all of the widened source types are the same.
11745     if (SourceType == MVT::Other)
11746       // First time.
11747       SourceType = InTy;
11748     else if (InTy != SourceType) {
11749       // Multiple income types. Abort.
11750       SourceType = MVT::Other;
11751       break;
11752     }
11753
11754     // Check if all of the extends are ANY_EXTENDs.
11755     AllAnyExt &= AnyExt;
11756   }
11757
11758   // In order to have valid types, all of the inputs must be extended from the
11759   // same source type and all of the inputs must be any or zero extend.
11760   // Scalar sizes must be a power of two.
11761   EVT OutScalarTy = VT.getScalarType();
11762   bool ValidTypes = SourceType != MVT::Other &&
11763                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11764                  isPowerOf2_32(SourceType.getSizeInBits());
11765
11766   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11767   // turn into a single shuffle instruction.
11768   if (!ValidTypes)
11769     return SDValue();
11770
11771   bool isLE = TLI.isLittleEndian();
11772   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11773   assert(ElemRatio > 1 && "Invalid element size ratio");
11774   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11775                                DAG.getConstant(0, SDLoc(N), SourceType);
11776
11777   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11778   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11779
11780   // Populate the new build_vector
11781   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11782     SDValue Cast = N->getOperand(i);
11783     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11784             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11785             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11786     SDValue In;
11787     if (Cast.getOpcode() == ISD::UNDEF)
11788       In = DAG.getUNDEF(SourceType);
11789     else
11790       In = Cast->getOperand(0);
11791     unsigned Index = isLE ? (i * ElemRatio) :
11792                             (i * ElemRatio + (ElemRatio - 1));
11793
11794     assert(Index < Ops.size() && "Invalid index");
11795     Ops[Index] = In;
11796   }
11797
11798   // The type of the new BUILD_VECTOR node.
11799   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11800   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11801          "Invalid vector size");
11802   // Check if the new vector type is legal.
11803   if (!isTypeLegal(VecVT)) return SDValue();
11804
11805   // Make the new BUILD_VECTOR.
11806   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11807
11808   // The new BUILD_VECTOR node has the potential to be further optimized.
11809   AddToWorklist(BV.getNode());
11810   // Bitcast to the desired type.
11811   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11812 }
11813
11814 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11815   EVT VT = N->getValueType(0);
11816
11817   unsigned NumInScalars = N->getNumOperands();
11818   SDLoc dl(N);
11819
11820   EVT SrcVT = MVT::Other;
11821   unsigned Opcode = ISD::DELETED_NODE;
11822   unsigned NumDefs = 0;
11823
11824   for (unsigned i = 0; i != NumInScalars; ++i) {
11825     SDValue In = N->getOperand(i);
11826     unsigned Opc = In.getOpcode();
11827
11828     if (Opc == ISD::UNDEF)
11829       continue;
11830
11831     // If all scalar values are floats and converted from integers.
11832     if (Opcode == ISD::DELETED_NODE &&
11833         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11834       Opcode = Opc;
11835     }
11836
11837     if (Opc != Opcode)
11838       return SDValue();
11839
11840     EVT InVT = In.getOperand(0).getValueType();
11841
11842     // If all scalar values are typed differently, bail out. It's chosen to
11843     // simplify BUILD_VECTOR of integer types.
11844     if (SrcVT == MVT::Other)
11845       SrcVT = InVT;
11846     if (SrcVT != InVT)
11847       return SDValue();
11848     NumDefs++;
11849   }
11850
11851   // If the vector has just one element defined, it's not worth to fold it into
11852   // a vectorized one.
11853   if (NumDefs < 2)
11854     return SDValue();
11855
11856   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11857          && "Should only handle conversion from integer to float.");
11858   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11859
11860   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11861
11862   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11863     return SDValue();
11864
11865   // Just because the floating-point vector type is legal does not necessarily
11866   // mean that the corresponding integer vector type is.
11867   if (!isTypeLegal(NVT))
11868     return SDValue();
11869
11870   SmallVector<SDValue, 8> Opnds;
11871   for (unsigned i = 0; i != NumInScalars; ++i) {
11872     SDValue In = N->getOperand(i);
11873
11874     if (In.getOpcode() == ISD::UNDEF)
11875       Opnds.push_back(DAG.getUNDEF(SrcVT));
11876     else
11877       Opnds.push_back(In.getOperand(0));
11878   }
11879   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11880   AddToWorklist(BV.getNode());
11881
11882   return DAG.getNode(Opcode, dl, VT, BV);
11883 }
11884
11885 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11886   unsigned NumInScalars = N->getNumOperands();
11887   SDLoc dl(N);
11888   EVT VT = N->getValueType(0);
11889
11890   // A vector built entirely of undefs is undef.
11891   if (ISD::allOperandsUndef(N))
11892     return DAG.getUNDEF(VT);
11893
11894   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11895     return V;
11896
11897   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11898     return V;
11899
11900   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11901   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11902   // at most two distinct vectors, turn this into a shuffle node.
11903
11904   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11905   if (!isTypeLegal(VT))
11906     return SDValue();
11907
11908   // May only combine to shuffle after legalize if shuffle is legal.
11909   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11910     return SDValue();
11911
11912   SDValue VecIn1, VecIn2;
11913   bool UsesZeroVector = false;
11914   for (unsigned i = 0; i != NumInScalars; ++i) {
11915     SDValue Op = N->getOperand(i);
11916     // Ignore undef inputs.
11917     if (Op.getOpcode() == ISD::UNDEF) continue;
11918
11919     // See if we can combine this build_vector into a blend with a zero vector.
11920     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
11921       UsesZeroVector = true;
11922       continue;
11923     }
11924
11925     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11926     // constant index, bail out.
11927     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11928         !isa<ConstantSDNode>(Op.getOperand(1))) {
11929       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11930       break;
11931     }
11932
11933     // We allow up to two distinct input vectors.
11934     SDValue ExtractedFromVec = Op.getOperand(0);
11935     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11936       continue;
11937
11938     if (!VecIn1.getNode()) {
11939       VecIn1 = ExtractedFromVec;
11940     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11941       VecIn2 = ExtractedFromVec;
11942     } else {
11943       // Too many inputs.
11944       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11945       break;
11946     }
11947   }
11948
11949   // If everything is good, we can make a shuffle operation.
11950   if (VecIn1.getNode()) {
11951     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11952     SmallVector<int, 8> Mask;
11953     for (unsigned i = 0; i != NumInScalars; ++i) {
11954       unsigned Opcode = N->getOperand(i).getOpcode();
11955       if (Opcode == ISD::UNDEF) {
11956         Mask.push_back(-1);
11957         continue;
11958       }
11959
11960       // Operands can also be zero.
11961       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11962         assert(UsesZeroVector &&
11963                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11964                "Unexpected node found!");
11965         Mask.push_back(NumInScalars+i);
11966         continue;
11967       }
11968
11969       // If extracting from the first vector, just use the index directly.
11970       SDValue Extract = N->getOperand(i);
11971       SDValue ExtVal = Extract.getOperand(1);
11972       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11973       if (Extract.getOperand(0) == VecIn1) {
11974         Mask.push_back(ExtIndex);
11975         continue;
11976       }
11977
11978       // Otherwise, use InIdx + InputVecSize
11979       Mask.push_back(InNumElements + ExtIndex);
11980     }
11981
11982     // Avoid introducing illegal shuffles with zero.
11983     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11984       return SDValue();
11985
11986     // We can't generate a shuffle node with mismatched input and output types.
11987     // Attempt to transform a single input vector to the correct type.
11988     if ((VT != VecIn1.getValueType())) {
11989       // If the input vector type has a different base type to the output
11990       // vector type, bail out.
11991       EVT VTElemType = VT.getVectorElementType();
11992       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11993           (VecIn2.getNode() &&
11994            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11995         return SDValue();
11996
11997       // If the input vector is too small, widen it.
11998       // We only support widening of vectors which are half the size of the
11999       // output registers. For example XMM->YMM widening on X86 with AVX.
12000       EVT VecInT = VecIn1.getValueType();
12001       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12002         // If we only have one small input, widen it by adding undef values.
12003         if (!VecIn2.getNode())
12004           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12005                                DAG.getUNDEF(VecIn1.getValueType()));
12006         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12007           // If we have two small inputs of the same type, try to concat them.
12008           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12009           VecIn2 = SDValue(nullptr, 0);
12010         } else
12011           return SDValue();
12012       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12013         // If the input vector is too large, try to split it.
12014         // We don't support having two input vectors that are too large.
12015         // If the zero vector was used, we can not split the vector,
12016         // since we'd need 3 inputs.
12017         if (UsesZeroVector || VecIn2.getNode())
12018           return SDValue();
12019
12020         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12021           return SDValue();
12022
12023         // Try to replace VecIn1 with two extract_subvectors
12024         // No need to update the masks, they should still be correct.
12025         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12026           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
12027         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12028           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
12029       } else
12030         return SDValue();
12031     }
12032
12033     if (UsesZeroVector)
12034       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12035                                 DAG.getConstantFP(0.0, dl, VT);
12036     else
12037       // If VecIn2 is unused then change it to undef.
12038       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12039
12040     // Check that we were able to transform all incoming values to the same
12041     // type.
12042     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12043         VecIn1.getValueType() != VT)
12044           return SDValue();
12045
12046     // Return the new VECTOR_SHUFFLE node.
12047     SDValue Ops[2];
12048     Ops[0] = VecIn1;
12049     Ops[1] = VecIn2;
12050     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12051   }
12052
12053   return SDValue();
12054 }
12055
12056 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12057   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12058   EVT OpVT = N->getOperand(0).getValueType();
12059
12060   // If the operands are legal vectors, leave them alone.
12061   if (TLI.isTypeLegal(OpVT))
12062     return SDValue();
12063
12064   SDLoc DL(N);
12065   EVT VT = N->getValueType(0);
12066   SmallVector<SDValue, 8> Ops;
12067
12068   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12069   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12070
12071   // Keep track of what we encounter.
12072   bool AnyInteger = false;
12073   bool AnyFP = false;
12074   for (const SDValue &Op : N->ops()) {
12075     if (ISD::BITCAST == Op.getOpcode() &&
12076         !Op.getOperand(0).getValueType().isVector())
12077       Ops.push_back(Op.getOperand(0));
12078     else if (ISD::UNDEF == Op.getOpcode())
12079       Ops.push_back(ScalarUndef);
12080     else
12081       return SDValue();
12082
12083     // Note whether we encounter an integer or floating point scalar.
12084     // If it's neither, bail out, it could be something weird like x86mmx.
12085     EVT LastOpVT = Ops.back().getValueType();
12086     if (LastOpVT.isFloatingPoint())
12087       AnyFP = true;
12088     else if (LastOpVT.isInteger())
12089       AnyInteger = true;
12090     else
12091       return SDValue();
12092   }
12093
12094   // If any of the operands is a floating point scalar bitcast to a vector,
12095   // use floating point types throughout, and bitcast everything.  
12096   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12097   if (AnyFP) {
12098     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12099     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12100     if (AnyInteger) {
12101       for (SDValue &Op : Ops) {
12102         if (Op.getValueType() == SVT)
12103           continue;
12104         if (Op.getOpcode() == ISD::UNDEF)
12105           Op = ScalarUndef;
12106         else
12107           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12108       }
12109     }
12110   }
12111
12112   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12113                                VT.getSizeInBits() / SVT.getSizeInBits());
12114   return DAG.getNode(ISD::BITCAST, DL, VT,
12115                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12116 }
12117
12118 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12119   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12120   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12121   // inputs come from at most two distinct vectors, turn this into a shuffle
12122   // node.
12123
12124   // If we only have one input vector, we don't need to do any concatenation.
12125   if (N->getNumOperands() == 1)
12126     return N->getOperand(0);
12127
12128   // Check if all of the operands are undefs.
12129   EVT VT = N->getValueType(0);
12130   if (ISD::allOperandsUndef(N))
12131     return DAG.getUNDEF(VT);
12132
12133   // Optimize concat_vectors where all but the first of the vectors are undef.
12134   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12135         return Op.getOpcode() == ISD::UNDEF;
12136       })) {
12137     SDValue In = N->getOperand(0);
12138     assert(In.getValueType().isVector() && "Must concat vectors");
12139
12140     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12141     if (In->getOpcode() == ISD::BITCAST &&
12142         !In->getOperand(0)->getValueType(0).isVector()) {
12143       SDValue Scalar = In->getOperand(0);
12144
12145       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12146       // look through the trunc so we can still do the transform:
12147       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12148       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12149           !TLI.isTypeLegal(Scalar.getValueType()) &&
12150           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12151         Scalar = Scalar->getOperand(0);
12152
12153       EVT SclTy = Scalar->getValueType(0);
12154
12155       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12156         return SDValue();
12157
12158       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12159                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12160       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12161         return SDValue();
12162
12163       SDLoc dl = SDLoc(N);
12164       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12165       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12166     }
12167   }
12168
12169   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12170   // We have already tested above for an UNDEF only concatenation.
12171   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12172   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12173   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12174     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12175   };
12176   bool AllBuildVectorsOrUndefs =
12177       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12178   if (AllBuildVectorsOrUndefs) {
12179     SmallVector<SDValue, 8> Opnds;
12180     EVT SVT = VT.getScalarType();
12181
12182     EVT MinVT = SVT;
12183     if (!SVT.isFloatingPoint()) {
12184       // If BUILD_VECTOR are from built from integer, they may have different
12185       // operand types. Get the smallest type and truncate all operands to it.
12186       bool FoundMinVT = false;
12187       for (const SDValue &Op : N->ops())
12188         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12189           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12190           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12191           FoundMinVT = true;
12192         }
12193       assert(FoundMinVT && "Concat vector type mismatch");
12194     }
12195
12196     for (const SDValue &Op : N->ops()) {
12197       EVT OpVT = Op.getValueType();
12198       unsigned NumElts = OpVT.getVectorNumElements();
12199
12200       if (ISD::UNDEF == Op.getOpcode())
12201         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12202
12203       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12204         if (SVT.isFloatingPoint()) {
12205           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12206           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12207         } else {
12208           for (unsigned i = 0; i != NumElts; ++i)
12209             Opnds.push_back(
12210                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12211         }
12212       }
12213     }
12214
12215     assert(VT.getVectorNumElements() == Opnds.size() &&
12216            "Concat vector type mismatch");
12217     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12218   }
12219
12220   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12221   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12222     return V;
12223
12224   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12225   // nodes often generate nop CONCAT_VECTOR nodes.
12226   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12227   // place the incoming vectors at the exact same location.
12228   SDValue SingleSource = SDValue();
12229   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12230
12231   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12232     SDValue Op = N->getOperand(i);
12233
12234     if (Op.getOpcode() == ISD::UNDEF)
12235       continue;
12236
12237     // Check if this is the identity extract:
12238     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12239       return SDValue();
12240
12241     // Find the single incoming vector for the extract_subvector.
12242     if (SingleSource.getNode()) {
12243       if (Op.getOperand(0) != SingleSource)
12244         return SDValue();
12245     } else {
12246       SingleSource = Op.getOperand(0);
12247
12248       // Check the source type is the same as the type of the result.
12249       // If not, this concat may extend the vector, so we can not
12250       // optimize it away.
12251       if (SingleSource.getValueType() != N->getValueType(0))
12252         return SDValue();
12253     }
12254
12255     unsigned IdentityIndex = i * PartNumElem;
12256     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12257     // The extract index must be constant.
12258     if (!CS)
12259       return SDValue();
12260
12261     // Check that we are reading from the identity index.
12262     if (CS->getZExtValue() != IdentityIndex)
12263       return SDValue();
12264   }
12265
12266   if (SingleSource.getNode())
12267     return SingleSource;
12268
12269   return SDValue();
12270 }
12271
12272 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12273   EVT NVT = N->getValueType(0);
12274   SDValue V = N->getOperand(0);
12275
12276   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12277     // Combine:
12278     //    (extract_subvec (concat V1, V2, ...), i)
12279     // Into:
12280     //    Vi if possible
12281     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12282     // type.
12283     if (V->getOperand(0).getValueType() != NVT)
12284       return SDValue();
12285     unsigned Idx = N->getConstantOperandVal(1);
12286     unsigned NumElems = NVT.getVectorNumElements();
12287     assert((Idx % NumElems) == 0 &&
12288            "IDX in concat is not a multiple of the result vector length.");
12289     return V->getOperand(Idx / NumElems);
12290   }
12291
12292   // Skip bitcasting
12293   if (V->getOpcode() == ISD::BITCAST)
12294     V = V.getOperand(0);
12295
12296   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12297     SDLoc dl(N);
12298     // Handle only simple case where vector being inserted and vector
12299     // being extracted are of same type, and are half size of larger vectors.
12300     EVT BigVT = V->getOperand(0).getValueType();
12301     EVT SmallVT = V->getOperand(1).getValueType();
12302     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12303       return SDValue();
12304
12305     // Only handle cases where both indexes are constants with the same type.
12306     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12307     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12308
12309     if (InsIdx && ExtIdx &&
12310         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12311         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12312       // Combine:
12313       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12314       // Into:
12315       //    indices are equal or bit offsets are equal => V1
12316       //    otherwise => (extract_subvec V1, ExtIdx)
12317       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12318           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12319         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12320       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12321                          DAG.getNode(ISD::BITCAST, dl,
12322                                      N->getOperand(0).getValueType(),
12323                                      V->getOperand(0)), N->getOperand(1));
12324     }
12325   }
12326
12327   return SDValue();
12328 }
12329
12330 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12331                                                  SDValue V, SelectionDAG &DAG) {
12332   SDLoc DL(V);
12333   EVT VT = V.getValueType();
12334
12335   switch (V.getOpcode()) {
12336   default:
12337     return V;
12338
12339   case ISD::CONCAT_VECTORS: {
12340     EVT OpVT = V->getOperand(0).getValueType();
12341     int OpSize = OpVT.getVectorNumElements();
12342     SmallBitVector OpUsedElements(OpSize, false);
12343     bool FoundSimplification = false;
12344     SmallVector<SDValue, 4> NewOps;
12345     NewOps.reserve(V->getNumOperands());
12346     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12347       SDValue Op = V->getOperand(i);
12348       bool OpUsed = false;
12349       for (int j = 0; j < OpSize; ++j)
12350         if (UsedElements[i * OpSize + j]) {
12351           OpUsedElements[j] = true;
12352           OpUsed = true;
12353         }
12354       NewOps.push_back(
12355           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12356                  : DAG.getUNDEF(OpVT));
12357       FoundSimplification |= Op == NewOps.back();
12358       OpUsedElements.reset();
12359     }
12360     if (FoundSimplification)
12361       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12362     return V;
12363   }
12364
12365   case ISD::INSERT_SUBVECTOR: {
12366     SDValue BaseV = V->getOperand(0);
12367     SDValue SubV = V->getOperand(1);
12368     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12369     if (!IdxN)
12370       return V;
12371
12372     int SubSize = SubV.getValueType().getVectorNumElements();
12373     int Idx = IdxN->getZExtValue();
12374     bool SubVectorUsed = false;
12375     SmallBitVector SubUsedElements(SubSize, false);
12376     for (int i = 0; i < SubSize; ++i)
12377       if (UsedElements[i + Idx]) {
12378         SubVectorUsed = true;
12379         SubUsedElements[i] = true;
12380         UsedElements[i + Idx] = false;
12381       }
12382
12383     // Now recurse on both the base and sub vectors.
12384     SDValue SimplifiedSubV =
12385         SubVectorUsed
12386             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12387             : DAG.getUNDEF(SubV.getValueType());
12388     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12389     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12390       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12391                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12392     return V;
12393   }
12394   }
12395 }
12396
12397 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12398                                        SDValue N1, SelectionDAG &DAG) {
12399   EVT VT = SVN->getValueType(0);
12400   int NumElts = VT.getVectorNumElements();
12401   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12402   for (int M : SVN->getMask())
12403     if (M >= 0 && M < NumElts)
12404       N0UsedElements[M] = true;
12405     else if (M >= NumElts)
12406       N1UsedElements[M - NumElts] = true;
12407
12408   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12409   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12410   if (S0 == N0 && S1 == N1)
12411     return SDValue();
12412
12413   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12414 }
12415
12416 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12417 // or turn a shuffle of a single concat into simpler shuffle then concat.
12418 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12419   EVT VT = N->getValueType(0);
12420   unsigned NumElts = VT.getVectorNumElements();
12421
12422   SDValue N0 = N->getOperand(0);
12423   SDValue N1 = N->getOperand(1);
12424   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12425
12426   SmallVector<SDValue, 4> Ops;
12427   EVT ConcatVT = N0.getOperand(0).getValueType();
12428   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12429   unsigned NumConcats = NumElts / NumElemsPerConcat;
12430
12431   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12432   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12433   // half vector elements.
12434   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12435       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12436                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12437     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12438                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12439     N1 = DAG.getUNDEF(ConcatVT);
12440     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12441   }
12442
12443   // Look at every vector that's inserted. We're looking for exact
12444   // subvector-sized copies from a concatenated vector
12445   for (unsigned I = 0; I != NumConcats; ++I) {
12446     // Make sure we're dealing with a copy.
12447     unsigned Begin = I * NumElemsPerConcat;
12448     bool AllUndef = true, NoUndef = true;
12449     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12450       if (SVN->getMaskElt(J) >= 0)
12451         AllUndef = false;
12452       else
12453         NoUndef = false;
12454     }
12455
12456     if (NoUndef) {
12457       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12458         return SDValue();
12459
12460       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12461         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12462           return SDValue();
12463
12464       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12465       if (FirstElt < N0.getNumOperands())
12466         Ops.push_back(N0.getOperand(FirstElt));
12467       else
12468         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12469
12470     } else if (AllUndef) {
12471       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12472     } else { // Mixed with general masks and undefs, can't do optimization.
12473       return SDValue();
12474     }
12475   }
12476
12477   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12478 }
12479
12480 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12481   EVT VT = N->getValueType(0);
12482   unsigned NumElts = VT.getVectorNumElements();
12483
12484   SDValue N0 = N->getOperand(0);
12485   SDValue N1 = N->getOperand(1);
12486
12487   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12488
12489   // Canonicalize shuffle undef, undef -> undef
12490   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12491     return DAG.getUNDEF(VT);
12492
12493   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12494
12495   // Canonicalize shuffle v, v -> v, undef
12496   if (N0 == N1) {
12497     SmallVector<int, 8> NewMask;
12498     for (unsigned i = 0; i != NumElts; ++i) {
12499       int Idx = SVN->getMaskElt(i);
12500       if (Idx >= (int)NumElts) Idx -= NumElts;
12501       NewMask.push_back(Idx);
12502     }
12503     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12504                                 &NewMask[0]);
12505   }
12506
12507   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12508   if (N0.getOpcode() == ISD::UNDEF) {
12509     SmallVector<int, 8> NewMask;
12510     for (unsigned i = 0; i != NumElts; ++i) {
12511       int Idx = SVN->getMaskElt(i);
12512       if (Idx >= 0) {
12513         if (Idx >= (int)NumElts)
12514           Idx -= NumElts;
12515         else
12516           Idx = -1; // remove reference to lhs
12517       }
12518       NewMask.push_back(Idx);
12519     }
12520     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12521                                 &NewMask[0]);
12522   }
12523
12524   // Remove references to rhs if it is undef
12525   if (N1.getOpcode() == ISD::UNDEF) {
12526     bool Changed = false;
12527     SmallVector<int, 8> NewMask;
12528     for (unsigned i = 0; i != NumElts; ++i) {
12529       int Idx = SVN->getMaskElt(i);
12530       if (Idx >= (int)NumElts) {
12531         Idx = -1;
12532         Changed = true;
12533       }
12534       NewMask.push_back(Idx);
12535     }
12536     if (Changed)
12537       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12538   }
12539
12540   // If it is a splat, check if the argument vector is another splat or a
12541   // build_vector.
12542   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12543     SDNode *V = N0.getNode();
12544
12545     // If this is a bit convert that changes the element type of the vector but
12546     // not the number of vector elements, look through it.  Be careful not to
12547     // look though conversions that change things like v4f32 to v2f64.
12548     if (V->getOpcode() == ISD::BITCAST) {
12549       SDValue ConvInput = V->getOperand(0);
12550       if (ConvInput.getValueType().isVector() &&
12551           ConvInput.getValueType().getVectorNumElements() == NumElts)
12552         V = ConvInput.getNode();
12553     }
12554
12555     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12556       assert(V->getNumOperands() == NumElts &&
12557              "BUILD_VECTOR has wrong number of operands");
12558       SDValue Base;
12559       bool AllSame = true;
12560       for (unsigned i = 0; i != NumElts; ++i) {
12561         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12562           Base = V->getOperand(i);
12563           break;
12564         }
12565       }
12566       // Splat of <u, u, u, u>, return <u, u, u, u>
12567       if (!Base.getNode())
12568         return N0;
12569       for (unsigned i = 0; i != NumElts; ++i) {
12570         if (V->getOperand(i) != Base) {
12571           AllSame = false;
12572           break;
12573         }
12574       }
12575       // Splat of <x, x, x, x>, return <x, x, x, x>
12576       if (AllSame)
12577         return N0;
12578
12579       // Canonicalize any other splat as a build_vector.
12580       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12581       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12582       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12583                                   V->getValueType(0), Ops);
12584
12585       // We may have jumped through bitcasts, so the type of the
12586       // BUILD_VECTOR may not match the type of the shuffle.
12587       if (V->getValueType(0) != VT)
12588         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12589       return NewBV;
12590     }
12591   }
12592
12593   // There are various patterns used to build up a vector from smaller vectors,
12594   // subvectors, or elements. Scan chains of these and replace unused insertions
12595   // or components with undef.
12596   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12597     return S;
12598
12599   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12600       Level < AfterLegalizeVectorOps &&
12601       (N1.getOpcode() == ISD::UNDEF ||
12602       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12603        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12604     SDValue V = partitionShuffleOfConcats(N, DAG);
12605
12606     if (V.getNode())
12607       return V;
12608   }
12609
12610   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12611   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12612   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12613     SmallVector<SDValue, 8> Ops;
12614     for (int M : SVN->getMask()) {
12615       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12616       if (M >= 0) {
12617         int Idx = M % NumElts;
12618         SDValue &S = (M < (int)NumElts ? N0 : N1);
12619         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12620           Op = S.getOperand(Idx);
12621         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12622           if (Idx == 0)
12623             Op = S.getOperand(0);
12624         } else {
12625           // Operand can't be combined - bail out.
12626           break;
12627         }
12628       }
12629       Ops.push_back(Op);
12630     }
12631     if (Ops.size() == VT.getVectorNumElements()) {
12632       // BUILD_VECTOR requires all inputs to be of the same type, find the
12633       // maximum type and extend them all.
12634       EVT SVT = VT.getScalarType();
12635       if (SVT.isInteger())
12636         for (SDValue &Op : Ops)
12637           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12638       if (SVT != VT.getScalarType())
12639         for (SDValue &Op : Ops)
12640           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12641                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12642                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12643       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12644     }
12645   }
12646
12647   // If this shuffle only has a single input that is a bitcasted shuffle,
12648   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12649   // back to their original types.
12650   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12651       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12652       TLI.isTypeLegal(VT)) {
12653
12654     // Peek through the bitcast only if there is one user.
12655     SDValue BC0 = N0;
12656     while (BC0.getOpcode() == ISD::BITCAST) {
12657       if (!BC0.hasOneUse())
12658         break;
12659       BC0 = BC0.getOperand(0);
12660     }
12661
12662     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12663       if (Scale == 1)
12664         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12665
12666       SmallVector<int, 8> NewMask;
12667       for (int M : Mask)
12668         for (int s = 0; s != Scale; ++s)
12669           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12670       return NewMask;
12671     };
12672
12673     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12674       EVT SVT = VT.getScalarType();
12675       EVT InnerVT = BC0->getValueType(0);
12676       EVT InnerSVT = InnerVT.getScalarType();
12677
12678       // Determine which shuffle works with the smaller scalar type.
12679       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12680       EVT ScaleSVT = ScaleVT.getScalarType();
12681
12682       if (TLI.isTypeLegal(ScaleVT) &&
12683           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12684           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12685
12686         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12687         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12688
12689         // Scale the shuffle masks to the smaller scalar type.
12690         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12691         SmallVector<int, 8> InnerMask =
12692             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12693         SmallVector<int, 8> OuterMask =
12694             ScaleShuffleMask(SVN->getMask(), OuterScale);
12695
12696         // Merge the shuffle masks.
12697         SmallVector<int, 8> NewMask;
12698         for (int M : OuterMask)
12699           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12700
12701         // Test for shuffle mask legality over both commutations.
12702         SDValue SV0 = BC0->getOperand(0);
12703         SDValue SV1 = BC0->getOperand(1);
12704         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12705         if (!LegalMask) {
12706           std::swap(SV0, SV1);
12707           ShuffleVectorSDNode::commuteMask(NewMask);
12708           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12709         }
12710
12711         if (LegalMask) {
12712           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12713           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12714           return DAG.getNode(
12715               ISD::BITCAST, SDLoc(N), VT,
12716               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12717         }
12718       }
12719     }
12720   }
12721
12722   // Canonicalize shuffles according to rules:
12723   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12724   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12725   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12726   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12727       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12728       TLI.isTypeLegal(VT)) {
12729     // The incoming shuffle must be of the same type as the result of the
12730     // current shuffle.
12731     assert(N1->getOperand(0).getValueType() == VT &&
12732            "Shuffle types don't match");
12733
12734     SDValue SV0 = N1->getOperand(0);
12735     SDValue SV1 = N1->getOperand(1);
12736     bool HasSameOp0 = N0 == SV0;
12737     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12738     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12739       // Commute the operands of this shuffle so that next rule
12740       // will trigger.
12741       return DAG.getCommutedVectorShuffle(*SVN);
12742   }
12743
12744   // Try to fold according to rules:
12745   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12746   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12747   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12748   // Don't try to fold shuffles with illegal type.
12749   // Only fold if this shuffle is the only user of the other shuffle.
12750   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12751       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12752     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12753
12754     // The incoming shuffle must be of the same type as the result of the
12755     // current shuffle.
12756     assert(OtherSV->getOperand(0).getValueType() == VT &&
12757            "Shuffle types don't match");
12758
12759     SDValue SV0, SV1;
12760     SmallVector<int, 4> Mask;
12761     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12762     // operand, and SV1 as the second operand.
12763     for (unsigned i = 0; i != NumElts; ++i) {
12764       int Idx = SVN->getMaskElt(i);
12765       if (Idx < 0) {
12766         // Propagate Undef.
12767         Mask.push_back(Idx);
12768         continue;
12769       }
12770
12771       SDValue CurrentVec;
12772       if (Idx < (int)NumElts) {
12773         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12774         // shuffle mask to identify which vector is actually referenced.
12775         Idx = OtherSV->getMaskElt(Idx);
12776         if (Idx < 0) {
12777           // Propagate Undef.
12778           Mask.push_back(Idx);
12779           continue;
12780         }
12781
12782         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12783                                            : OtherSV->getOperand(1);
12784       } else {
12785         // This shuffle index references an element within N1.
12786         CurrentVec = N1;
12787       }
12788
12789       // Simple case where 'CurrentVec' is UNDEF.
12790       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12791         Mask.push_back(-1);
12792         continue;
12793       }
12794
12795       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12796       // will be the first or second operand of the combined shuffle.
12797       Idx = Idx % NumElts;
12798       if (!SV0.getNode() || SV0 == CurrentVec) {
12799         // Ok. CurrentVec is the left hand side.
12800         // Update the mask accordingly.
12801         SV0 = CurrentVec;
12802         Mask.push_back(Idx);
12803         continue;
12804       }
12805
12806       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12807       if (SV1.getNode() && SV1 != CurrentVec)
12808         return SDValue();
12809
12810       // Ok. CurrentVec is the right hand side.
12811       // Update the mask accordingly.
12812       SV1 = CurrentVec;
12813       Mask.push_back(Idx + NumElts);
12814     }
12815
12816     // Check if all indices in Mask are Undef. In case, propagate Undef.
12817     bool isUndefMask = true;
12818     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12819       isUndefMask &= Mask[i] < 0;
12820
12821     if (isUndefMask)
12822       return DAG.getUNDEF(VT);
12823
12824     if (!SV0.getNode())
12825       SV0 = DAG.getUNDEF(VT);
12826     if (!SV1.getNode())
12827       SV1 = DAG.getUNDEF(VT);
12828
12829     // Avoid introducing shuffles with illegal mask.
12830     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12831       ShuffleVectorSDNode::commuteMask(Mask);
12832
12833       if (!TLI.isShuffleMaskLegal(Mask, VT))
12834         return SDValue();
12835
12836       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12837       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12838       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12839       std::swap(SV0, SV1);
12840     }
12841
12842     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12843     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12844     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12845     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12846   }
12847
12848   return SDValue();
12849 }
12850
12851 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12852   SDValue InVal = N->getOperand(0);
12853   EVT VT = N->getValueType(0);
12854
12855   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12856   // with a VECTOR_SHUFFLE.
12857   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12858     SDValue InVec = InVal->getOperand(0);
12859     SDValue EltNo = InVal->getOperand(1);
12860
12861     // FIXME: We could support implicit truncation if the shuffle can be
12862     // scaled to a smaller vector scalar type.
12863     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12864     if (C0 && VT == InVec.getValueType() &&
12865         VT.getScalarType() == InVal.getValueType()) {
12866       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12867       int Elt = C0->getZExtValue();
12868       NewMask[0] = Elt;
12869
12870       if (TLI.isShuffleMaskLegal(NewMask, VT))
12871         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12872                                     NewMask);
12873     }
12874   }
12875
12876   return SDValue();
12877 }
12878
12879 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12880   SDValue N0 = N->getOperand(0);
12881   SDValue N2 = N->getOperand(2);
12882
12883   // If the input vector is a concatenation, and the insert replaces
12884   // one of the halves, we can optimize into a single concat_vectors.
12885   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12886       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12887     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12888     EVT VT = N->getValueType(0);
12889
12890     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12891     // (concat_vectors Z, Y)
12892     if (InsIdx == 0)
12893       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12894                          N->getOperand(1), N0.getOperand(1));
12895
12896     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12897     // (concat_vectors X, Z)
12898     if (InsIdx == VT.getVectorNumElements()/2)
12899       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12900                          N0.getOperand(0), N->getOperand(1));
12901   }
12902
12903   return SDValue();
12904 }
12905
12906 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12907   SDValue N0 = N->getOperand(0);
12908
12909   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12910   if (N0->getOpcode() == ISD::FP16_TO_FP)
12911     return N0->getOperand(0);
12912
12913   return SDValue();
12914 }
12915
12916 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12917 /// with the destination vector and a zero vector.
12918 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12919 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12920 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12921   EVT VT = N->getValueType(0);
12922   SDValue LHS = N->getOperand(0);
12923   SDValue RHS = N->getOperand(1);
12924   SDLoc dl(N);
12925
12926   // Make sure we're not running after operation legalization where it 
12927   // may have custom lowered the vector shuffles.
12928   if (LegalOperations)
12929     return SDValue();
12930
12931   if (N->getOpcode() != ISD::AND)
12932     return SDValue();
12933
12934   if (RHS.getOpcode() == ISD::BITCAST)
12935     RHS = RHS.getOperand(0);
12936
12937   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12938     SmallVector<int, 8> Indices;
12939     unsigned NumElts = RHS.getNumOperands();
12940
12941     for (unsigned i = 0; i != NumElts; ++i) {
12942       SDValue Elt = RHS.getOperand(i);
12943       if (isAllOnesConstant(Elt))
12944         Indices.push_back(i);
12945       else if (isNullConstant(Elt))
12946         Indices.push_back(NumElts+i);
12947       else
12948         return SDValue();
12949     }
12950
12951     // Let's see if the target supports this vector_shuffle.
12952     EVT RVT = RHS.getValueType();
12953     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12954       return SDValue();
12955
12956     // Return the new VECTOR_SHUFFLE node.
12957     EVT EltVT = RVT.getVectorElementType();
12958     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12959                                    DAG.getConstant(0, dl, EltVT));
12960     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12961     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12962     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12963     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12964   }
12965
12966   return SDValue();
12967 }
12968
12969 /// Visit a binary vector operation, like ADD.
12970 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12971   assert(N->getValueType(0).isVector() &&
12972          "SimplifyVBinOp only works on vectors!");
12973
12974   SDValue LHS = N->getOperand(0);
12975   SDValue RHS = N->getOperand(1);
12976
12977   if (SDValue Shuffle = XformToShuffleWithZero(N))
12978     return Shuffle;
12979
12980   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12981   // this operation.
12982   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12983       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12984     // Check if both vectors are constants. If not bail out.
12985     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12986           cast<BuildVectorSDNode>(RHS)->isConstant()))
12987       return SDValue();
12988
12989     SmallVector<SDValue, 8> Ops;
12990     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12991       SDValue LHSOp = LHS.getOperand(i);
12992       SDValue RHSOp = RHS.getOperand(i);
12993
12994       // Can't fold divide by zero.
12995       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12996           N->getOpcode() == ISD::FDIV) {
12997         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
12998              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12999           break;
13000       }
13001
13002       EVT VT = LHSOp.getValueType();
13003       EVT RVT = RHSOp.getValueType();
13004       if (RVT != VT) {
13005         // Integer BUILD_VECTOR operands may have types larger than the element
13006         // size (e.g., when the element type is not legal).  Prior to type
13007         // legalization, the types may not match between the two BUILD_VECTORS.
13008         // Truncate one of the operands to make them match.
13009         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13010           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13011         } else {
13012           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13013           VT = RVT;
13014         }
13015       }
13016       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13017                                    LHSOp, RHSOp);
13018       if (FoldOp.getOpcode() != ISD::UNDEF &&
13019           FoldOp.getOpcode() != ISD::Constant &&
13020           FoldOp.getOpcode() != ISD::ConstantFP)
13021         break;
13022       Ops.push_back(FoldOp);
13023       AddToWorklist(FoldOp.getNode());
13024     }
13025
13026     if (Ops.size() == LHS.getNumOperands())
13027       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13028   }
13029
13030   // Type legalization might introduce new shuffles in the DAG.
13031   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13032   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13033   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13034       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13035       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13036       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13037     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13038     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13039
13040     if (SVN0->getMask().equals(SVN1->getMask())) {
13041       EVT VT = N->getValueType(0);
13042       SDValue UndefVector = LHS.getOperand(1);
13043       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13044                                      LHS.getOperand(0), RHS.getOperand(0));
13045       AddUsersToWorklist(N);
13046       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13047                                   &SVN0->getMask()[0]);
13048     }
13049   }
13050
13051   return SDValue();
13052 }
13053
13054 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13055                                     SDValue N1, SDValue N2){
13056   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13057
13058   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13059                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13060
13061   // If we got a simplified select_cc node back from SimplifySelectCC, then
13062   // break it down into a new SETCC node, and a new SELECT node, and then return
13063   // the SELECT node, since we were called with a SELECT node.
13064   if (SCC.getNode()) {
13065     // Check to see if we got a select_cc back (to turn into setcc/select).
13066     // Otherwise, just return whatever node we got back, like fabs.
13067     if (SCC.getOpcode() == ISD::SELECT_CC) {
13068       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13069                                   N0.getValueType(),
13070                                   SCC.getOperand(0), SCC.getOperand(1),
13071                                   SCC.getOperand(4));
13072       AddToWorklist(SETCC.getNode());
13073       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13074                            SCC.getOperand(2), SCC.getOperand(3));
13075     }
13076
13077     return SCC;
13078   }
13079   return SDValue();
13080 }
13081
13082 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13083 /// being selected between, see if we can simplify the select.  Callers of this
13084 /// should assume that TheSelect is deleted if this returns true.  As such, they
13085 /// should return the appropriate thing (e.g. the node) back to the top-level of
13086 /// the DAG combiner loop to avoid it being looked at.
13087 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13088                                     SDValue RHS) {
13089
13090   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13091   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13092   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13093     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13094       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13095       SDValue Sqrt = RHS;
13096       ISD::CondCode CC;
13097       SDValue CmpLHS;
13098       const ConstantFPSDNode *NegZero = nullptr;
13099
13100       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13101         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13102         CmpLHS = TheSelect->getOperand(0);
13103         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13104       } else {
13105         // SELECT or VSELECT
13106         SDValue Cmp = TheSelect->getOperand(0);
13107         if (Cmp.getOpcode() == ISD::SETCC) {
13108           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13109           CmpLHS = Cmp.getOperand(0);
13110           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13111         }
13112       }
13113       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13114           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13115           CC == ISD::SETULT || CC == ISD::SETLT)) {
13116         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13117         CombineTo(TheSelect, Sqrt);
13118         return true;
13119       }
13120     }
13121   }
13122   // Cannot simplify select with vector condition
13123   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13124
13125   // If this is a select from two identical things, try to pull the operation
13126   // through the select.
13127   if (LHS.getOpcode() != RHS.getOpcode() ||
13128       !LHS.hasOneUse() || !RHS.hasOneUse())
13129     return false;
13130
13131   // If this is a load and the token chain is identical, replace the select
13132   // of two loads with a load through a select of the address to load from.
13133   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13134   // constants have been dropped into the constant pool.
13135   if (LHS.getOpcode() == ISD::LOAD) {
13136     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13137     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13138
13139     // Token chains must be identical.
13140     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13141         // Do not let this transformation reduce the number of volatile loads.
13142         LLD->isVolatile() || RLD->isVolatile() ||
13143         // FIXME: If either is a pre/post inc/dec load,
13144         // we'd need to split out the address adjustment.
13145         LLD->isIndexed() || RLD->isIndexed() ||
13146         // If this is an EXTLOAD, the VT's must match.
13147         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13148         // If this is an EXTLOAD, the kind of extension must match.
13149         (LLD->getExtensionType() != RLD->getExtensionType() &&
13150          // The only exception is if one of the extensions is anyext.
13151          LLD->getExtensionType() != ISD::EXTLOAD &&
13152          RLD->getExtensionType() != ISD::EXTLOAD) ||
13153         // FIXME: this discards src value information.  This is
13154         // over-conservative. It would be beneficial to be able to remember
13155         // both potential memory locations.  Since we are discarding
13156         // src value info, don't do the transformation if the memory
13157         // locations are not in the default address space.
13158         LLD->getPointerInfo().getAddrSpace() != 0 ||
13159         RLD->getPointerInfo().getAddrSpace() != 0 ||
13160         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13161                                       LLD->getBasePtr().getValueType()))
13162       return false;
13163
13164     // Check that the select condition doesn't reach either load.  If so,
13165     // folding this will induce a cycle into the DAG.  If not, this is safe to
13166     // xform, so create a select of the addresses.
13167     SDValue Addr;
13168     if (TheSelect->getOpcode() == ISD::SELECT) {
13169       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13170       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13171           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13172         return false;
13173       // The loads must not depend on one another.
13174       if (LLD->isPredecessorOf(RLD) ||
13175           RLD->isPredecessorOf(LLD))
13176         return false;
13177       Addr = DAG.getSelect(SDLoc(TheSelect),
13178                            LLD->getBasePtr().getValueType(),
13179                            TheSelect->getOperand(0), LLD->getBasePtr(),
13180                            RLD->getBasePtr());
13181     } else {  // Otherwise SELECT_CC
13182       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13183       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13184
13185       if ((LLD->hasAnyUseOfValue(1) &&
13186            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13187           (RLD->hasAnyUseOfValue(1) &&
13188            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13189         return false;
13190
13191       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13192                          LLD->getBasePtr().getValueType(),
13193                          TheSelect->getOperand(0),
13194                          TheSelect->getOperand(1),
13195                          LLD->getBasePtr(), RLD->getBasePtr(),
13196                          TheSelect->getOperand(4));
13197     }
13198
13199     SDValue Load;
13200     // It is safe to replace the two loads if they have different alignments,
13201     // but the new load must be the minimum (most restrictive) alignment of the
13202     // inputs.
13203     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13204     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13205     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13206       Load = DAG.getLoad(TheSelect->getValueType(0),
13207                          SDLoc(TheSelect),
13208                          // FIXME: Discards pointer and AA info.
13209                          LLD->getChain(), Addr, MachinePointerInfo(),
13210                          LLD->isVolatile(), LLD->isNonTemporal(),
13211                          isInvariant, Alignment);
13212     } else {
13213       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13214                             RLD->getExtensionType() : LLD->getExtensionType(),
13215                             SDLoc(TheSelect),
13216                             TheSelect->getValueType(0),
13217                             // FIXME: Discards pointer and AA info.
13218                             LLD->getChain(), Addr, MachinePointerInfo(),
13219                             LLD->getMemoryVT(), LLD->isVolatile(),
13220                             LLD->isNonTemporal(), isInvariant, Alignment);
13221     }
13222
13223     // Users of the select now use the result of the load.
13224     CombineTo(TheSelect, Load);
13225
13226     // Users of the old loads now use the new load's chain.  We know the
13227     // old-load value is dead now.
13228     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13229     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13230     return true;
13231   }
13232
13233   return false;
13234 }
13235
13236 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13237 /// where 'cond' is the comparison specified by CC.
13238 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13239                                       SDValue N2, SDValue N3,
13240                                       ISD::CondCode CC, bool NotExtCompare) {
13241   // (x ? y : y) -> y.
13242   if (N2 == N3) return N2;
13243
13244   EVT VT = N2.getValueType();
13245   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13246   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13247
13248   // Determine if the condition we're dealing with is constant
13249   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13250                               N0, N1, CC, DL, false);
13251   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13252
13253   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13254     // fold select_cc true, x, y -> x
13255     // fold select_cc false, x, y -> y
13256     return !SCCC->isNullValue() ? N2 : N3;
13257   }
13258
13259   // Check to see if we can simplify the select into an fabs node
13260   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13261     // Allow either -0.0 or 0.0
13262     if (CFP->getValueAPF().isZero()) {
13263       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13264       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13265           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13266           N2 == N3.getOperand(0))
13267         return DAG.getNode(ISD::FABS, DL, VT, N0);
13268
13269       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13270       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13271           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13272           N2.getOperand(0) == N3)
13273         return DAG.getNode(ISD::FABS, DL, VT, N3);
13274     }
13275   }
13276
13277   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13278   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13279   // in it.  This is a win when the constant is not otherwise available because
13280   // it replaces two constant pool loads with one.  We only do this if the FP
13281   // type is known to be legal, because if it isn't, then we are before legalize
13282   // types an we want the other legalization to happen first (e.g. to avoid
13283   // messing with soft float) and if the ConstantFP is not legal, because if
13284   // it is legal, we may not need to store the FP constant in a constant pool.
13285   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13286     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13287       if (TLI.isTypeLegal(N2.getValueType()) &&
13288           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13289                TargetLowering::Legal &&
13290            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13291            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13292           // If both constants have multiple uses, then we won't need to do an
13293           // extra load, they are likely around in registers for other users.
13294           (TV->hasOneUse() || FV->hasOneUse())) {
13295         Constant *Elts[] = {
13296           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13297           const_cast<ConstantFP*>(TV->getConstantFPValue())
13298         };
13299         Type *FPTy = Elts[0]->getType();
13300         const DataLayout &TD = *TLI.getDataLayout();
13301
13302         // Create a ConstantArray of the two constants.
13303         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13304         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13305                                             TD.getPrefTypeAlignment(FPTy));
13306         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13307
13308         // Get the offsets to the 0 and 1 element of the array so that we can
13309         // select between them.
13310         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13311         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13312         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13313
13314         SDValue Cond = DAG.getSetCC(DL,
13315                                     getSetCCResultType(N0.getValueType()),
13316                                     N0, N1, CC);
13317         AddToWorklist(Cond.getNode());
13318         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13319                                           Cond, One, Zero);
13320         AddToWorklist(CstOffset.getNode());
13321         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13322                             CstOffset);
13323         AddToWorklist(CPIdx.getNode());
13324         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13325                            MachinePointerInfo::getConstantPool(), false,
13326                            false, false, Alignment);
13327       }
13328     }
13329
13330   // Check to see if we can perform the "gzip trick", transforming
13331   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13332   if (isNullConstant(N3) && CC == ISD::SETLT &&
13333       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13334        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13335     EVT XType = N0.getValueType();
13336     EVT AType = N2.getValueType();
13337     if (XType.bitsGE(AType)) {
13338       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13339       // single-bit constant.
13340       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13341         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13342         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13343         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13344                                        getShiftAmountTy(N0.getValueType()));
13345         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13346                                     XType, N0, ShCt);
13347         AddToWorklist(Shift.getNode());
13348
13349         if (XType.bitsGT(AType)) {
13350           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13351           AddToWorklist(Shift.getNode());
13352         }
13353
13354         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13355       }
13356
13357       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13358                                   XType, N0,
13359                                   DAG.getConstant(XType.getSizeInBits() - 1,
13360                                                   SDLoc(N0),
13361                                          getShiftAmountTy(N0.getValueType())));
13362       AddToWorklist(Shift.getNode());
13363
13364       if (XType.bitsGT(AType)) {
13365         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13366         AddToWorklist(Shift.getNode());
13367       }
13368
13369       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13370     }
13371   }
13372
13373   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13374   // where y is has a single bit set.
13375   // A plaintext description would be, we can turn the SELECT_CC into an AND
13376   // when the condition can be materialized as an all-ones register.  Any
13377   // single bit-test can be materialized as an all-ones register with
13378   // shift-left and shift-right-arith.
13379   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13380       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13381     SDValue AndLHS = N0->getOperand(0);
13382     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13383     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13384       // Shift the tested bit over the sign bit.
13385       APInt AndMask = ConstAndRHS->getAPIntValue();
13386       SDValue ShlAmt =
13387         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13388                         getShiftAmountTy(AndLHS.getValueType()));
13389       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13390
13391       // Now arithmetic right shift it all the way over, so the result is either
13392       // all-ones, or zero.
13393       SDValue ShrAmt =
13394         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13395                         getShiftAmountTy(Shl.getValueType()));
13396       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13397
13398       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13399     }
13400   }
13401
13402   // fold select C, 16, 0 -> shl C, 4
13403   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13404       TLI.getBooleanContents(N0.getValueType()) ==
13405           TargetLowering::ZeroOrOneBooleanContent) {
13406
13407     // If the caller doesn't want us to simplify this into a zext of a compare,
13408     // don't do it.
13409     if (NotExtCompare && N2C->isOne())
13410       return SDValue();
13411
13412     // Get a SetCC of the condition
13413     // NOTE: Don't create a SETCC if it's not legal on this target.
13414     if (!LegalOperations ||
13415         TLI.isOperationLegal(ISD::SETCC,
13416           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13417       SDValue Temp, SCC;
13418       // cast from setcc result type to select result type
13419       if (LegalTypes) {
13420         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13421                             N0, N1, CC);
13422         if (N2.getValueType().bitsLT(SCC.getValueType()))
13423           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13424                                         N2.getValueType());
13425         else
13426           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13427                              N2.getValueType(), SCC);
13428       } else {
13429         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13430         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13431                            N2.getValueType(), SCC);
13432       }
13433
13434       AddToWorklist(SCC.getNode());
13435       AddToWorklist(Temp.getNode());
13436
13437       if (N2C->isOne())
13438         return Temp;
13439
13440       // shl setcc result by log2 n2c
13441       return DAG.getNode(
13442           ISD::SHL, DL, N2.getValueType(), Temp,
13443           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13444                           getShiftAmountTy(Temp.getValueType())));
13445     }
13446   }
13447
13448   // Check to see if this is the equivalent of setcc
13449   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13450   // otherwise, go ahead with the folds.
13451   if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13452     EVT XType = N0.getValueType();
13453     if (!LegalOperations ||
13454         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13455       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13456       if (Res.getValueType() != VT)
13457         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13458       return Res;
13459     }
13460
13461     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13462     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13463         (!LegalOperations ||
13464          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13465       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13466       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13467                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13468                                          SDLoc(Ctlz),
13469                                        getShiftAmountTy(Ctlz.getValueType())));
13470     }
13471     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13472     if (isNullConstant(N1) && CC == ISD::SETGT) {
13473       SDLoc DL(N0);
13474       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13475                                   XType, DAG.getConstant(0, DL, XType), N0);
13476       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13477       return DAG.getNode(ISD::SRL, DL, XType,
13478                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13479                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13480                                          getShiftAmountTy(XType)));
13481     }
13482     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13483     if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13484       SDLoc DL(N0);
13485       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13486                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13487                                          getShiftAmountTy(N0.getValueType())));
13488       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13489                                                                     XType));
13490     }
13491   }
13492
13493   // Check to see if this is an integer abs.
13494   // select_cc setg[te] X,  0,  X, -X ->
13495   // select_cc setgt    X, -1,  X, -X ->
13496   // select_cc setl[te] X,  0, -X,  X ->
13497   // select_cc setlt    X,  1, -X,  X ->
13498   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13499   if (N1C) {
13500     ConstantSDNode *SubC = nullptr;
13501     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13502          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13503         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13504       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13505     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13506               (N1C->isOne() && CC == ISD::SETLT)) &&
13507              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13508       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13509
13510     EVT XType = N0.getValueType();
13511     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13512       SDLoc DL(N0);
13513       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13514                                   N0,
13515                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13516                                          getShiftAmountTy(N0.getValueType())));
13517       SDValue Add = DAG.getNode(ISD::ADD, DL,
13518                                 XType, N0, Shift);
13519       AddToWorklist(Shift.getNode());
13520       AddToWorklist(Add.getNode());
13521       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13522     }
13523   }
13524
13525   return SDValue();
13526 }
13527
13528 /// This is a stub for TargetLowering::SimplifySetCC.
13529 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13530                                    SDValue N1, ISD::CondCode Cond,
13531                                    SDLoc DL, bool foldBooleans) {
13532   TargetLowering::DAGCombinerInfo
13533     DagCombineInfo(DAG, Level, false, this);
13534   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13535 }
13536
13537 /// Given an ISD::SDIV node expressing a divide by constant, return
13538 /// a DAG expression to select that will generate the same value by multiplying
13539 /// by a magic number.
13540 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13541 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13542   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13543   if (!C)
13544     return SDValue();
13545
13546   // Avoid division by zero.
13547   if (C->isNullValue())
13548     return SDValue();
13549
13550   std::vector<SDNode*> Built;
13551   SDValue S =
13552       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13553
13554   for (SDNode *N : Built)
13555     AddToWorklist(N);
13556   return S;
13557 }
13558
13559 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13560 /// DAG expression that will generate the same value by right shifting.
13561 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13562   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13563   if (!C)
13564     return SDValue();
13565
13566   // Avoid division by zero.
13567   if (C->isNullValue())
13568     return SDValue();
13569
13570   std::vector<SDNode *> Built;
13571   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13572
13573   for (SDNode *N : Built)
13574     AddToWorklist(N);
13575   return S;
13576 }
13577
13578 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13579 /// expression that will generate the same value by multiplying by a magic
13580 /// number.
13581 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13582 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13583   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13584   if (!C)
13585     return SDValue();
13586
13587   // Avoid division by zero.
13588   if (C->isNullValue())
13589     return SDValue();
13590
13591   std::vector<SDNode*> Built;
13592   SDValue S =
13593       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13594
13595   for (SDNode *N : Built)
13596     AddToWorklist(N);
13597   return S;
13598 }
13599
13600 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13601   if (Level >= AfterLegalizeDAG)
13602     return SDValue();
13603
13604   // Expose the DAG combiner to the target combiner implementations.
13605   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13606
13607   unsigned Iterations = 0;
13608   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13609     if (Iterations) {
13610       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13611       // For the reciprocal, we need to find the zero of the function:
13612       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13613       //     =>
13614       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13615       //     does not require additional intermediate precision]
13616       EVT VT = Op.getValueType();
13617       SDLoc DL(Op);
13618       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13619
13620       AddToWorklist(Est.getNode());
13621
13622       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13623       for (unsigned i = 0; i < Iterations; ++i) {
13624         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13625         AddToWorklist(NewEst.getNode());
13626
13627         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13628         AddToWorklist(NewEst.getNode());
13629
13630         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13631         AddToWorklist(NewEst.getNode());
13632
13633         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13634         AddToWorklist(Est.getNode());
13635       }
13636     }
13637     return Est;
13638   }
13639
13640   return SDValue();
13641 }
13642
13643 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13644 /// For the reciprocal sqrt, we need to find the zero of the function:
13645 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13646 ///     =>
13647 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13648 /// As a result, we precompute A/2 prior to the iteration loop.
13649 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13650                                           unsigned Iterations) {
13651   EVT VT = Arg.getValueType();
13652   SDLoc DL(Arg);
13653   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13654
13655   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13656   // this entire sequence requires only one FP constant.
13657   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13658   AddToWorklist(HalfArg.getNode());
13659
13660   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13661   AddToWorklist(HalfArg.getNode());
13662
13663   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13664   for (unsigned i = 0; i < Iterations; ++i) {
13665     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13666     AddToWorklist(NewEst.getNode());
13667
13668     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13669     AddToWorklist(NewEst.getNode());
13670
13671     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13672     AddToWorklist(NewEst.getNode());
13673
13674     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13675     AddToWorklist(Est.getNode());
13676   }
13677   return Est;
13678 }
13679
13680 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13681 /// For the reciprocal sqrt, we need to find the zero of the function:
13682 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13683 ///     =>
13684 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13685 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13686                                           unsigned Iterations) {
13687   EVT VT = Arg.getValueType();
13688   SDLoc DL(Arg);
13689   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13690   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13691
13692   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13693   for (unsigned i = 0; i < Iterations; ++i) {
13694     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13695     AddToWorklist(HalfEst.getNode());
13696
13697     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13698     AddToWorklist(Est.getNode());
13699
13700     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13701     AddToWorklist(Est.getNode());
13702
13703     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13704     AddToWorklist(Est.getNode());
13705
13706     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13707     AddToWorklist(Est.getNode());
13708   }
13709   return Est;
13710 }
13711
13712 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13713   if (Level >= AfterLegalizeDAG)
13714     return SDValue();
13715
13716   // Expose the DAG combiner to the target combiner implementations.
13717   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13718   unsigned Iterations = 0;
13719   bool UseOneConstNR = false;
13720   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13721     AddToWorklist(Est.getNode());
13722     if (Iterations) {
13723       Est = UseOneConstNR ?
13724         BuildRsqrtNROneConst(Op, Est, Iterations) :
13725         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13726     }
13727     return Est;
13728   }
13729
13730   return SDValue();
13731 }
13732
13733 /// Return true if base is a frame index, which is known not to alias with
13734 /// anything but itself.  Provides base object and offset as results.
13735 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13736                            const GlobalValue *&GV, const void *&CV) {
13737   // Assume it is a primitive operation.
13738   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13739
13740   // If it's an adding a simple constant then integrate the offset.
13741   if (Base.getOpcode() == ISD::ADD) {
13742     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13743       Base = Base.getOperand(0);
13744       Offset += C->getZExtValue();
13745     }
13746   }
13747
13748   // Return the underlying GlobalValue, and update the Offset.  Return false
13749   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13750   // by multiple nodes with different offsets.
13751   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13752     GV = G->getGlobal();
13753     Offset += G->getOffset();
13754     return false;
13755   }
13756
13757   // Return the underlying Constant value, and update the Offset.  Return false
13758   // for ConstantSDNodes since the same constant pool entry may be represented
13759   // by multiple nodes with different offsets.
13760   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13761     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13762                                          : (const void *)C->getConstVal();
13763     Offset += C->getOffset();
13764     return false;
13765   }
13766   // If it's any of the following then it can't alias with anything but itself.
13767   return isa<FrameIndexSDNode>(Base);
13768 }
13769
13770 /// Return true if there is any possibility that the two addresses overlap.
13771 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13772   // If they are the same then they must be aliases.
13773   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13774
13775   // If they are both volatile then they cannot be reordered.
13776   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13777
13778   // Gather base node and offset information.
13779   SDValue Base1, Base2;
13780   int64_t Offset1, Offset2;
13781   const GlobalValue *GV1, *GV2;
13782   const void *CV1, *CV2;
13783   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13784                                       Base1, Offset1, GV1, CV1);
13785   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13786                                       Base2, Offset2, GV2, CV2);
13787
13788   // If they have a same base address then check to see if they overlap.
13789   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13790     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13791              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13792
13793   // It is possible for different frame indices to alias each other, mostly
13794   // when tail call optimization reuses return address slots for arguments.
13795   // To catch this case, look up the actual index of frame indices to compute
13796   // the real alias relationship.
13797   if (isFrameIndex1 && isFrameIndex2) {
13798     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13799     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13800     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13801     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13802              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13803   }
13804
13805   // Otherwise, if we know what the bases are, and they aren't identical, then
13806   // we know they cannot alias.
13807   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13808     return false;
13809
13810   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13811   // compared to the size and offset of the access, we may be able to prove they
13812   // do not alias.  This check is conservative for now to catch cases created by
13813   // splitting vector types.
13814   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13815       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13816       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13817        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13818       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13819     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13820     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13821
13822     // There is no overlap between these relatively aligned accesses of similar
13823     // size, return no alias.
13824     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13825         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13826       return false;
13827   }
13828
13829   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13830                    ? CombinerGlobalAA
13831                    : DAG.getSubtarget().useAA();
13832 #ifndef NDEBUG
13833   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13834       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13835     UseAA = false;
13836 #endif
13837   if (UseAA &&
13838       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13839     // Use alias analysis information.
13840     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13841                                  Op1->getSrcValueOffset());
13842     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13843         Op0->getSrcValueOffset() - MinOffset;
13844     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13845         Op1->getSrcValueOffset() - MinOffset;
13846     AliasAnalysis::AliasResult AAResult =
13847         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13848                                          Overlap1,
13849                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13850                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13851                                          Overlap2,
13852                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13853     if (AAResult == AliasAnalysis::NoAlias)
13854       return false;
13855   }
13856
13857   // Otherwise we have to assume they alias.
13858   return true;
13859 }
13860
13861 /// Walk up chain skipping non-aliasing memory nodes,
13862 /// looking for aliasing nodes and adding them to the Aliases vector.
13863 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13864                                    SmallVectorImpl<SDValue> &Aliases) {
13865   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13866   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13867
13868   // Get alias information for node.
13869   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13870
13871   // Starting off.
13872   Chains.push_back(OriginalChain);
13873   unsigned Depth = 0;
13874
13875   // Look at each chain and determine if it is an alias.  If so, add it to the
13876   // aliases list.  If not, then continue up the chain looking for the next
13877   // candidate.
13878   while (!Chains.empty()) {
13879     SDValue Chain = Chains.back();
13880     Chains.pop_back();
13881
13882     // For TokenFactor nodes, look at each operand and only continue up the
13883     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13884     // find more and revert to original chain since the xform is unlikely to be
13885     // profitable.
13886     //
13887     // FIXME: The depth check could be made to return the last non-aliasing
13888     // chain we found before we hit a tokenfactor rather than the original
13889     // chain.
13890     if (Depth > 6 || Aliases.size() == 2) {
13891       Aliases.clear();
13892       Aliases.push_back(OriginalChain);
13893       return;
13894     }
13895
13896     // Don't bother if we've been before.
13897     if (!Visited.insert(Chain.getNode()).second)
13898       continue;
13899
13900     switch (Chain.getOpcode()) {
13901     case ISD::EntryToken:
13902       // Entry token is ideal chain operand, but handled in FindBetterChain.
13903       break;
13904
13905     case ISD::LOAD:
13906     case ISD::STORE: {
13907       // Get alias information for Chain.
13908       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13909           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13910
13911       // If chain is alias then stop here.
13912       if (!(IsLoad && IsOpLoad) &&
13913           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13914         Aliases.push_back(Chain);
13915       } else {
13916         // Look further up the chain.
13917         Chains.push_back(Chain.getOperand(0));
13918         ++Depth;
13919       }
13920       break;
13921     }
13922
13923     case ISD::TokenFactor:
13924       // We have to check each of the operands of the token factor for "small"
13925       // token factors, so we queue them up.  Adding the operands to the queue
13926       // (stack) in reverse order maintains the original order and increases the
13927       // likelihood that getNode will find a matching token factor (CSE.)
13928       if (Chain.getNumOperands() > 16) {
13929         Aliases.push_back(Chain);
13930         break;
13931       }
13932       for (unsigned n = Chain.getNumOperands(); n;)
13933         Chains.push_back(Chain.getOperand(--n));
13934       ++Depth;
13935       break;
13936
13937     default:
13938       // For all other instructions we will just have to take what we can get.
13939       Aliases.push_back(Chain);
13940       break;
13941     }
13942   }
13943
13944   // We need to be careful here to also search for aliases through the
13945   // value operand of a store, etc. Consider the following situation:
13946   //   Token1 = ...
13947   //   L1 = load Token1, %52
13948   //   S1 = store Token1, L1, %51
13949   //   L2 = load Token1, %52+8
13950   //   S2 = store Token1, L2, %51+8
13951   //   Token2 = Token(S1, S2)
13952   //   L3 = load Token2, %53
13953   //   S3 = store Token2, L3, %52
13954   //   L4 = load Token2, %53+8
13955   //   S4 = store Token2, L4, %52+8
13956   // If we search for aliases of S3 (which loads address %52), and we look
13957   // only through the chain, then we'll miss the trivial dependence on L1
13958   // (which also loads from %52). We then might change all loads and
13959   // stores to use Token1 as their chain operand, which could result in
13960   // copying %53 into %52 before copying %52 into %51 (which should
13961   // happen first).
13962   //
13963   // The problem is, however, that searching for such data dependencies
13964   // can become expensive, and the cost is not directly related to the
13965   // chain depth. Instead, we'll rule out such configurations here by
13966   // insisting that we've visited all chain users (except for users
13967   // of the original chain, which is not necessary). When doing this,
13968   // we need to look through nodes we don't care about (otherwise, things
13969   // like register copies will interfere with trivial cases).
13970
13971   SmallVector<const SDNode *, 16> Worklist;
13972   for (const SDNode *N : Visited)
13973     if (N != OriginalChain.getNode())
13974       Worklist.push_back(N);
13975
13976   while (!Worklist.empty()) {
13977     const SDNode *M = Worklist.pop_back_val();
13978
13979     // We have already visited M, and want to make sure we've visited any uses
13980     // of M that we care about. For uses that we've not visisted, and don't
13981     // care about, queue them to the worklist.
13982
13983     for (SDNode::use_iterator UI = M->use_begin(),
13984          UIE = M->use_end(); UI != UIE; ++UI)
13985       if (UI.getUse().getValueType() == MVT::Other &&
13986           Visited.insert(*UI).second) {
13987         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13988           // We've not visited this use, and we care about it (it could have an
13989           // ordering dependency with the original node).
13990           Aliases.clear();
13991           Aliases.push_back(OriginalChain);
13992           return;
13993         }
13994
13995         // We've not visited this use, but we don't care about it. Mark it as
13996         // visited and enqueue it to the worklist.
13997         Worklist.push_back(*UI);
13998       }
13999   }
14000 }
14001
14002 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14003 /// (aliasing node.)
14004 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14005   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14006
14007   // Accumulate all the aliases to this node.
14008   GatherAllAliases(N, OldChain, Aliases);
14009
14010   // If no operands then chain to entry token.
14011   if (Aliases.size() == 0)
14012     return DAG.getEntryNode();
14013
14014   // If a single operand then chain to it.  We don't need to revisit it.
14015   if (Aliases.size() == 1)
14016     return Aliases[0];
14017
14018   // Construct a custom tailored token factor.
14019   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14020 }
14021
14022 /// This is the entry point for the file.
14023 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14024                            CodeGenOpt::Level OptLevel) {
14025   /// This is the main entry point to this class.
14026   DAGCombiner(*this, AA, OptLevel).Run(Level);
14027 }