[SDAG] Now that we have a way to communicate the exact bit on sdiv use it to simplify...
[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 visitBSWAP(SDNode *N);
259     SDValue visitCTLZ(SDNode *N);
260     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTTZ(SDNode *N);
262     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263     SDValue visitCTPOP(SDNode *N);
264     SDValue visitSELECT(SDNode *N);
265     SDValue visitVSELECT(SDNode *N);
266     SDValue visitSELECT_CC(SDNode *N);
267     SDValue visitSETCC(SDNode *N);
268     SDValue visitSIGN_EXTEND(SDNode *N);
269     SDValue visitZERO_EXTEND(SDNode *N);
270     SDValue visitANY_EXTEND(SDNode *N);
271     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
273     SDValue visitTRUNCATE(SDNode *N);
274     SDValue visitBITCAST(SDNode *N);
275     SDValue visitBUILD_PAIR(SDNode *N);
276     SDValue visitFADD(SDNode *N);
277     SDValue visitFSUB(SDNode *N);
278     SDValue visitFMUL(SDNode *N);
279     SDValue visitFMA(SDNode *N);
280     SDValue visitFDIV(SDNode *N);
281     SDValue visitFREM(SDNode *N);
282     SDValue visitFSQRT(SDNode *N);
283     SDValue visitFCOPYSIGN(SDNode *N);
284     SDValue visitSINT_TO_FP(SDNode *N);
285     SDValue visitUINT_TO_FP(SDNode *N);
286     SDValue visitFP_TO_SINT(SDNode *N);
287     SDValue visitFP_TO_UINT(SDNode *N);
288     SDValue visitFP_ROUND(SDNode *N);
289     SDValue visitFP_ROUND_INREG(SDNode *N);
290     SDValue visitFP_EXTEND(SDNode *N);
291     SDValue visitFNEG(SDNode *N);
292     SDValue visitFABS(SDNode *N);
293     SDValue visitFCEIL(SDNode *N);
294     SDValue visitFTRUNC(SDNode *N);
295     SDValue visitFFLOOR(SDNode *N);
296     SDValue visitFMINNUM(SDNode *N);
297     SDValue visitFMAXNUM(SDNode *N);
298     SDValue visitBRCOND(SDNode *N);
299     SDValue visitBR_CC(SDNode *N);
300     SDValue visitLOAD(SDNode *N);
301     SDValue visitSTORE(SDNode *N);
302     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
303     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
304     SDValue visitBUILD_VECTOR(SDNode *N);
305     SDValue visitCONCAT_VECTORS(SDNode *N);
306     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
307     SDValue visitVECTOR_SHUFFLE(SDNode *N);
308     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
309     SDValue visitINSERT_SUBVECTOR(SDNode *N);
310     SDValue visitMLOAD(SDNode *N);
311     SDValue visitMSTORE(SDNode *N);
312     SDValue visitMGATHER(SDNode *N);
313     SDValue visitMSCATTER(SDNode *N);
314     SDValue visitFP_TO_FP16(SDNode *N);
315
316     SDValue visitFADDForFMACombine(SDNode *N);
317     SDValue visitFSUBForFMACombine(SDNode *N);
318
319     SDValue XformToShuffleWithZero(SDNode *N);
320     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
321
322     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
323
324     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
325     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
326     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
327     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
328                              SDValue N3, ISD::CondCode CC,
329                              bool NotExtCompare = false);
330     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
331                           SDLoc DL, bool foldBooleans = true);
332
333     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
334                            SDValue &CC) const;
335     bool isOneUseSetCC(SDValue N) const;
336
337     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
338                                          unsigned HiOp);
339     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
340     SDValue CombineExtLoad(SDNode *N);
341     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
342     SDValue BuildSDIV(SDNode *N);
343     SDValue BuildSDIVPow2(SDNode *N);
344     SDValue BuildUDIV(SDNode *N);
345     SDValue BuildReciprocalEstimate(SDValue Op);
346     SDValue BuildRsqrtEstimate(SDValue Op);
347     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
348     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
349     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
350                                bool DemandHighBits = true);
351     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
352     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
353                               SDValue InnerPos, SDValue InnerNeg,
354                               unsigned PosOpcode, unsigned NegOpcode,
355                               SDLoc DL);
356     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
357     SDValue ReduceLoadWidth(SDNode *N);
358     SDValue ReduceLoadOpStoreWidth(SDNode *N);
359     SDValue TransformFPLoadStorePair(SDNode *N);
360     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
361     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
362
363     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
364
365     /// Walk up chain skipping non-aliasing memory nodes,
366     /// looking for aliasing nodes and adding them to the Aliases vector.
367     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
368                           SmallVectorImpl<SDValue> &Aliases);
369
370     /// Return true if there is any possibility that the two addresses overlap.
371     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
372
373     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
374     /// chain (aliasing node.)
375     SDValue FindBetterChain(SDNode *N, SDValue Chain);
376
377     /// Holds a pointer to an LSBaseSDNode as well as information on where it
378     /// is located in a sequence of memory operations connected by a chain.
379     struct MemOpLink {
380       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
381       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
382       // Ptr to the mem node.
383       LSBaseSDNode *MemNode;
384       // Offset from the base ptr.
385       int64_t OffsetFromBase;
386       // What is the sequence number of this mem node.
387       // Lowest mem operand in the DAG starts at zero.
388       unsigned SequenceNum;
389     };
390
391     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
392     /// constant build_vector of the stored constant values in Stores.
393     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
394                                          SDLoc SL,
395                                          ArrayRef<MemOpLink> Stores,
396                                          EVT Ty) const;
397
398     /// This is a helper function for MergeConsecutiveStores. When the source
399     /// elements of the consecutive stores are all constants or all extracted
400     /// vector elements, try to merge them into one larger store.
401     /// \return True if a merged store was created.
402     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
403                                          EVT MemVT, unsigned NumElem,
404                                          bool IsConstantSrc, bool UseVector);
405
406     /// This is a helper function for MergeConsecutiveStores.
407     /// Stores that may be merged are placed in StoreNodes.
408     /// Loads that may alias with those stores are placed in AliasLoadNodes.
409     void getStoreMergeAndAliasCandidates(
410         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
411         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
412     
413     /// Merge consecutive store operations into a wide store.
414     /// This optimization uses wide integers or vectors when possible.
415     /// \return True if some memory operations were changed.
416     bool MergeConsecutiveStores(StoreSDNode *N);
417
418     /// \brief Try to transform a truncation where C is a constant:
419     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
420     ///
421     /// \p N needs to be a truncation and its first operand an AND. Other
422     /// requirements are checked by the function (e.g. that trunc is
423     /// single-use) and if missed an empty SDValue is returned.
424     SDValue distributeTruncateThroughAnd(SDNode *N);
425
426   public:
427     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
428         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
429           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
430       auto *F = DAG.getMachineFunction().getFunction();
431       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
432                     F->hasFnAttribute(Attribute::MinSize);
433     }
434
435     /// Runs the dag combiner on all nodes in the work list
436     void Run(CombineLevel AtLevel);
437
438     SelectionDAG &getDAG() const { return DAG; }
439
440     /// Returns a type large enough to hold any valid shift amount - before type
441     /// legalization these can be huge.
442     EVT getShiftAmountTy(EVT LHSTy) {
443       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
444       if (LHSTy.isVector())
445         return LHSTy;
446       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
447                         : TLI.getPointerTy();
448     }
449
450     /// This method returns true if we are running before type legalization or
451     /// if the specified VT is legal.
452     bool isTypeLegal(const EVT &VT) {
453       if (!LegalTypes) return true;
454       return TLI.isTypeLegal(VT);
455     }
456
457     /// Convenience wrapper around TargetLowering::getSetCCResultType
458     EVT getSetCCResultType(EVT VT) const {
459       return TLI.getSetCCResultType(*DAG.getContext(), VT);
460     }
461   };
462 }
463
464
465 namespace {
466 /// This class is a DAGUpdateListener that removes any deleted
467 /// nodes from the worklist.
468 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
469   DAGCombiner &DC;
470 public:
471   explicit WorklistRemover(DAGCombiner &dc)
472     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
473
474   void NodeDeleted(SDNode *N, SDNode *E) override {
475     DC.removeFromWorklist(N);
476   }
477 };
478 }
479
480 //===----------------------------------------------------------------------===//
481 //  TargetLowering::DAGCombinerInfo implementation
482 //===----------------------------------------------------------------------===//
483
484 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
485   ((DAGCombiner*)DC)->AddToWorklist(N);
486 }
487
488 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
489   ((DAGCombiner*)DC)->removeFromWorklist(N);
490 }
491
492 SDValue TargetLowering::DAGCombinerInfo::
493 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
494   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
495 }
496
497 SDValue TargetLowering::DAGCombinerInfo::
498 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
499   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
500 }
501
502
503 SDValue TargetLowering::DAGCombinerInfo::
504 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
505   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
506 }
507
508 void TargetLowering::DAGCombinerInfo::
509 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
510   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
511 }
512
513 //===----------------------------------------------------------------------===//
514 // Helper Functions
515 //===----------------------------------------------------------------------===//
516
517 void DAGCombiner::deleteAndRecombine(SDNode *N) {
518   removeFromWorklist(N);
519
520   // If the operands of this node are only used by the node, they will now be
521   // dead. Make sure to re-visit them and recursively delete dead nodes.
522   for (const SDValue &Op : N->ops())
523     // For an operand generating multiple values, one of the values may
524     // become dead allowing further simplification (e.g. split index
525     // arithmetic from an indexed load).
526     if (Op->hasOneUse() || Op->getNumValues() > 1)
527       AddToWorklist(Op.getNode());
528
529   DAG.DeleteNode(N);
530 }
531
532 /// Return 1 if we can compute the negated form of the specified expression for
533 /// the same cost as the expression itself, or 2 if we can compute the negated
534 /// form more cheaply than the expression itself.
535 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
536                                const TargetLowering &TLI,
537                                const TargetOptions *Options,
538                                unsigned Depth = 0) {
539   // fneg is removable even if it has multiple uses.
540   if (Op.getOpcode() == ISD::FNEG) return 2;
541
542   // Don't allow anything with multiple uses.
543   if (!Op.hasOneUse()) return 0;
544
545   // Don't recurse exponentially.
546   if (Depth > 6) return 0;
547
548   switch (Op.getOpcode()) {
549   default: return false;
550   case ISD::ConstantFP:
551     // Don't invert constant FP values after legalize.  The negated constant
552     // isn't necessarily legal.
553     return LegalOperations ? 0 : 1;
554   case ISD::FADD:
555     // FIXME: determine better conditions for this xform.
556     if (!Options->UnsafeFPMath) return 0;
557
558     // After operation legalization, it might not be legal to create new FSUBs.
559     if (LegalOperations &&
560         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
561       return 0;
562
563     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
564     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
565                                     Options, Depth + 1))
566       return V;
567     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
568     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
569                               Depth + 1);
570   case ISD::FSUB:
571     // We can't turn -(A-B) into B-A when we honor signed zeros.
572     if (!Options->UnsafeFPMath) return 0;
573
574     // fold (fneg (fsub A, B)) -> (fsub B, A)
575     return 1;
576
577   case ISD::FMUL:
578   case ISD::FDIV:
579     if (Options->HonorSignDependentRoundingFPMath()) return 0;
580
581     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
582     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
583                                     Options, Depth + 1))
584       return V;
585
586     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
587                               Depth + 1);
588
589   case ISD::FP_EXTEND:
590   case ISD::FP_ROUND:
591   case ISD::FSIN:
592     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
593                               Depth + 1);
594   }
595 }
596
597 /// If isNegatibleForFree returns true, return the newly negated expression.
598 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
599                                     bool LegalOperations, unsigned Depth = 0) {
600   const TargetOptions &Options = DAG.getTarget().Options;
601   // fneg is removable even if it has multiple uses.
602   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
603
604   // Don't allow anything with multiple uses.
605   assert(Op.hasOneUse() && "Unknown reuse!");
606
607   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
608   switch (Op.getOpcode()) {
609   default: llvm_unreachable("Unknown code");
610   case ISD::ConstantFP: {
611     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
612     V.changeSign();
613     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
614   }
615   case ISD::FADD:
616     // FIXME: determine better conditions for this xform.
617     assert(Options.UnsafeFPMath);
618
619     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
620     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
621                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
622       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
623                          GetNegatedExpression(Op.getOperand(0), DAG,
624                                               LegalOperations, Depth+1),
625                          Op.getOperand(1));
626     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
627     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
628                        GetNegatedExpression(Op.getOperand(1), DAG,
629                                             LegalOperations, Depth+1),
630                        Op.getOperand(0));
631   case ISD::FSUB:
632     // We can't turn -(A-B) into B-A when we honor signed zeros.
633     assert(Options.UnsafeFPMath);
634
635     // fold (fneg (fsub 0, B)) -> B
636     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
637       if (N0CFP->isZero())
638         return Op.getOperand(1);
639
640     // fold (fneg (fsub A, B)) -> (fsub B, A)
641     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
642                        Op.getOperand(1), Op.getOperand(0));
643
644   case ISD::FMUL:
645   case ISD::FDIV:
646     assert(!Options.HonorSignDependentRoundingFPMath());
647
648     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
649     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
650                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
651       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
652                          GetNegatedExpression(Op.getOperand(0), DAG,
653                                               LegalOperations, Depth+1),
654                          Op.getOperand(1));
655
656     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
657     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
658                        Op.getOperand(0),
659                        GetNegatedExpression(Op.getOperand(1), DAG,
660                                             LegalOperations, Depth+1));
661
662   case ISD::FP_EXTEND:
663   case ISD::FSIN:
664     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
665                        GetNegatedExpression(Op.getOperand(0), DAG,
666                                             LegalOperations, Depth+1));
667   case ISD::FP_ROUND:
668       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
669                          GetNegatedExpression(Op.getOperand(0), DAG,
670                                               LegalOperations, Depth+1),
671                          Op.getOperand(1));
672   }
673 }
674
675 // Return true if this node is a setcc, or is a select_cc
676 // that selects between the target values used for true and false, making it
677 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
678 // the appropriate nodes based on the type of node we are checking. This
679 // simplifies life a bit for the callers.
680 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
681                                     SDValue &CC) const {
682   if (N.getOpcode() == ISD::SETCC) {
683     LHS = N.getOperand(0);
684     RHS = N.getOperand(1);
685     CC  = N.getOperand(2);
686     return true;
687   }
688
689   if (N.getOpcode() != ISD::SELECT_CC ||
690       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
691       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
692     return false;
693
694   if (TLI.getBooleanContents(N.getValueType()) ==
695       TargetLowering::UndefinedBooleanContent)
696     return false;
697
698   LHS = N.getOperand(0);
699   RHS = N.getOperand(1);
700   CC  = N.getOperand(4);
701   return true;
702 }
703
704 /// Return true if this is a SetCC-equivalent operation with only one use.
705 /// If this is true, it allows the users to invert the operation for free when
706 /// it is profitable to do so.
707 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
708   SDValue N0, N1, N2;
709   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
710     return true;
711   return false;
712 }
713
714 /// Returns true if N is a BUILD_VECTOR node whose
715 /// elements are all the same constant or undefined.
716 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
717   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
718   if (!C)
719     return false;
720
721   APInt SplatUndef;
722   unsigned SplatBitSize;
723   bool HasAnyUndefs;
724   EVT EltVT = N->getValueType(0).getVectorElementType();
725   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
726                              HasAnyUndefs) &&
727           EltVT.getSizeInBits() >= SplatBitSize);
728 }
729
730 // \brief Returns the SDNode if it is a constant integer BuildVector
731 // or constant integer.
732 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
733   if (isa<ConstantSDNode>(N))
734     return N.getNode();
735   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
736     return N.getNode();
737   return nullptr;
738 }
739
740 // \brief Returns the SDNode if it is a constant float BuildVector
741 // or constant float.
742 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
743   if (isa<ConstantFPSDNode>(N))
744     return N.getNode();
745   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
746     return N.getNode();
747   return nullptr;
748 }
749
750 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
751 // int.
752 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
753   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
754     return CN;
755
756   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
757     BitVector UndefElements;
758     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
759
760     // BuildVectors can truncate their operands. Ignore that case here.
761     // FIXME: We blindly ignore splats which include undef which is overly
762     // pessimistic.
763     if (CN && UndefElements.none() &&
764         CN->getValueType(0) == N.getValueType().getScalarType())
765       return CN;
766   }
767
768   return nullptr;
769 }
770
771 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
772 // float.
773 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
774   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
775     return CN;
776
777   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
778     BitVector UndefElements;
779     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
780
781     if (CN && UndefElements.none())
782       return CN;
783   }
784
785   return nullptr;
786 }
787
788 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
789                                     SDValue N0, SDValue N1) {
790   EVT VT = N0.getValueType();
791   if (N0.getOpcode() == Opc) {
792     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
793       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
794         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
795         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
796           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
797         return SDValue();
798       }
799       if (N0.hasOneUse()) {
800         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
801         // use
802         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
803         if (!OpNode.getNode())
804           return SDValue();
805         AddToWorklist(OpNode.getNode());
806         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
807       }
808     }
809   }
810
811   if (N1.getOpcode() == Opc) {
812     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
813       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
814         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
815         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
816           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
817         return SDValue();
818       }
819       if (N1.hasOneUse()) {
820         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
821         // use
822         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
823         if (!OpNode.getNode())
824           return SDValue();
825         AddToWorklist(OpNode.getNode());
826         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
827       }
828     }
829   }
830
831   return SDValue();
832 }
833
834 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
835                                bool AddTo) {
836   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
837   ++NodesCombined;
838   DEBUG(dbgs() << "\nReplacing.1 ";
839         N->dump(&DAG);
840         dbgs() << "\nWith: ";
841         To[0].getNode()->dump(&DAG);
842         dbgs() << " and " << NumTo-1 << " other values\n");
843   for (unsigned i = 0, e = NumTo; i != e; ++i)
844     assert((!To[i].getNode() ||
845             N->getValueType(i) == To[i].getValueType()) &&
846            "Cannot combine value to value of different type!");
847
848   WorklistRemover DeadNodes(*this);
849   DAG.ReplaceAllUsesWith(N, To);
850   if (AddTo) {
851     // Push the new nodes and any users onto the worklist
852     for (unsigned i = 0, e = NumTo; i != e; ++i) {
853       if (To[i].getNode()) {
854         AddToWorklist(To[i].getNode());
855         AddUsersToWorklist(To[i].getNode());
856       }
857     }
858   }
859
860   // Finally, if the node is now dead, remove it from the graph.  The node
861   // may not be dead if the replacement process recursively simplified to
862   // something else needing this node.
863   if (N->use_empty())
864     deleteAndRecombine(N);
865   return SDValue(N, 0);
866 }
867
868 void DAGCombiner::
869 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
870   // Replace all uses.  If any nodes become isomorphic to other nodes and
871   // are deleted, make sure to remove them from our worklist.
872   WorklistRemover DeadNodes(*this);
873   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
874
875   // Push the new node and any (possibly new) users onto the worklist.
876   AddToWorklist(TLO.New.getNode());
877   AddUsersToWorklist(TLO.New.getNode());
878
879   // Finally, if the node is now dead, remove it from the graph.  The node
880   // may not be dead if the replacement process recursively simplified to
881   // something else needing this node.
882   if (TLO.Old.getNode()->use_empty())
883     deleteAndRecombine(TLO.Old.getNode());
884 }
885
886 /// Check the specified integer node value to see if it can be simplified or if
887 /// things it uses can be simplified by bit propagation. If so, return true.
888 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
889   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
890   APInt KnownZero, KnownOne;
891   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
892     return false;
893
894   // Revisit the node.
895   AddToWorklist(Op.getNode());
896
897   // Replace the old value with the new one.
898   ++NodesCombined;
899   DEBUG(dbgs() << "\nReplacing.2 ";
900         TLO.Old.getNode()->dump(&DAG);
901         dbgs() << "\nWith: ";
902         TLO.New.getNode()->dump(&DAG);
903         dbgs() << '\n');
904
905   CommitTargetLoweringOpt(TLO);
906   return true;
907 }
908
909 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
910   SDLoc dl(Load);
911   EVT VT = Load->getValueType(0);
912   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
913
914   DEBUG(dbgs() << "\nReplacing.9 ";
915         Load->dump(&DAG);
916         dbgs() << "\nWith: ";
917         Trunc.getNode()->dump(&DAG);
918         dbgs() << '\n');
919   WorklistRemover DeadNodes(*this);
920   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
921   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
922   deleteAndRecombine(Load);
923   AddToWorklist(Trunc.getNode());
924 }
925
926 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
927   Replace = false;
928   SDLoc dl(Op);
929   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
930     EVT MemVT = LD->getMemoryVT();
931     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
932       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
933                                                        : ISD::EXTLOAD)
934       : LD->getExtensionType();
935     Replace = true;
936     return DAG.getExtLoad(ExtType, dl, PVT,
937                           LD->getChain(), LD->getBasePtr(),
938                           MemVT, LD->getMemOperand());
939   }
940
941   unsigned Opc = Op.getOpcode();
942   switch (Opc) {
943   default: break;
944   case ISD::AssertSext:
945     return DAG.getNode(ISD::AssertSext, dl, PVT,
946                        SExtPromoteOperand(Op.getOperand(0), PVT),
947                        Op.getOperand(1));
948   case ISD::AssertZext:
949     return DAG.getNode(ISD::AssertZext, dl, PVT,
950                        ZExtPromoteOperand(Op.getOperand(0), PVT),
951                        Op.getOperand(1));
952   case ISD::Constant: {
953     unsigned ExtOpc =
954       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
955     return DAG.getNode(ExtOpc, dl, PVT, Op);
956   }
957   }
958
959   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
960     return SDValue();
961   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
962 }
963
964 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
965   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
966     return SDValue();
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.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
978                      DAG.getValueType(OldVT));
979 }
980
981 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
982   EVT OldVT = Op.getValueType();
983   SDLoc dl(Op);
984   bool Replace = false;
985   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
986   if (!NewOp.getNode())
987     return SDValue();
988   AddToWorklist(NewOp.getNode());
989
990   if (Replace)
991     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
992   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
993 }
994
995 /// Promote the specified integer binary operation if the target indicates it is
996 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
997 /// i32 since i16 instructions are longer.
998 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
999   if (!LegalOperations)
1000     return SDValue();
1001
1002   EVT VT = Op.getValueType();
1003   if (VT.isVector() || !VT.isInteger())
1004     return SDValue();
1005
1006   // If operation type is 'undesirable', e.g. i16 on x86, consider
1007   // promoting it.
1008   unsigned Opc = Op.getOpcode();
1009   if (TLI.isTypeDesirableForOp(Opc, VT))
1010     return SDValue();
1011
1012   EVT PVT = VT;
1013   // Consult target whether it is a good idea to promote this operation and
1014   // what's the right type to promote it to.
1015   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1016     assert(PVT != VT && "Don't know what type to promote to!");
1017
1018     bool Replace0 = false;
1019     SDValue N0 = Op.getOperand(0);
1020     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1021     if (!NN0.getNode())
1022       return SDValue();
1023
1024     bool Replace1 = false;
1025     SDValue N1 = Op.getOperand(1);
1026     SDValue NN1;
1027     if (N0 == N1)
1028       NN1 = NN0;
1029     else {
1030       NN1 = PromoteOperand(N1, PVT, Replace1);
1031       if (!NN1.getNode())
1032         return SDValue();
1033     }
1034
1035     AddToWorklist(NN0.getNode());
1036     if (NN1.getNode())
1037       AddToWorklist(NN1.getNode());
1038
1039     if (Replace0)
1040       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1041     if (Replace1)
1042       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1043
1044     DEBUG(dbgs() << "\nPromoting ";
1045           Op.getNode()->dump(&DAG));
1046     SDLoc dl(Op);
1047     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1048                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1049   }
1050   return SDValue();
1051 }
1052
1053 /// Promote the specified integer shift operation if the target indicates it is
1054 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1055 /// i32 since i16 instructions are longer.
1056 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1057   if (!LegalOperations)
1058     return SDValue();
1059
1060   EVT VT = Op.getValueType();
1061   if (VT.isVector() || !VT.isInteger())
1062     return SDValue();
1063
1064   // If operation type is 'undesirable', e.g. i16 on x86, consider
1065   // promoting it.
1066   unsigned Opc = Op.getOpcode();
1067   if (TLI.isTypeDesirableForOp(Opc, VT))
1068     return SDValue();
1069
1070   EVT PVT = VT;
1071   // Consult target whether it is a good idea to promote this operation and
1072   // what's the right type to promote it to.
1073   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1074     assert(PVT != VT && "Don't know what type to promote to!");
1075
1076     bool Replace = false;
1077     SDValue N0 = Op.getOperand(0);
1078     if (Opc == ISD::SRA)
1079       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1080     else if (Opc == ISD::SRL)
1081       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1082     else
1083       N0 = PromoteOperand(N0, PVT, Replace);
1084     if (!N0.getNode())
1085       return SDValue();
1086
1087     AddToWorklist(N0.getNode());
1088     if (Replace)
1089       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1090
1091     DEBUG(dbgs() << "\nPromoting ";
1092           Op.getNode()->dump(&DAG));
1093     SDLoc dl(Op);
1094     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1095                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1096   }
1097   return SDValue();
1098 }
1099
1100 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1101   if (!LegalOperations)
1102     return SDValue();
1103
1104   EVT VT = Op.getValueType();
1105   if (VT.isVector() || !VT.isInteger())
1106     return SDValue();
1107
1108   // If operation type is 'undesirable', e.g. i16 on x86, consider
1109   // promoting it.
1110   unsigned Opc = Op.getOpcode();
1111   if (TLI.isTypeDesirableForOp(Opc, VT))
1112     return SDValue();
1113
1114   EVT PVT = VT;
1115   // Consult target whether it is a good idea to promote this operation and
1116   // what's the right type to promote it to.
1117   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1118     assert(PVT != VT && "Don't know what type to promote to!");
1119     // fold (aext (aext x)) -> (aext x)
1120     // fold (aext (zext x)) -> (zext x)
1121     // fold (aext (sext x)) -> (sext x)
1122     DEBUG(dbgs() << "\nPromoting ";
1123           Op.getNode()->dump(&DAG));
1124     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1125   }
1126   return SDValue();
1127 }
1128
1129 bool DAGCombiner::PromoteLoad(SDValue Op) {
1130   if (!LegalOperations)
1131     return false;
1132
1133   EVT VT = Op.getValueType();
1134   if (VT.isVector() || !VT.isInteger())
1135     return false;
1136
1137   // If operation type is 'undesirable', e.g. i16 on x86, consider
1138   // promoting it.
1139   unsigned Opc = Op.getOpcode();
1140   if (TLI.isTypeDesirableForOp(Opc, VT))
1141     return false;
1142
1143   EVT PVT = VT;
1144   // Consult target whether it is a good idea to promote this operation and
1145   // what's the right type to promote it to.
1146   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1147     assert(PVT != VT && "Don't know what type to promote to!");
1148
1149     SDLoc dl(Op);
1150     SDNode *N = Op.getNode();
1151     LoadSDNode *LD = cast<LoadSDNode>(N);
1152     EVT MemVT = LD->getMemoryVT();
1153     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1154       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1155                                                        : ISD::EXTLOAD)
1156       : LD->getExtensionType();
1157     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1158                                    LD->getChain(), LD->getBasePtr(),
1159                                    MemVT, LD->getMemOperand());
1160     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1161
1162     DEBUG(dbgs() << "\nPromoting ";
1163           N->dump(&DAG);
1164           dbgs() << "\nTo: ";
1165           Result.getNode()->dump(&DAG);
1166           dbgs() << '\n');
1167     WorklistRemover DeadNodes(*this);
1168     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1169     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1170     deleteAndRecombine(N);
1171     AddToWorklist(Result.getNode());
1172     return true;
1173   }
1174   return false;
1175 }
1176
1177 /// \brief Recursively delete a node which has no uses and any operands for
1178 /// which it is the only use.
1179 ///
1180 /// Note that this both deletes the nodes and removes them from the worklist.
1181 /// It also adds any nodes who have had a user deleted to the worklist as they
1182 /// may now have only one use and subject to other combines.
1183 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1184   if (!N->use_empty())
1185     return false;
1186
1187   SmallSetVector<SDNode *, 16> Nodes;
1188   Nodes.insert(N);
1189   do {
1190     N = Nodes.pop_back_val();
1191     if (!N)
1192       continue;
1193
1194     if (N->use_empty()) {
1195       for (const SDValue &ChildN : N->op_values())
1196         Nodes.insert(ChildN.getNode());
1197
1198       removeFromWorklist(N);
1199       DAG.DeleteNode(N);
1200     } else {
1201       AddToWorklist(N);
1202     }
1203   } while (!Nodes.empty());
1204   return true;
1205 }
1206
1207 //===----------------------------------------------------------------------===//
1208 //  Main DAG Combiner implementation
1209 //===----------------------------------------------------------------------===//
1210
1211 void DAGCombiner::Run(CombineLevel AtLevel) {
1212   // set the instance variables, so that the various visit routines may use it.
1213   Level = AtLevel;
1214   LegalOperations = Level >= AfterLegalizeVectorOps;
1215   LegalTypes = Level >= AfterLegalizeTypes;
1216
1217   // Add all the dag nodes to the worklist.
1218   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1219        E = DAG.allnodes_end(); I != E; ++I)
1220     AddToWorklist(I);
1221
1222   // Create a dummy node (which is not added to allnodes), that adds a reference
1223   // to the root node, preventing it from being deleted, and tracking any
1224   // changes of the root.
1225   HandleSDNode Dummy(DAG.getRoot());
1226
1227   // while the worklist isn't empty, find a node and
1228   // try and combine it.
1229   while (!WorklistMap.empty()) {
1230     SDNode *N;
1231     // The Worklist holds the SDNodes in order, but it may contain null entries.
1232     do {
1233       N = Worklist.pop_back_val();
1234     } while (!N);
1235
1236     bool GoodWorklistEntry = WorklistMap.erase(N);
1237     (void)GoodWorklistEntry;
1238     assert(GoodWorklistEntry &&
1239            "Found a worklist entry without a corresponding map entry!");
1240
1241     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1242     // N is deleted from the DAG, since they too may now be dead or may have a
1243     // reduced number of uses, allowing other xforms.
1244     if (recursivelyDeleteUnusedNodes(N))
1245       continue;
1246
1247     WorklistRemover DeadNodes(*this);
1248
1249     // If this combine is running after legalizing the DAG, re-legalize any
1250     // nodes pulled off the worklist.
1251     if (Level == AfterLegalizeDAG) {
1252       SmallSetVector<SDNode *, 16> UpdatedNodes;
1253       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1254
1255       for (SDNode *LN : UpdatedNodes) {
1256         AddToWorklist(LN);
1257         AddUsersToWorklist(LN);
1258       }
1259       if (!NIsValid)
1260         continue;
1261     }
1262
1263     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1264
1265     // Add any operands of the new node which have not yet been combined to the
1266     // worklist as well. Because the worklist uniques things already, this
1267     // won't repeatedly process the same operand.
1268     CombinedNodes.insert(N);
1269     for (const SDValue &ChildN : N->op_values())
1270       if (!CombinedNodes.count(ChildN.getNode()))
1271         AddToWorklist(ChildN.getNode());
1272
1273     SDValue RV = combine(N);
1274
1275     if (!RV.getNode())
1276       continue;
1277
1278     ++NodesCombined;
1279
1280     // If we get back the same node we passed in, rather than a new node or
1281     // zero, we know that the node must have defined multiple values and
1282     // CombineTo was used.  Since CombineTo takes care of the worklist
1283     // mechanics for us, we have no work to do in this case.
1284     if (RV.getNode() == N)
1285       continue;
1286
1287     assert(N->getOpcode() != ISD::DELETED_NODE &&
1288            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1289            "Node was deleted but visit returned new node!");
1290
1291     DEBUG(dbgs() << " ... into: ";
1292           RV.getNode()->dump(&DAG));
1293
1294     // Transfer debug value.
1295     DAG.TransferDbgValues(SDValue(N, 0), RV);
1296     if (N->getNumValues() == RV.getNode()->getNumValues())
1297       DAG.ReplaceAllUsesWith(N, RV.getNode());
1298     else {
1299       assert(N->getValueType(0) == RV.getValueType() &&
1300              N->getNumValues() == 1 && "Type mismatch");
1301       SDValue OpV = RV;
1302       DAG.ReplaceAllUsesWith(N, &OpV);
1303     }
1304
1305     // Push the new node and any users onto the worklist
1306     AddToWorklist(RV.getNode());
1307     AddUsersToWorklist(RV.getNode());
1308
1309     // Finally, if the node is now dead, remove it from the graph.  The node
1310     // may not be dead if the replacement process recursively simplified to
1311     // something else needing this node. This will also take care of adding any
1312     // operands which have lost a user to the worklist.
1313     recursivelyDeleteUnusedNodes(N);
1314   }
1315
1316   // If the root changed (e.g. it was a dead load, update the root).
1317   DAG.setRoot(Dummy.getValue());
1318   DAG.RemoveDeadNodes();
1319 }
1320
1321 SDValue DAGCombiner::visit(SDNode *N) {
1322   switch (N->getOpcode()) {
1323   default: break;
1324   case ISD::TokenFactor:        return visitTokenFactor(N);
1325   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1326   case ISD::ADD:                return visitADD(N);
1327   case ISD::SUB:                return visitSUB(N);
1328   case ISD::ADDC:               return visitADDC(N);
1329   case ISD::SUBC:               return visitSUBC(N);
1330   case ISD::ADDE:               return visitADDE(N);
1331   case ISD::SUBE:               return visitSUBE(N);
1332   case ISD::MUL:                return visitMUL(N);
1333   case ISD::SDIV:               return visitSDIV(N);
1334   case ISD::UDIV:               return visitUDIV(N);
1335   case ISD::SREM:               return visitSREM(N);
1336   case ISD::UREM:               return visitUREM(N);
1337   case ISD::MULHU:              return visitMULHU(N);
1338   case ISD::MULHS:              return visitMULHS(N);
1339   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1340   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1341   case ISD::SMULO:              return visitSMULO(N);
1342   case ISD::UMULO:              return visitUMULO(N);
1343   case ISD::SDIVREM:            return visitSDIVREM(N);
1344   case ISD::UDIVREM:            return visitUDIVREM(N);
1345   case ISD::AND:                return visitAND(N);
1346   case ISD::OR:                 return visitOR(N);
1347   case ISD::XOR:                return visitXOR(N);
1348   case ISD::SHL:                return visitSHL(N);
1349   case ISD::SRA:                return visitSRA(N);
1350   case ISD::SRL:                return visitSRL(N);
1351   case ISD::ROTR:
1352   case ISD::ROTL:               return visitRotate(N);
1353   case ISD::BSWAP:              return visitBSWAP(N);
1354   case ISD::CTLZ:               return visitCTLZ(N);
1355   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1356   case ISD::CTTZ:               return visitCTTZ(N);
1357   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1358   case ISD::CTPOP:              return visitCTPOP(N);
1359   case ISD::SELECT:             return visitSELECT(N);
1360   case ISD::VSELECT:            return visitVSELECT(N);
1361   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1362   case ISD::SETCC:              return visitSETCC(N);
1363   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1364   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1365   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1366   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1367   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1368   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1369   case ISD::BITCAST:            return visitBITCAST(N);
1370   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1371   case ISD::FADD:               return visitFADD(N);
1372   case ISD::FSUB:               return visitFSUB(N);
1373   case ISD::FMUL:               return visitFMUL(N);
1374   case ISD::FMA:                return visitFMA(N);
1375   case ISD::FDIV:               return visitFDIV(N);
1376   case ISD::FREM:               return visitFREM(N);
1377   case ISD::FSQRT:              return visitFSQRT(N);
1378   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1379   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1380   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1381   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1382   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1383   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1384   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1385   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1386   case ISD::FNEG:               return visitFNEG(N);
1387   case ISD::FABS:               return visitFABS(N);
1388   case ISD::FFLOOR:             return visitFFLOOR(N);
1389   case ISD::FMINNUM:            return visitFMINNUM(N);
1390   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1391   case ISD::FCEIL:              return visitFCEIL(N);
1392   case ISD::FTRUNC:             return visitFTRUNC(N);
1393   case ISD::BRCOND:             return visitBRCOND(N);
1394   case ISD::BR_CC:              return visitBR_CC(N);
1395   case ISD::LOAD:               return visitLOAD(N);
1396   case ISD::STORE:              return visitSTORE(N);
1397   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1398   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1399   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1400   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1401   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1402   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1403   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1404   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1405   case ISD::MGATHER:            return visitMGATHER(N);
1406   case ISD::MLOAD:              return visitMLOAD(N);
1407   case ISD::MSCATTER:           return visitMSCATTER(N);
1408   case ISD::MSTORE:             return visitMSTORE(N);
1409   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1410   }
1411   return SDValue();
1412 }
1413
1414 SDValue DAGCombiner::combine(SDNode *N) {
1415   SDValue RV = visit(N);
1416
1417   // If nothing happened, try a target-specific DAG combine.
1418   if (!RV.getNode()) {
1419     assert(N->getOpcode() != ISD::DELETED_NODE &&
1420            "Node was deleted but visit returned NULL!");
1421
1422     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1423         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1424
1425       // Expose the DAG combiner to the target combiner impls.
1426       TargetLowering::DAGCombinerInfo
1427         DagCombineInfo(DAG, Level, false, this);
1428
1429       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1430     }
1431   }
1432
1433   // If nothing happened still, try promoting the operation.
1434   if (!RV.getNode()) {
1435     switch (N->getOpcode()) {
1436     default: break;
1437     case ISD::ADD:
1438     case ISD::SUB:
1439     case ISD::MUL:
1440     case ISD::AND:
1441     case ISD::OR:
1442     case ISD::XOR:
1443       RV = PromoteIntBinOp(SDValue(N, 0));
1444       break;
1445     case ISD::SHL:
1446     case ISD::SRA:
1447     case ISD::SRL:
1448       RV = PromoteIntShiftOp(SDValue(N, 0));
1449       break;
1450     case ISD::SIGN_EXTEND:
1451     case ISD::ZERO_EXTEND:
1452     case ISD::ANY_EXTEND:
1453       RV = PromoteExtend(SDValue(N, 0));
1454       break;
1455     case ISD::LOAD:
1456       if (PromoteLoad(SDValue(N, 0)))
1457         RV = SDValue(N, 0);
1458       break;
1459     }
1460   }
1461
1462   // If N is a commutative binary node, try commuting it to enable more
1463   // sdisel CSE.
1464   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1465       N->getNumValues() == 1) {
1466     SDValue N0 = N->getOperand(0);
1467     SDValue N1 = N->getOperand(1);
1468
1469     // Constant operands are canonicalized to RHS.
1470     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1471       SDValue Ops[] = {N1, N0};
1472       SDNode *CSENode;
1473       if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1474         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1475                                       &BinNode->Flags);
1476       } else {
1477         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1478       }
1479       if (CSENode)
1480         return SDValue(CSENode, 0);
1481     }
1482   }
1483
1484   return RV;
1485 }
1486
1487 /// Given a node, return its input chain if it has one, otherwise return a null
1488 /// sd operand.
1489 static SDValue getInputChainForNode(SDNode *N) {
1490   if (unsigned NumOps = N->getNumOperands()) {
1491     if (N->getOperand(0).getValueType() == MVT::Other)
1492       return N->getOperand(0);
1493     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1494       return N->getOperand(NumOps-1);
1495     for (unsigned i = 1; i < NumOps-1; ++i)
1496       if (N->getOperand(i).getValueType() == MVT::Other)
1497         return N->getOperand(i);
1498   }
1499   return SDValue();
1500 }
1501
1502 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1503   // If N has two operands, where one has an input chain equal to the other,
1504   // the 'other' chain is redundant.
1505   if (N->getNumOperands() == 2) {
1506     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1507       return N->getOperand(0);
1508     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1509       return N->getOperand(1);
1510   }
1511
1512   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1513   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1514   SmallPtrSet<SDNode*, 16> SeenOps;
1515   bool Changed = false;             // If we should replace this token factor.
1516
1517   // Start out with this token factor.
1518   TFs.push_back(N);
1519
1520   // Iterate through token factors.  The TFs grows when new token factors are
1521   // encountered.
1522   for (unsigned i = 0; i < TFs.size(); ++i) {
1523     SDNode *TF = TFs[i];
1524
1525     // Check each of the operands.
1526     for (const SDValue &Op : TF->op_values()) {
1527
1528       switch (Op.getOpcode()) {
1529       case ISD::EntryToken:
1530         // Entry tokens don't need to be added to the list. They are
1531         // redundant.
1532         Changed = true;
1533         break;
1534
1535       case ISD::TokenFactor:
1536         if (Op.hasOneUse() &&
1537             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1538           // Queue up for processing.
1539           TFs.push_back(Op.getNode());
1540           // Clean up in case the token factor is removed.
1541           AddToWorklist(Op.getNode());
1542           Changed = true;
1543           break;
1544         }
1545         // Fall thru
1546
1547       default:
1548         // Only add if it isn't already in the list.
1549         if (SeenOps.insert(Op.getNode()).second)
1550           Ops.push_back(Op);
1551         else
1552           Changed = true;
1553         break;
1554       }
1555     }
1556   }
1557
1558   SDValue Result;
1559
1560   // If we've changed things around then replace token factor.
1561   if (Changed) {
1562     if (Ops.empty()) {
1563       // The entry token is the only possible outcome.
1564       Result = DAG.getEntryNode();
1565     } else {
1566       // New and improved token factor.
1567       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1568     }
1569
1570     // Add users to worklist if AA is enabled, since it may introduce
1571     // a lot of new chained token factors while removing memory deps.
1572     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1573       : DAG.getSubtarget().useAA();
1574     return CombineTo(N, Result, UseAA /*add to worklist*/);
1575   }
1576
1577   return Result;
1578 }
1579
1580 /// MERGE_VALUES can always be eliminated.
1581 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1582   WorklistRemover DeadNodes(*this);
1583   // Replacing results may cause a different MERGE_VALUES to suddenly
1584   // be CSE'd with N, and carry its uses with it. Iterate until no
1585   // uses remain, to ensure that the node can be safely deleted.
1586   // First add the users of this node to the work list so that they
1587   // can be tried again once they have new operands.
1588   AddUsersToWorklist(N);
1589   do {
1590     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1591       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1592   } while (!N->use_empty());
1593   deleteAndRecombine(N);
1594   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1595 }
1596
1597 static bool isNullConstant(SDValue V) {
1598   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1599   return Const != nullptr && Const->isNullValue();
1600 }
1601
1602 static bool isNullFPConstant(SDValue V) {
1603   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1604   return Const != nullptr && Const->isZero() && !Const->isNegative();
1605 }
1606
1607 static bool isAllOnesConstant(SDValue V) {
1608   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1609   return Const != nullptr && Const->isAllOnesValue();
1610 }
1611
1612 static bool isOneConstant(SDValue V) {
1613   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1614   return Const != nullptr && Const->isOne();
1615 }
1616
1617 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1618 /// ContantSDNode pointer else nullptr.
1619 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1620   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1621   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1622 }
1623
1624 SDValue DAGCombiner::visitADD(SDNode *N) {
1625   SDValue N0 = N->getOperand(0);
1626   SDValue N1 = N->getOperand(1);
1627   EVT VT = N0.getValueType();
1628
1629   // fold vector ops
1630   if (VT.isVector()) {
1631     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1632       return FoldedVOp;
1633
1634     // fold (add x, 0) -> x, vector edition
1635     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1636       return N0;
1637     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1638       return N1;
1639   }
1640
1641   // fold (add x, undef) -> undef
1642   if (N0.getOpcode() == ISD::UNDEF)
1643     return N0;
1644   if (N1.getOpcode() == ISD::UNDEF)
1645     return N1;
1646   // fold (add c1, c2) -> c1+c2
1647   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1648   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1649   if (N0C && N1C)
1650     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1651   // canonicalize constant to RHS
1652   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1653      !isConstantIntBuildVectorOrConstantInt(N1))
1654     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1655   // fold (add x, 0) -> x
1656   if (isNullConstant(N1))
1657     return N0;
1658   // fold (add Sym, c) -> Sym+c
1659   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1660     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1661         GA->getOpcode() == ISD::GlobalAddress)
1662       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1663                                   GA->getOffset() +
1664                                     (uint64_t)N1C->getSExtValue());
1665   // fold ((c1-A)+c2) -> (c1+c2)-A
1666   if (N1C && N0.getOpcode() == ISD::SUB)
1667     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1668       SDLoc DL(N);
1669       return DAG.getNode(ISD::SUB, DL, VT,
1670                          DAG.getConstant(N1C->getAPIntValue()+
1671                                          N0C->getAPIntValue(), DL, VT),
1672                          N0.getOperand(1));
1673     }
1674   // reassociate add
1675   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1676     return RADD;
1677   // fold ((0-A) + B) -> B-A
1678   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1679     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1680   // fold (A + (0-B)) -> A-B
1681   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1682     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1683   // fold (A+(B-A)) -> B
1684   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1685     return N1.getOperand(0);
1686   // fold ((B-A)+A) -> B
1687   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1688     return N0.getOperand(0);
1689   // fold (A+(B-(A+C))) to (B-C)
1690   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1691       N0 == N1.getOperand(1).getOperand(0))
1692     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1693                        N1.getOperand(1).getOperand(1));
1694   // fold (A+(B-(C+A))) to (B-C)
1695   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1696       N0 == N1.getOperand(1).getOperand(1))
1697     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1698                        N1.getOperand(1).getOperand(0));
1699   // fold (A+((B-A)+or-C)) to (B+or-C)
1700   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1701       N1.getOperand(0).getOpcode() == ISD::SUB &&
1702       N0 == N1.getOperand(0).getOperand(1))
1703     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1704                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1705
1706   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1707   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1708     SDValue N00 = N0.getOperand(0);
1709     SDValue N01 = N0.getOperand(1);
1710     SDValue N10 = N1.getOperand(0);
1711     SDValue N11 = N1.getOperand(1);
1712
1713     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1714       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1715                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1716                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1717   }
1718
1719   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1720     return SDValue(N, 0);
1721
1722   // fold (a+b) -> (a|b) iff a and b share no bits.
1723   if (VT.isInteger() && !VT.isVector()) {
1724     APInt LHSZero, LHSOne;
1725     APInt RHSZero, RHSOne;
1726     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1727
1728     if (LHSZero.getBoolValue()) {
1729       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1730
1731       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1732       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1733       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1734         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1735           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1736       }
1737     }
1738   }
1739
1740   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1741   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1742       isNullConstant(N1.getOperand(0).getOperand(0)))
1743     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1744                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1745                                    N1.getOperand(0).getOperand(1),
1746                                    N1.getOperand(1)));
1747   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1748       isNullConstant(N0.getOperand(0).getOperand(0)))
1749     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1750                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1751                                    N0.getOperand(0).getOperand(1),
1752                                    N0.getOperand(1)));
1753
1754   if (N1.getOpcode() == ISD::AND) {
1755     SDValue AndOp0 = N1.getOperand(0);
1756     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1757     unsigned DestBits = VT.getScalarType().getSizeInBits();
1758
1759     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1760     // and similar xforms where the inner op is either ~0 or 0.
1761     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1762       SDLoc DL(N);
1763       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1764     }
1765   }
1766
1767   // add (sext i1), X -> sub X, (zext i1)
1768   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1769       N0.getOperand(0).getValueType() == MVT::i1 &&
1770       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1771     SDLoc DL(N);
1772     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1773     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1774   }
1775
1776   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1777   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1778     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1779     if (TN->getVT() == MVT::i1) {
1780       SDLoc DL(N);
1781       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1782                                  DAG.getConstant(1, DL, VT));
1783       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1784     }
1785   }
1786
1787   return SDValue();
1788 }
1789
1790 SDValue DAGCombiner::visitADDC(SDNode *N) {
1791   SDValue N0 = N->getOperand(0);
1792   SDValue N1 = N->getOperand(1);
1793   EVT VT = N0.getValueType();
1794
1795   // If the flag result is dead, turn this into an ADD.
1796   if (!N->hasAnyUseOfValue(1))
1797     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1798                      DAG.getNode(ISD::CARRY_FALSE,
1799                                  SDLoc(N), MVT::Glue));
1800
1801   // canonicalize constant to RHS.
1802   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1803   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1804   if (N0C && !N1C)
1805     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1806
1807   // fold (addc x, 0) -> x + no carry out
1808   if (isNullConstant(N1))
1809     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1810                                         SDLoc(N), MVT::Glue));
1811
1812   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1813   APInt LHSZero, LHSOne;
1814   APInt RHSZero, RHSOne;
1815   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1816
1817   if (LHSZero.getBoolValue()) {
1818     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1819
1820     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1821     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1822     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1823       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1824                        DAG.getNode(ISD::CARRY_FALSE,
1825                                    SDLoc(N), MVT::Glue));
1826   }
1827
1828   return SDValue();
1829 }
1830
1831 SDValue DAGCombiner::visitADDE(SDNode *N) {
1832   SDValue N0 = N->getOperand(0);
1833   SDValue N1 = N->getOperand(1);
1834   SDValue CarryIn = N->getOperand(2);
1835
1836   // canonicalize constant to RHS
1837   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1838   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1839   if (N0C && !N1C)
1840     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1841                        N1, N0, CarryIn);
1842
1843   // fold (adde x, y, false) -> (addc x, y)
1844   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1845     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1846
1847   return SDValue();
1848 }
1849
1850 // Since it may not be valid to emit a fold to zero for vector initializers
1851 // check if we can before folding.
1852 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1853                              SelectionDAG &DAG,
1854                              bool LegalOperations, bool LegalTypes) {
1855   if (!VT.isVector())
1856     return DAG.getConstant(0, DL, VT);
1857   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1858     return DAG.getConstant(0, DL, VT);
1859   return SDValue();
1860 }
1861
1862 SDValue DAGCombiner::visitSUB(SDNode *N) {
1863   SDValue N0 = N->getOperand(0);
1864   SDValue N1 = N->getOperand(1);
1865   EVT VT = N0.getValueType();
1866
1867   // fold vector ops
1868   if (VT.isVector()) {
1869     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1870       return FoldedVOp;
1871
1872     // fold (sub x, 0) -> x, vector edition
1873     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1874       return N0;
1875   }
1876
1877   // fold (sub x, x) -> 0
1878   // FIXME: Refactor this and xor and other similar operations together.
1879   if (N0 == N1)
1880     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1881   // fold (sub c1, c2) -> c1-c2
1882   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1883   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1884   if (N0C && N1C)
1885     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1886   // fold (sub x, c) -> (add x, -c)
1887   if (N1C) {
1888     SDLoc DL(N);
1889     return DAG.getNode(ISD::ADD, DL, VT, N0,
1890                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1891   }
1892   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1893   if (isAllOnesConstant(N0))
1894     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1895   // fold A-(A-B) -> B
1896   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1897     return N1.getOperand(1);
1898   // fold (A+B)-A -> B
1899   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1900     return N0.getOperand(1);
1901   // fold (A+B)-B -> A
1902   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1903     return N0.getOperand(0);
1904   // fold C2-(A+C1) -> (C2-C1)-A
1905   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1906     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1907   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1908     SDLoc DL(N);
1909     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1910                                    DL, VT);
1911     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1912                        N1.getOperand(0));
1913   }
1914   // fold ((A+(B+or-C))-B) -> A+or-C
1915   if (N0.getOpcode() == ISD::ADD &&
1916       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1917        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1918       N0.getOperand(1).getOperand(0) == N1)
1919     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1920                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1921   // fold ((A+(C+B))-B) -> A+C
1922   if (N0.getOpcode() == ISD::ADD &&
1923       N0.getOperand(1).getOpcode() == ISD::ADD &&
1924       N0.getOperand(1).getOperand(1) == N1)
1925     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1926                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1927   // fold ((A-(B-C))-C) -> A-B
1928   if (N0.getOpcode() == ISD::SUB &&
1929       N0.getOperand(1).getOpcode() == ISD::SUB &&
1930       N0.getOperand(1).getOperand(1) == N1)
1931     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1932                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1933
1934   // If either operand of a sub is undef, the result is undef
1935   if (N0.getOpcode() == ISD::UNDEF)
1936     return N0;
1937   if (N1.getOpcode() == ISD::UNDEF)
1938     return N1;
1939
1940   // If the relocation model supports it, consider symbol offsets.
1941   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1942     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1943       // fold (sub Sym, c) -> Sym-c
1944       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1945         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1946                                     GA->getOffset() -
1947                                       (uint64_t)N1C->getSExtValue());
1948       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1949       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1950         if (GA->getGlobal() == GB->getGlobal())
1951           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1952                                  SDLoc(N), VT);
1953     }
1954
1955   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1956   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1957     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1958     if (TN->getVT() == MVT::i1) {
1959       SDLoc DL(N);
1960       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1961                                  DAG.getConstant(1, DL, VT));
1962       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1963     }
1964   }
1965
1966   return SDValue();
1967 }
1968
1969 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1970   SDValue N0 = N->getOperand(0);
1971   SDValue N1 = N->getOperand(1);
1972   EVT VT = N0.getValueType();
1973
1974   // If the flag result is dead, turn this into an SUB.
1975   if (!N->hasAnyUseOfValue(1))
1976     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1977                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1978                                  MVT::Glue));
1979
1980   // fold (subc x, x) -> 0 + no borrow
1981   if (N0 == N1) {
1982     SDLoc DL(N);
1983     return CombineTo(N, DAG.getConstant(0, DL, VT),
1984                      DAG.getNode(ISD::CARRY_FALSE, DL,
1985                                  MVT::Glue));
1986   }
1987
1988   // fold (subc x, 0) -> x + no borrow
1989   if (isNullConstant(N1))
1990     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1991                                         MVT::Glue));
1992
1993   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1994   if (isAllOnesConstant(N0))
1995     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1996                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1997                                  MVT::Glue));
1998
1999   return SDValue();
2000 }
2001
2002 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2003   SDValue N0 = N->getOperand(0);
2004   SDValue N1 = N->getOperand(1);
2005   SDValue CarryIn = N->getOperand(2);
2006
2007   // fold (sube x, y, false) -> (subc x, y)
2008   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2009     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2010
2011   return SDValue();
2012 }
2013
2014 SDValue DAGCombiner::visitMUL(SDNode *N) {
2015   SDValue N0 = N->getOperand(0);
2016   SDValue N1 = N->getOperand(1);
2017   EVT VT = N0.getValueType();
2018
2019   // fold (mul x, undef) -> 0
2020   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2021     return DAG.getConstant(0, SDLoc(N), VT);
2022
2023   bool N0IsConst = false;
2024   bool N1IsConst = false;
2025   bool N1IsOpaqueConst = false;
2026   bool N0IsOpaqueConst = false;
2027   APInt ConstValue0, ConstValue1;
2028   // fold vector ops
2029   if (VT.isVector()) {
2030     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2031       return FoldedVOp;
2032
2033     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2034     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2035   } else {
2036     N0IsConst = isa<ConstantSDNode>(N0);
2037     if (N0IsConst) {
2038       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2039       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2040     }
2041     N1IsConst = isa<ConstantSDNode>(N1);
2042     if (N1IsConst) {
2043       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2044       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2045     }
2046   }
2047
2048   // fold (mul c1, c2) -> c1*c2
2049   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2050     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2051                                       N0.getNode(), N1.getNode());
2052
2053   // canonicalize constant to RHS (vector doesn't have to splat)
2054   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2055      !isConstantIntBuildVectorOrConstantInt(N1))
2056     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2057   // fold (mul x, 0) -> 0
2058   if (N1IsConst && ConstValue1 == 0)
2059     return N1;
2060   // We require a splat of the entire scalar bit width for non-contiguous
2061   // bit patterns.
2062   bool IsFullSplat =
2063     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2064   // fold (mul x, 1) -> x
2065   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2066     return N0;
2067   // fold (mul x, -1) -> 0-x
2068   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2069     SDLoc DL(N);
2070     return DAG.getNode(ISD::SUB, DL, VT,
2071                        DAG.getConstant(0, DL, VT), N0);
2072   }
2073   // fold (mul x, (1 << c)) -> x << c
2074   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2075       IsFullSplat) {
2076     SDLoc DL(N);
2077     return DAG.getNode(ISD::SHL, DL, VT, N0,
2078                        DAG.getConstant(ConstValue1.logBase2(), DL,
2079                                        getShiftAmountTy(N0.getValueType())));
2080   }
2081   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2082   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2083       IsFullSplat) {
2084     unsigned Log2Val = (-ConstValue1).logBase2();
2085     SDLoc DL(N);
2086     // FIXME: If the input is something that is easily negated (e.g. a
2087     // single-use add), we should put the negate there.
2088     return DAG.getNode(ISD::SUB, DL, VT,
2089                        DAG.getConstant(0, DL, VT),
2090                        DAG.getNode(ISD::SHL, DL, VT, N0,
2091                             DAG.getConstant(Log2Val, DL,
2092                                       getShiftAmountTy(N0.getValueType()))));
2093   }
2094
2095   APInt Val;
2096   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2097   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2098       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2099                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2100     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2101                              N1, N0.getOperand(1));
2102     AddToWorklist(C3.getNode());
2103     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2104                        N0.getOperand(0), C3);
2105   }
2106
2107   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2108   // use.
2109   {
2110     SDValue Sh(nullptr,0), Y(nullptr,0);
2111     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2112     if (N0.getOpcode() == ISD::SHL &&
2113         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2114                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2115         N0.getNode()->hasOneUse()) {
2116       Sh = N0; Y = N1;
2117     } else if (N1.getOpcode() == ISD::SHL &&
2118                isa<ConstantSDNode>(N1.getOperand(1)) &&
2119                N1.getNode()->hasOneUse()) {
2120       Sh = N1; Y = N0;
2121     }
2122
2123     if (Sh.getNode()) {
2124       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2125                                 Sh.getOperand(0), Y);
2126       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2127                          Mul, Sh.getOperand(1));
2128     }
2129   }
2130
2131   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2132   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2133       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2134                      isa<ConstantSDNode>(N0.getOperand(1))))
2135     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2136                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2137                                    N0.getOperand(0), N1),
2138                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2139                                    N0.getOperand(1), N1));
2140
2141   // reassociate mul
2142   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2143     return RMUL;
2144
2145   return SDValue();
2146 }
2147
2148 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2149   SDValue N0 = N->getOperand(0);
2150   SDValue N1 = N->getOperand(1);
2151   EVT VT = N->getValueType(0);
2152
2153   // fold vector ops
2154   if (VT.isVector())
2155     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2156       return FoldedVOp;
2157
2158   // fold (sdiv c1, c2) -> c1/c2
2159   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2160   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2161   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2162     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2163   // fold (sdiv X, 1) -> X
2164   if (N1C && N1C->isOne())
2165     return N0;
2166   // fold (sdiv X, -1) -> 0-X
2167   if (N1C && N1C->isAllOnesValue()) {
2168     SDLoc DL(N);
2169     return DAG.getNode(ISD::SUB, DL, VT,
2170                        DAG.getConstant(0, DL, VT), N0);
2171   }
2172   // If we know the sign bits of both operands are zero, strength reduce to a
2173   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2174   if (!VT.isVector()) {
2175     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2176       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2177                          N0, N1);
2178   }
2179
2180   // fold (sdiv X, pow2) -> simple ops after legalize
2181   // FIXME: We check for the exact bit here because the generic lowering gives
2182   // better results in that case. The target-specific lowering should learn how
2183   // to handle exact sdivs efficiently.
2184   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2185       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2186       (N1C->getAPIntValue().isPowerOf2() ||
2187        (-N1C->getAPIntValue()).isPowerOf2())) {
2188     // If dividing by powers of two is cheap, then don't perform the following
2189     // fold.
2190     if (TLI.isPow2SDivCheap())
2191       return SDValue();
2192
2193     // Target-specific implementation of sdiv x, pow2.
2194     SDValue Res = BuildSDIVPow2(N);
2195     if (Res.getNode())
2196       return Res;
2197
2198     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2199     SDLoc DL(N);
2200
2201     // Splat the sign bit into the register
2202     SDValue SGN =
2203         DAG.getNode(ISD::SRA, DL, VT, N0,
2204                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2205                                     getShiftAmountTy(N0.getValueType())));
2206     AddToWorklist(SGN.getNode());
2207
2208     // Add (N0 < 0) ? abs2 - 1 : 0;
2209     SDValue SRL =
2210         DAG.getNode(ISD::SRL, DL, VT, SGN,
2211                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2212                                     getShiftAmountTy(SGN.getValueType())));
2213     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2214     AddToWorklist(SRL.getNode());
2215     AddToWorklist(ADD.getNode());    // Divide by pow2
2216     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2217                   DAG.getConstant(lg2, DL,
2218                                   getShiftAmountTy(ADD.getValueType())));
2219
2220     // If we're dividing by a positive value, we're done.  Otherwise, we must
2221     // negate the result.
2222     if (N1C->getAPIntValue().isNonNegative())
2223       return SRA;
2224
2225     AddToWorklist(SRA.getNode());
2226     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2227   }
2228
2229   // If integer divide is expensive and we satisfy the requirements, emit an
2230   // alternate sequence.
2231   if (N1C && !TLI.isIntDivCheap()) {
2232     SDValue Op = BuildSDIV(N);
2233     if (Op.getNode()) return Op;
2234   }
2235
2236   // undef / X -> 0
2237   if (N0.getOpcode() == ISD::UNDEF)
2238     return DAG.getConstant(0, SDLoc(N), VT);
2239   // X / undef -> undef
2240   if (N1.getOpcode() == ISD::UNDEF)
2241     return N1;
2242
2243   return SDValue();
2244 }
2245
2246 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2247   SDValue N0 = N->getOperand(0);
2248   SDValue N1 = N->getOperand(1);
2249   EVT VT = N->getValueType(0);
2250
2251   // fold vector ops
2252   if (VT.isVector())
2253     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2254       return FoldedVOp;
2255
2256   // fold (udiv c1, c2) -> c1/c2
2257   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2258   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2259   if (N0C && N1C)
2260     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2261                                                     N0C, N1C))
2262       return Folded;
2263   // fold (udiv x, (1 << c)) -> x >>u c
2264   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2265     SDLoc DL(N);
2266     return DAG.getNode(ISD::SRL, DL, VT, N0,
2267                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2268                                        getShiftAmountTy(N0.getValueType())));
2269   }
2270   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2271   if (N1.getOpcode() == ISD::SHL) {
2272     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2273       if (SHC->getAPIntValue().isPowerOf2()) {
2274         EVT ADDVT = N1.getOperand(1).getValueType();
2275         SDLoc DL(N);
2276         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2277                                   N1.getOperand(1),
2278                                   DAG.getConstant(SHC->getAPIntValue()
2279                                                                   .logBase2(),
2280                                                   DL, ADDVT));
2281         AddToWorklist(Add.getNode());
2282         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2283       }
2284     }
2285   }
2286   // fold (udiv x, c) -> alternate
2287   if (N1C && !TLI.isIntDivCheap()) {
2288     SDValue Op = BuildUDIV(N);
2289     if (Op.getNode()) return Op;
2290   }
2291
2292   // undef / X -> 0
2293   if (N0.getOpcode() == ISD::UNDEF)
2294     return DAG.getConstant(0, SDLoc(N), VT);
2295   // X / undef -> undef
2296   if (N1.getOpcode() == ISD::UNDEF)
2297     return N1;
2298
2299   return SDValue();
2300 }
2301
2302 SDValue DAGCombiner::visitSREM(SDNode *N) {
2303   SDValue N0 = N->getOperand(0);
2304   SDValue N1 = N->getOperand(1);
2305   EVT VT = N->getValueType(0);
2306
2307   // fold (srem c1, c2) -> c1%c2
2308   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2309   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2310   if (N0C && N1C)
2311     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2312                                                     N0C, N1C))
2313       return Folded;
2314   // If we know the sign bits of both operands are zero, strength reduce to a
2315   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2316   if (!VT.isVector()) {
2317     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2318       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2319   }
2320
2321   // If X/C can be simplified by the division-by-constant logic, lower
2322   // X%C to the equivalent of X-X/C*C.
2323   if (N1C && !N1C->isNullValue()) {
2324     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2325     AddToWorklist(Div.getNode());
2326     SDValue OptimizedDiv = combine(Div.getNode());
2327     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2328       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2329                                 OptimizedDiv, N1);
2330       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2331       AddToWorklist(Mul.getNode());
2332       return Sub;
2333     }
2334   }
2335
2336   // undef % X -> 0
2337   if (N0.getOpcode() == ISD::UNDEF)
2338     return DAG.getConstant(0, SDLoc(N), VT);
2339   // X % undef -> undef
2340   if (N1.getOpcode() == ISD::UNDEF)
2341     return N1;
2342
2343   return SDValue();
2344 }
2345
2346 SDValue DAGCombiner::visitUREM(SDNode *N) {
2347   SDValue N0 = N->getOperand(0);
2348   SDValue N1 = N->getOperand(1);
2349   EVT VT = N->getValueType(0);
2350
2351   // fold (urem c1, c2) -> c1%c2
2352   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2353   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2354   if (N0C && N1C)
2355     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2356                                                     N0C, N1C))
2357       return Folded;
2358   // fold (urem x, pow2) -> (and x, pow2-1)
2359   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2360       N1C->getAPIntValue().isPowerOf2()) {
2361     SDLoc DL(N);
2362     return DAG.getNode(ISD::AND, DL, VT, N0,
2363                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2364   }
2365   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2366   if (N1.getOpcode() == ISD::SHL) {
2367     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2368       if (SHC->getAPIntValue().isPowerOf2()) {
2369         SDLoc DL(N);
2370         SDValue Add =
2371           DAG.getNode(ISD::ADD, DL, VT, N1,
2372                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2373                                  VT));
2374         AddToWorklist(Add.getNode());
2375         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2376       }
2377     }
2378   }
2379
2380   // If X/C can be simplified by the division-by-constant logic, lower
2381   // X%C to the equivalent of X-X/C*C.
2382   if (N1C && !N1C->isNullValue()) {
2383     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2384     AddToWorklist(Div.getNode());
2385     SDValue OptimizedDiv = combine(Div.getNode());
2386     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2387       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2388                                 OptimizedDiv, N1);
2389       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2390       AddToWorklist(Mul.getNode());
2391       return Sub;
2392     }
2393   }
2394
2395   // undef % X -> 0
2396   if (N0.getOpcode() == ISD::UNDEF)
2397     return DAG.getConstant(0, SDLoc(N), VT);
2398   // X % undef -> undef
2399   if (N1.getOpcode() == ISD::UNDEF)
2400     return N1;
2401
2402   return SDValue();
2403 }
2404
2405 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2406   SDValue N0 = N->getOperand(0);
2407   SDValue N1 = N->getOperand(1);
2408   EVT VT = N->getValueType(0);
2409   SDLoc DL(N);
2410
2411   // fold (mulhs x, 0) -> 0
2412   if (isNullConstant(N1))
2413     return N1;
2414   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2415   if (isOneConstant(N1)) {
2416     SDLoc DL(N);
2417     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2418                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2419                                        DL,
2420                                        getShiftAmountTy(N0.getValueType())));
2421   }
2422   // fold (mulhs x, undef) -> 0
2423   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2424     return DAG.getConstant(0, SDLoc(N), VT);
2425
2426   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2427   // plus a shift.
2428   if (VT.isSimple() && !VT.isVector()) {
2429     MVT Simple = VT.getSimpleVT();
2430     unsigned SimpleSize = Simple.getSizeInBits();
2431     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2432     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2433       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2434       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2435       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2436       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2437             DAG.getConstant(SimpleSize, DL,
2438                             getShiftAmountTy(N1.getValueType())));
2439       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2440     }
2441   }
2442
2443   return SDValue();
2444 }
2445
2446 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2447   SDValue N0 = N->getOperand(0);
2448   SDValue N1 = N->getOperand(1);
2449   EVT VT = N->getValueType(0);
2450   SDLoc DL(N);
2451
2452   // fold (mulhu x, 0) -> 0
2453   if (isNullConstant(N1))
2454     return N1;
2455   // fold (mulhu x, 1) -> 0
2456   if (isOneConstant(N1))
2457     return DAG.getConstant(0, DL, N0.getValueType());
2458   // fold (mulhu x, undef) -> 0
2459   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2460     return DAG.getConstant(0, DL, VT);
2461
2462   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2463   // plus a shift.
2464   if (VT.isSimple() && !VT.isVector()) {
2465     MVT Simple = VT.getSimpleVT();
2466     unsigned SimpleSize = Simple.getSizeInBits();
2467     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2468     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2469       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2470       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2471       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2472       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2473             DAG.getConstant(SimpleSize, DL,
2474                             getShiftAmountTy(N1.getValueType())));
2475       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2476     }
2477   }
2478
2479   return SDValue();
2480 }
2481
2482 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2483 /// give the opcodes for the two computations that are being performed. Return
2484 /// true if a simplification was made.
2485 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2486                                                 unsigned HiOp) {
2487   // If the high half is not needed, just compute the low half.
2488   bool HiExists = N->hasAnyUseOfValue(1);
2489   if (!HiExists &&
2490       (!LegalOperations ||
2491        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2492     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2493     return CombineTo(N, Res, Res);
2494   }
2495
2496   // If the low half is not needed, just compute the high half.
2497   bool LoExists = N->hasAnyUseOfValue(0);
2498   if (!LoExists &&
2499       (!LegalOperations ||
2500        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2501     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2502     return CombineTo(N, Res, Res);
2503   }
2504
2505   // If both halves are used, return as it is.
2506   if (LoExists && HiExists)
2507     return SDValue();
2508
2509   // If the two computed results can be simplified separately, separate them.
2510   if (LoExists) {
2511     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2512     AddToWorklist(Lo.getNode());
2513     SDValue LoOpt = combine(Lo.getNode());
2514     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2515         (!LegalOperations ||
2516          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2517       return CombineTo(N, LoOpt, LoOpt);
2518   }
2519
2520   if (HiExists) {
2521     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2522     AddToWorklist(Hi.getNode());
2523     SDValue HiOpt = combine(Hi.getNode());
2524     if (HiOpt.getNode() && HiOpt != Hi &&
2525         (!LegalOperations ||
2526          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2527       return CombineTo(N, HiOpt, HiOpt);
2528   }
2529
2530   return SDValue();
2531 }
2532
2533 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2534   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2535   if (Res.getNode()) return Res;
2536
2537   EVT VT = N->getValueType(0);
2538   SDLoc DL(N);
2539
2540   // If the type is twice as wide is legal, transform the mulhu to a wider
2541   // multiply plus a shift.
2542   if (VT.isSimple() && !VT.isVector()) {
2543     MVT Simple = VT.getSimpleVT();
2544     unsigned SimpleSize = Simple.getSizeInBits();
2545     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2546     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2547       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2548       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2549       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2550       // Compute the high part as N1.
2551       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2552             DAG.getConstant(SimpleSize, DL,
2553                             getShiftAmountTy(Lo.getValueType())));
2554       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2555       // Compute the low part as N0.
2556       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2557       return CombineTo(N, Lo, Hi);
2558     }
2559   }
2560
2561   return SDValue();
2562 }
2563
2564 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2565   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2566   if (Res.getNode()) return Res;
2567
2568   EVT VT = N->getValueType(0);
2569   SDLoc DL(N);
2570
2571   // If the type is twice as wide is legal, transform the mulhu to a wider
2572   // multiply plus a shift.
2573   if (VT.isSimple() && !VT.isVector()) {
2574     MVT Simple = VT.getSimpleVT();
2575     unsigned SimpleSize = Simple.getSizeInBits();
2576     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2577     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2578       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2579       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2580       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2581       // Compute the high part as N1.
2582       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2583             DAG.getConstant(SimpleSize, DL,
2584                             getShiftAmountTy(Lo.getValueType())));
2585       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2586       // Compute the low part as N0.
2587       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2588       return CombineTo(N, Lo, Hi);
2589     }
2590   }
2591
2592   return SDValue();
2593 }
2594
2595 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2596   // (smulo x, 2) -> (saddo x, x)
2597   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2598     if (C2->getAPIntValue() == 2)
2599       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2600                          N->getOperand(0), N->getOperand(0));
2601
2602   return SDValue();
2603 }
2604
2605 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2606   // (umulo x, 2) -> (uaddo x, x)
2607   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2608     if (C2->getAPIntValue() == 2)
2609       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2610                          N->getOperand(0), N->getOperand(0));
2611
2612   return SDValue();
2613 }
2614
2615 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2616   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2617   if (Res.getNode()) return Res;
2618
2619   return SDValue();
2620 }
2621
2622 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2623   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2624   if (Res.getNode()) return Res;
2625
2626   return SDValue();
2627 }
2628
2629 /// If this is a binary operator with two operands of the same opcode, try to
2630 /// simplify it.
2631 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2632   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2633   EVT VT = N0.getValueType();
2634   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2635
2636   // Bail early if none of these transforms apply.
2637   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2638
2639   // For each of OP in AND/OR/XOR:
2640   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2641   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2642   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2643   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2644   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2645   //
2646   // do not sink logical op inside of a vector extend, since it may combine
2647   // into a vsetcc.
2648   EVT Op0VT = N0.getOperand(0).getValueType();
2649   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2650        N0.getOpcode() == ISD::SIGN_EXTEND ||
2651        N0.getOpcode() == ISD::BSWAP ||
2652        // Avoid infinite looping with PromoteIntBinOp.
2653        (N0.getOpcode() == ISD::ANY_EXTEND &&
2654         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2655        (N0.getOpcode() == ISD::TRUNCATE &&
2656         (!TLI.isZExtFree(VT, Op0VT) ||
2657          !TLI.isTruncateFree(Op0VT, VT)) &&
2658         TLI.isTypeLegal(Op0VT))) &&
2659       !VT.isVector() &&
2660       Op0VT == N1.getOperand(0).getValueType() &&
2661       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2662     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2663                                  N0.getOperand(0).getValueType(),
2664                                  N0.getOperand(0), N1.getOperand(0));
2665     AddToWorklist(ORNode.getNode());
2666     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2667   }
2668
2669   // For each of OP in SHL/SRL/SRA/AND...
2670   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2671   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2672   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2673   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2674        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2675       N0.getOperand(1) == N1.getOperand(1)) {
2676     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2677                                  N0.getOperand(0).getValueType(),
2678                                  N0.getOperand(0), N1.getOperand(0));
2679     AddToWorklist(ORNode.getNode());
2680     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2681                        ORNode, N0.getOperand(1));
2682   }
2683
2684   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2685   // Only perform this optimization after type legalization and before
2686   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2687   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2688   // we don't want to undo this promotion.
2689   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2690   // on scalars.
2691   if ((N0.getOpcode() == ISD::BITCAST ||
2692        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2693       Level == AfterLegalizeTypes) {
2694     SDValue In0 = N0.getOperand(0);
2695     SDValue In1 = N1.getOperand(0);
2696     EVT In0Ty = In0.getValueType();
2697     EVT In1Ty = In1.getValueType();
2698     SDLoc DL(N);
2699     // If both incoming values are integers, and the original types are the
2700     // same.
2701     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2702       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2703       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2704       AddToWorklist(Op.getNode());
2705       return BC;
2706     }
2707   }
2708
2709   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2710   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2711   // If both shuffles use the same mask, and both shuffle within a single
2712   // vector, then it is worthwhile to move the swizzle after the operation.
2713   // The type-legalizer generates this pattern when loading illegal
2714   // vector types from memory. In many cases this allows additional shuffle
2715   // optimizations.
2716   // There are other cases where moving the shuffle after the xor/and/or
2717   // is profitable even if shuffles don't perform a swizzle.
2718   // If both shuffles use the same mask, and both shuffles have the same first
2719   // or second operand, then it might still be profitable to move the shuffle
2720   // after the xor/and/or operation.
2721   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2722     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2723     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2724
2725     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2726            "Inputs to shuffles are not the same type");
2727
2728     // Check that both shuffles use the same mask. The masks are known to be of
2729     // the same length because the result vector type is the same.
2730     // Check also that shuffles have only one use to avoid introducing extra
2731     // instructions.
2732     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2733         SVN0->getMask().equals(SVN1->getMask())) {
2734       SDValue ShOp = N0->getOperand(1);
2735
2736       // Don't try to fold this node if it requires introducing a
2737       // build vector of all zeros that might be illegal at this stage.
2738       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2739         if (!LegalTypes)
2740           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2741         else
2742           ShOp = SDValue();
2743       }
2744
2745       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2746       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2747       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2748       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2749         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2750                                       N0->getOperand(0), N1->getOperand(0));
2751         AddToWorklist(NewNode.getNode());
2752         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2753                                     &SVN0->getMask()[0]);
2754       }
2755
2756       // Don't try to fold this node if it requires introducing a
2757       // build vector of all zeros that might be illegal at this stage.
2758       ShOp = N0->getOperand(0);
2759       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2760         if (!LegalTypes)
2761           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2762         else
2763           ShOp = SDValue();
2764       }
2765
2766       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2767       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2768       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2769       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2770         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2771                                       N0->getOperand(1), N1->getOperand(1));
2772         AddToWorklist(NewNode.getNode());
2773         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2774                                     &SVN0->getMask()[0]);
2775       }
2776     }
2777   }
2778
2779   return SDValue();
2780 }
2781
2782 /// This contains all DAGCombine rules which reduce two values combined by
2783 /// an And operation to a single value. This makes them reusable in the context
2784 /// of visitSELECT(). Rules involving constants are not included as
2785 /// visitSELECT() already handles those cases.
2786 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2787                                   SDNode *LocReference) {
2788   EVT VT = N1.getValueType();
2789
2790   // fold (and x, undef) -> 0
2791   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2792     return DAG.getConstant(0, SDLoc(LocReference), VT);
2793   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2794   SDValue LL, LR, RL, RR, CC0, CC1;
2795   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2796     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2797     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2798
2799     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2800         LL.getValueType().isInteger()) {
2801       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2802       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2803         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2804                                      LR.getValueType(), LL, RL);
2805         AddToWorklist(ORNode.getNode());
2806         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2807       }
2808       if (isAllOnesConstant(LR)) {
2809         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2810         if (Op1 == ISD::SETEQ) {
2811           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2812                                         LR.getValueType(), LL, RL);
2813           AddToWorklist(ANDNode.getNode());
2814           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2815         }
2816         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2817         if (Op1 == ISD::SETGT) {
2818           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2819                                        LR.getValueType(), LL, RL);
2820           AddToWorklist(ORNode.getNode());
2821           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2822         }
2823       }
2824     }
2825     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2826     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2827         Op0 == Op1 && LL.getValueType().isInteger() &&
2828       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2829                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2830       SDLoc DL(N0);
2831       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2832                                     LL, DAG.getConstant(1, DL,
2833                                                         LL.getValueType()));
2834       AddToWorklist(ADDNode.getNode());
2835       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2836                           DAG.getConstant(2, DL, LL.getValueType()),
2837                           ISD::SETUGE);
2838     }
2839     // canonicalize equivalent to ll == rl
2840     if (LL == RR && LR == RL) {
2841       Op1 = ISD::getSetCCSwappedOperands(Op1);
2842       std::swap(RL, RR);
2843     }
2844     if (LL == RL && LR == RR) {
2845       bool isInteger = LL.getValueType().isInteger();
2846       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2847       if (Result != ISD::SETCC_INVALID &&
2848           (!LegalOperations ||
2849            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2850             TLI.isOperationLegal(ISD::SETCC,
2851                             getSetCCResultType(N0.getSimpleValueType())))))
2852         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2853                             LL, LR, Result);
2854     }
2855   }
2856
2857   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2858       VT.getSizeInBits() <= 64) {
2859     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2860       APInt ADDC = ADDI->getAPIntValue();
2861       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2862         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2863         // immediate for an add, but it is legal if its top c2 bits are set,
2864         // transform the ADD so the immediate doesn't need to be materialized
2865         // in a register.
2866         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2867           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2868                                              SRLI->getZExtValue());
2869           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2870             ADDC |= Mask;
2871             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2872               SDLoc DL(N0);
2873               SDValue NewAdd =
2874                 DAG.getNode(ISD::ADD, DL, VT,
2875                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2876               CombineTo(N0.getNode(), NewAdd);
2877               // Return N so it doesn't get rechecked!
2878               return SDValue(LocReference, 0);
2879             }
2880           }
2881         }
2882       }
2883     }
2884   }
2885
2886   return SDValue();
2887 }
2888
2889 SDValue DAGCombiner::visitAND(SDNode *N) {
2890   SDValue N0 = N->getOperand(0);
2891   SDValue N1 = N->getOperand(1);
2892   EVT VT = N1.getValueType();
2893
2894   // fold vector ops
2895   if (VT.isVector()) {
2896     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2897       return FoldedVOp;
2898
2899     // fold (and x, 0) -> 0, vector edition
2900     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2901       // do not return N0, because undef node may exist in N0
2902       return DAG.getConstant(
2903           APInt::getNullValue(
2904               N0.getValueType().getScalarType().getSizeInBits()),
2905           SDLoc(N), N0.getValueType());
2906     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2907       // do not return N1, because undef node may exist in N1
2908       return DAG.getConstant(
2909           APInt::getNullValue(
2910               N1.getValueType().getScalarType().getSizeInBits()),
2911           SDLoc(N), N1.getValueType());
2912
2913     // fold (and x, -1) -> x, vector edition
2914     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2915       return N1;
2916     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2917       return N0;
2918   }
2919
2920   // fold (and c1, c2) -> c1&c2
2921   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2922   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2923   if (N0C && N1C && !N1C->isOpaque())
2924     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2925   // canonicalize constant to RHS
2926   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2927      !isConstantIntBuildVectorOrConstantInt(N1))
2928     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2929   // fold (and x, -1) -> x
2930   if (isAllOnesConstant(N1))
2931     return N0;
2932   // if (and x, c) is known to be zero, return 0
2933   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2934   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2935                                    APInt::getAllOnesValue(BitWidth)))
2936     return DAG.getConstant(0, SDLoc(N), VT);
2937   // reassociate and
2938   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2939     return RAND;
2940   // fold (and (or x, C), D) -> D if (C & D) == D
2941   if (N1C && N0.getOpcode() == ISD::OR)
2942     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2943       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2944         return N1;
2945   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2946   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2947     SDValue N0Op0 = N0.getOperand(0);
2948     APInt Mask = ~N1C->getAPIntValue();
2949     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2950     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2951       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2952                                  N0.getValueType(), N0Op0);
2953
2954       // Replace uses of the AND with uses of the Zero extend node.
2955       CombineTo(N, Zext);
2956
2957       // We actually want to replace all uses of the any_extend with the
2958       // zero_extend, to avoid duplicating things.  This will later cause this
2959       // AND to be folded.
2960       CombineTo(N0.getNode(), Zext);
2961       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2962     }
2963   }
2964   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2965   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2966   // already be zero by virtue of the width of the base type of the load.
2967   //
2968   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2969   // more cases.
2970   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2971        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2972       N0.getOpcode() == ISD::LOAD) {
2973     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2974                                          N0 : N0.getOperand(0) );
2975
2976     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2977     // This can be a pure constant or a vector splat, in which case we treat the
2978     // vector as a scalar and use the splat value.
2979     APInt Constant = APInt::getNullValue(1);
2980     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2981       Constant = C->getAPIntValue();
2982     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2983       APInt SplatValue, SplatUndef;
2984       unsigned SplatBitSize;
2985       bool HasAnyUndefs;
2986       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2987                                              SplatBitSize, HasAnyUndefs);
2988       if (IsSplat) {
2989         // Undef bits can contribute to a possible optimisation if set, so
2990         // set them.
2991         SplatValue |= SplatUndef;
2992
2993         // The splat value may be something like "0x00FFFFFF", which means 0 for
2994         // the first vector value and FF for the rest, repeating. We need a mask
2995         // that will apply equally to all members of the vector, so AND all the
2996         // lanes of the constant together.
2997         EVT VT = Vector->getValueType(0);
2998         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2999
3000         // If the splat value has been compressed to a bitlength lower
3001         // than the size of the vector lane, we need to re-expand it to
3002         // the lane size.
3003         if (BitWidth > SplatBitSize)
3004           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3005                SplatBitSize < BitWidth;
3006                SplatBitSize = SplatBitSize * 2)
3007             SplatValue |= SplatValue.shl(SplatBitSize);
3008
3009         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3010         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3011         if (SplatBitSize % BitWidth == 0) {
3012           Constant = APInt::getAllOnesValue(BitWidth);
3013           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3014             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3015         }
3016       }
3017     }
3018
3019     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3020     // actually legal and isn't going to get expanded, else this is a false
3021     // optimisation.
3022     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3023                                                     Load->getValueType(0),
3024                                                     Load->getMemoryVT());
3025
3026     // Resize the constant to the same size as the original memory access before
3027     // extension. If it is still the AllOnesValue then this AND is completely
3028     // unneeded.
3029     Constant =
3030       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3031
3032     bool B;
3033     switch (Load->getExtensionType()) {
3034     default: B = false; break;
3035     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3036     case ISD::ZEXTLOAD:
3037     case ISD::NON_EXTLOAD: B = true; break;
3038     }
3039
3040     if (B && Constant.isAllOnesValue()) {
3041       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3042       // preserve semantics once we get rid of the AND.
3043       SDValue NewLoad(Load, 0);
3044       if (Load->getExtensionType() == ISD::EXTLOAD) {
3045         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3046                               Load->getValueType(0), SDLoc(Load),
3047                               Load->getChain(), Load->getBasePtr(),
3048                               Load->getOffset(), Load->getMemoryVT(),
3049                               Load->getMemOperand());
3050         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3051         if (Load->getNumValues() == 3) {
3052           // PRE/POST_INC loads have 3 values.
3053           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3054                            NewLoad.getValue(2) };
3055           CombineTo(Load, To, 3, true);
3056         } else {
3057           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3058         }
3059       }
3060
3061       // Fold the AND away, taking care not to fold to the old load node if we
3062       // replaced it.
3063       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3064
3065       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3066     }
3067   }
3068
3069   // fold (and (load x), 255) -> (zextload x, i8)
3070   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3071   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3072   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3073               (N0.getOpcode() == ISD::ANY_EXTEND &&
3074                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3075     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3076     LoadSDNode *LN0 = HasAnyExt
3077       ? cast<LoadSDNode>(N0.getOperand(0))
3078       : cast<LoadSDNode>(N0);
3079     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3080         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3081       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3082       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3083         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3084         EVT LoadedVT = LN0->getMemoryVT();
3085         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3086
3087         if (ExtVT == LoadedVT &&
3088             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3089                                                     ExtVT))) {
3090
3091           SDValue NewLoad =
3092             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3093                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3094                            LN0->getMemOperand());
3095           AddToWorklist(N);
3096           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3097           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3098         }
3099
3100         // Do not change the width of a volatile load.
3101         // Do not generate loads of non-round integer types since these can
3102         // be expensive (and would be wrong if the type is not byte sized).
3103         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3104             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3105                                                     ExtVT))) {
3106           EVT PtrType = LN0->getOperand(1).getValueType();
3107
3108           unsigned Alignment = LN0->getAlignment();
3109           SDValue NewPtr = LN0->getBasePtr();
3110
3111           // For big endian targets, we need to add an offset to the pointer
3112           // to load the correct bytes.  For little endian systems, we merely
3113           // need to read fewer bytes from the same pointer.
3114           if (TLI.isBigEndian()) {
3115             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3116             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3117             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3118             SDLoc DL(LN0);
3119             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3120                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3121             Alignment = MinAlign(Alignment, PtrOff);
3122           }
3123
3124           AddToWorklist(NewPtr.getNode());
3125
3126           SDValue Load =
3127             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3128                            LN0->getChain(), NewPtr,
3129                            LN0->getPointerInfo(),
3130                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3131                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3132           AddToWorklist(N);
3133           CombineTo(LN0, Load, Load.getValue(1));
3134           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3135         }
3136       }
3137     }
3138   }
3139
3140   if (SDValue Combined = visitANDLike(N0, N1, N))
3141     return Combined;
3142
3143   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3144   if (N0.getOpcode() == N1.getOpcode()) {
3145     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3146     if (Tmp.getNode()) return Tmp;
3147   }
3148
3149   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3150   // fold (and (sra)) -> (and (srl)) when possible.
3151   if (!VT.isVector() &&
3152       SimplifyDemandedBits(SDValue(N, 0)))
3153     return SDValue(N, 0);
3154
3155   // fold (zext_inreg (extload x)) -> (zextload x)
3156   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3157     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3158     EVT MemVT = LN0->getMemoryVT();
3159     // If we zero all the possible extended bits, then we can turn this into
3160     // a zextload if we are running before legalize or the operation is legal.
3161     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3162     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3163                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3164         ((!LegalOperations && !LN0->isVolatile()) ||
3165          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3166       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3167                                        LN0->getChain(), LN0->getBasePtr(),
3168                                        MemVT, LN0->getMemOperand());
3169       AddToWorklist(N);
3170       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3171       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3172     }
3173   }
3174   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3175   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3176       N0.hasOneUse()) {
3177     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3178     EVT MemVT = LN0->getMemoryVT();
3179     // If we zero all the possible extended bits, then we can turn this into
3180     // a zextload if we are running before legalize or the operation is legal.
3181     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3182     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3183                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3184         ((!LegalOperations && !LN0->isVolatile()) ||
3185          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3186       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3187                                        LN0->getChain(), LN0->getBasePtr(),
3188                                        MemVT, LN0->getMemOperand());
3189       AddToWorklist(N);
3190       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3191       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3192     }
3193   }
3194   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3195   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3196     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3197                                        N0.getOperand(1), false);
3198     if (BSwap.getNode())
3199       return BSwap;
3200   }
3201
3202   return SDValue();
3203 }
3204
3205 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3206 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3207                                         bool DemandHighBits) {
3208   if (!LegalOperations)
3209     return SDValue();
3210
3211   EVT VT = N->getValueType(0);
3212   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3213     return SDValue();
3214   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3215     return SDValue();
3216
3217   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3218   bool LookPassAnd0 = false;
3219   bool LookPassAnd1 = false;
3220   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3221       std::swap(N0, N1);
3222   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3223       std::swap(N0, N1);
3224   if (N0.getOpcode() == ISD::AND) {
3225     if (!N0.getNode()->hasOneUse())
3226       return SDValue();
3227     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3228     if (!N01C || N01C->getZExtValue() != 0xFF00)
3229       return SDValue();
3230     N0 = N0.getOperand(0);
3231     LookPassAnd0 = true;
3232   }
3233
3234   if (N1.getOpcode() == ISD::AND) {
3235     if (!N1.getNode()->hasOneUse())
3236       return SDValue();
3237     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3238     if (!N11C || N11C->getZExtValue() != 0xFF)
3239       return SDValue();
3240     N1 = N1.getOperand(0);
3241     LookPassAnd1 = true;
3242   }
3243
3244   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3245     std::swap(N0, N1);
3246   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3247     return SDValue();
3248   if (!N0.getNode()->hasOneUse() ||
3249       !N1.getNode()->hasOneUse())
3250     return SDValue();
3251
3252   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3253   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3254   if (!N01C || !N11C)
3255     return SDValue();
3256   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3257     return SDValue();
3258
3259   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3260   SDValue N00 = N0->getOperand(0);
3261   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3262     if (!N00.getNode()->hasOneUse())
3263       return SDValue();
3264     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3265     if (!N001C || N001C->getZExtValue() != 0xFF)
3266       return SDValue();
3267     N00 = N00.getOperand(0);
3268     LookPassAnd0 = true;
3269   }
3270
3271   SDValue N10 = N1->getOperand(0);
3272   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3273     if (!N10.getNode()->hasOneUse())
3274       return SDValue();
3275     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3276     if (!N101C || N101C->getZExtValue() != 0xFF00)
3277       return SDValue();
3278     N10 = N10.getOperand(0);
3279     LookPassAnd1 = true;
3280   }
3281
3282   if (N00 != N10)
3283     return SDValue();
3284
3285   // Make sure everything beyond the low halfword gets set to zero since the SRL
3286   // 16 will clear the top bits.
3287   unsigned OpSizeInBits = VT.getSizeInBits();
3288   if (DemandHighBits && OpSizeInBits > 16) {
3289     // If the left-shift isn't masked out then the only way this is a bswap is
3290     // if all bits beyond the low 8 are 0. In that case the entire pattern
3291     // reduces to a left shift anyway: leave it for other parts of the combiner.
3292     if (!LookPassAnd0)
3293       return SDValue();
3294
3295     // However, if the right shift isn't masked out then it might be because
3296     // it's not needed. See if we can spot that too.
3297     if (!LookPassAnd1 &&
3298         !DAG.MaskedValueIsZero(
3299             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3300       return SDValue();
3301   }
3302
3303   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3304   if (OpSizeInBits > 16) {
3305     SDLoc DL(N);
3306     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3307                       DAG.getConstant(OpSizeInBits - 16, DL,
3308                                       getShiftAmountTy(VT)));
3309   }
3310   return Res;
3311 }
3312
3313 /// Return true if the specified node is an element that makes up a 32-bit
3314 /// packed halfword byteswap.
3315 /// ((x & 0x000000ff) << 8) |
3316 /// ((x & 0x0000ff00) >> 8) |
3317 /// ((x & 0x00ff0000) << 8) |
3318 /// ((x & 0xff000000) >> 8)
3319 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3320   if (!N.getNode()->hasOneUse())
3321     return false;
3322
3323   unsigned Opc = N.getOpcode();
3324   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3325     return false;
3326
3327   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3328   if (!N1C)
3329     return false;
3330
3331   unsigned Num;
3332   switch (N1C->getZExtValue()) {
3333   default:
3334     return false;
3335   case 0xFF:       Num = 0; break;
3336   case 0xFF00:     Num = 1; break;
3337   case 0xFF0000:   Num = 2; break;
3338   case 0xFF000000: Num = 3; break;
3339   }
3340
3341   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3342   SDValue N0 = N.getOperand(0);
3343   if (Opc == ISD::AND) {
3344     if (Num == 0 || Num == 2) {
3345       // (x >> 8) & 0xff
3346       // (x >> 8) & 0xff0000
3347       if (N0.getOpcode() != ISD::SRL)
3348         return false;
3349       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3350       if (!C || C->getZExtValue() != 8)
3351         return false;
3352     } else {
3353       // (x << 8) & 0xff00
3354       // (x << 8) & 0xff000000
3355       if (N0.getOpcode() != ISD::SHL)
3356         return false;
3357       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3358       if (!C || C->getZExtValue() != 8)
3359         return false;
3360     }
3361   } else if (Opc == ISD::SHL) {
3362     // (x & 0xff) << 8
3363     // (x & 0xff0000) << 8
3364     if (Num != 0 && Num != 2)
3365       return false;
3366     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3367     if (!C || C->getZExtValue() != 8)
3368       return false;
3369   } else { // Opc == ISD::SRL
3370     // (x & 0xff00) >> 8
3371     // (x & 0xff000000) >> 8
3372     if (Num != 1 && Num != 3)
3373       return false;
3374     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3375     if (!C || C->getZExtValue() != 8)
3376       return false;
3377   }
3378
3379   if (Parts[Num])
3380     return false;
3381
3382   Parts[Num] = N0.getOperand(0).getNode();
3383   return true;
3384 }
3385
3386 /// Match a 32-bit packed halfword bswap. That is
3387 /// ((x & 0x000000ff) << 8) |
3388 /// ((x & 0x0000ff00) >> 8) |
3389 /// ((x & 0x00ff0000) << 8) |
3390 /// ((x & 0xff000000) >> 8)
3391 /// => (rotl (bswap x), 16)
3392 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3393   if (!LegalOperations)
3394     return SDValue();
3395
3396   EVT VT = N->getValueType(0);
3397   if (VT != MVT::i32)
3398     return SDValue();
3399   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3400     return SDValue();
3401
3402   // Look for either
3403   // (or (or (and), (and)), (or (and), (and)))
3404   // (or (or (or (and), (and)), (and)), (and))
3405   if (N0.getOpcode() != ISD::OR)
3406     return SDValue();
3407   SDValue N00 = N0.getOperand(0);
3408   SDValue N01 = N0.getOperand(1);
3409   SDNode *Parts[4] = {};
3410
3411   if (N1.getOpcode() == ISD::OR &&
3412       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3413     // (or (or (and), (and)), (or (and), (and)))
3414     SDValue N000 = N00.getOperand(0);
3415     if (!isBSwapHWordElement(N000, Parts))
3416       return SDValue();
3417
3418     SDValue N001 = N00.getOperand(1);
3419     if (!isBSwapHWordElement(N001, Parts))
3420       return SDValue();
3421     SDValue N010 = N01.getOperand(0);
3422     if (!isBSwapHWordElement(N010, Parts))
3423       return SDValue();
3424     SDValue N011 = N01.getOperand(1);
3425     if (!isBSwapHWordElement(N011, Parts))
3426       return SDValue();
3427   } else {
3428     // (or (or (or (and), (and)), (and)), (and))
3429     if (!isBSwapHWordElement(N1, Parts))
3430       return SDValue();
3431     if (!isBSwapHWordElement(N01, Parts))
3432       return SDValue();
3433     if (N00.getOpcode() != ISD::OR)
3434       return SDValue();
3435     SDValue N000 = N00.getOperand(0);
3436     if (!isBSwapHWordElement(N000, Parts))
3437       return SDValue();
3438     SDValue N001 = N00.getOperand(1);
3439     if (!isBSwapHWordElement(N001, Parts))
3440       return SDValue();
3441   }
3442
3443   // Make sure the parts are all coming from the same node.
3444   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3445     return SDValue();
3446
3447   SDLoc DL(N);
3448   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3449                               SDValue(Parts[0], 0));
3450
3451   // Result of the bswap should be rotated by 16. If it's not legal, then
3452   // do  (x << 16) | (x >> 16).
3453   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3454   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3455     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3456   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3457     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3458   return DAG.getNode(ISD::OR, DL, VT,
3459                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3460                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3461 }
3462
3463 /// This contains all DAGCombine rules which reduce two values combined by
3464 /// an Or operation to a single value \see visitANDLike().
3465 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3466   EVT VT = N1.getValueType();
3467   // fold (or x, undef) -> -1
3468   if (!LegalOperations &&
3469       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3470     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3471     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3472                            SDLoc(LocReference), VT);
3473   }
3474   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3475   SDValue LL, LR, RL, RR, CC0, CC1;
3476   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3477     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3478     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3479
3480     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3481       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3482       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3483       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3484         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3485                                      LR.getValueType(), LL, RL);
3486         AddToWorklist(ORNode.getNode());
3487         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3488       }
3489       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3490       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3491       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3492         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3493                                       LR.getValueType(), LL, RL);
3494         AddToWorklist(ANDNode.getNode());
3495         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3496       }
3497     }
3498     // canonicalize equivalent to ll == rl
3499     if (LL == RR && LR == RL) {
3500       Op1 = ISD::getSetCCSwappedOperands(Op1);
3501       std::swap(RL, RR);
3502     }
3503     if (LL == RL && LR == RR) {
3504       bool isInteger = LL.getValueType().isInteger();
3505       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3506       if (Result != ISD::SETCC_INVALID &&
3507           (!LegalOperations ||
3508            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3509             TLI.isOperationLegal(ISD::SETCC,
3510               getSetCCResultType(N0.getValueType())))))
3511         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3512                             LL, LR, Result);
3513     }
3514   }
3515
3516   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3517   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3518       // Don't increase # computations.
3519       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3520     // We can only do this xform if we know that bits from X that are set in C2
3521     // but not in C1 are already zero.  Likewise for Y.
3522     if (const ConstantSDNode *N0O1C =
3523         getAsNonOpaqueConstant(N0.getOperand(1))) {
3524       if (const ConstantSDNode *N1O1C =
3525           getAsNonOpaqueConstant(N1.getOperand(1))) {
3526         // We can only do this xform if we know that bits from X that are set in
3527         // C2 but not in C1 are already zero.  Likewise for Y.
3528         const APInt &LHSMask = N0O1C->getAPIntValue();
3529         const APInt &RHSMask = N1O1C->getAPIntValue();
3530
3531         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3532             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3533           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3534                                   N0.getOperand(0), N1.getOperand(0));
3535           SDLoc DL(LocReference);
3536           return DAG.getNode(ISD::AND, DL, VT, X,
3537                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3538         }
3539       }
3540     }
3541   }
3542
3543   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3544   if (N0.getOpcode() == ISD::AND &&
3545       N1.getOpcode() == ISD::AND &&
3546       N0.getOperand(0) == N1.getOperand(0) &&
3547       // Don't increase # computations.
3548       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3549     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3550                             N0.getOperand(1), N1.getOperand(1));
3551     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3552   }
3553
3554   return SDValue();
3555 }
3556
3557 SDValue DAGCombiner::visitOR(SDNode *N) {
3558   SDValue N0 = N->getOperand(0);
3559   SDValue N1 = N->getOperand(1);
3560   EVT VT = N1.getValueType();
3561
3562   // fold vector ops
3563   if (VT.isVector()) {
3564     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3565       return FoldedVOp;
3566
3567     // fold (or x, 0) -> x, vector edition
3568     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3569       return N1;
3570     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3571       return N0;
3572
3573     // fold (or x, -1) -> -1, vector edition
3574     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3575       // do not return N0, because undef node may exist in N0
3576       return DAG.getConstant(
3577           APInt::getAllOnesValue(
3578               N0.getValueType().getScalarType().getSizeInBits()),
3579           SDLoc(N), N0.getValueType());
3580     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3581       // do not return N1, because undef node may exist in N1
3582       return DAG.getConstant(
3583           APInt::getAllOnesValue(
3584               N1.getValueType().getScalarType().getSizeInBits()),
3585           SDLoc(N), N1.getValueType());
3586
3587     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3588     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3589     // Do this only if the resulting shuffle is legal.
3590     if (isa<ShuffleVectorSDNode>(N0) &&
3591         isa<ShuffleVectorSDNode>(N1) &&
3592         // Avoid folding a node with illegal type.
3593         TLI.isTypeLegal(VT) &&
3594         N0->getOperand(1) == N1->getOperand(1) &&
3595         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3596       bool CanFold = true;
3597       unsigned NumElts = VT.getVectorNumElements();
3598       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3599       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3600       // We construct two shuffle masks:
3601       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3602       // and N1 as the second operand.
3603       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3604       // and N0 as the second operand.
3605       // We do this because OR is commutable and therefore there might be
3606       // two ways to fold this node into a shuffle.
3607       SmallVector<int,4> Mask1;
3608       SmallVector<int,4> Mask2;
3609
3610       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3611         int M0 = SV0->getMaskElt(i);
3612         int M1 = SV1->getMaskElt(i);
3613
3614         // Both shuffle indexes are undef. Propagate Undef.
3615         if (M0 < 0 && M1 < 0) {
3616           Mask1.push_back(M0);
3617           Mask2.push_back(M0);
3618           continue;
3619         }
3620
3621         if (M0 < 0 || M1 < 0 ||
3622             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3623             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3624           CanFold = false;
3625           break;
3626         }
3627
3628         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3629         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3630       }
3631
3632       if (CanFold) {
3633         // Fold this sequence only if the resulting shuffle is 'legal'.
3634         if (TLI.isShuffleMaskLegal(Mask1, VT))
3635           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3636                                       N1->getOperand(0), &Mask1[0]);
3637         if (TLI.isShuffleMaskLegal(Mask2, VT))
3638           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3639                                       N0->getOperand(0), &Mask2[0]);
3640       }
3641     }
3642   }
3643
3644   // fold (or c1, c2) -> c1|c2
3645   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3646   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3647   if (N0C && N1C && !N1C->isOpaque())
3648     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3649   // canonicalize constant to RHS
3650   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3651      !isConstantIntBuildVectorOrConstantInt(N1))
3652     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3653   // fold (or x, 0) -> x
3654   if (isNullConstant(N1))
3655     return N0;
3656   // fold (or x, -1) -> -1
3657   if (isAllOnesConstant(N1))
3658     return N1;
3659   // fold (or x, c) -> c iff (x & ~c) == 0
3660   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3661     return N1;
3662
3663   if (SDValue Combined = visitORLike(N0, N1, N))
3664     return Combined;
3665
3666   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3667   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3668   if (BSwap.getNode())
3669     return BSwap;
3670   BSwap = MatchBSwapHWordLow(N, N0, N1);
3671   if (BSwap.getNode())
3672     return BSwap;
3673
3674   // reassociate or
3675   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3676     return ROR;
3677   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3678   // iff (c1 & c2) == 0.
3679   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3680              isa<ConstantSDNode>(N0.getOperand(1))) {
3681     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3682     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3683       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3684                                                    N1C, C1))
3685         return DAG.getNode(
3686             ISD::AND, SDLoc(N), VT,
3687             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3688       return SDValue();
3689     }
3690   }
3691   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3692   if (N0.getOpcode() == N1.getOpcode()) {
3693     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3694     if (Tmp.getNode()) return Tmp;
3695   }
3696
3697   // See if this is some rotate idiom.
3698   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3699     return SDValue(Rot, 0);
3700
3701   // Simplify the operands using demanded-bits information.
3702   if (!VT.isVector() &&
3703       SimplifyDemandedBits(SDValue(N, 0)))
3704     return SDValue(N, 0);
3705
3706   return SDValue();
3707 }
3708
3709 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3710 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3711   if (Op.getOpcode() == ISD::AND) {
3712     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3713       Mask = Op.getOperand(1);
3714       Op = Op.getOperand(0);
3715     } else {
3716       return false;
3717     }
3718   }
3719
3720   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3721     Shift = Op;
3722     return true;
3723   }
3724
3725   return false;
3726 }
3727
3728 // Return true if we can prove that, whenever Neg and Pos are both in the
3729 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3730 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3731 //
3732 //     (or (shift1 X, Neg), (shift2 X, Pos))
3733 //
3734 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3735 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3736 // to consider shift amounts with defined behavior.
3737 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3738   // If OpSize is a power of 2 then:
3739   //
3740   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3741   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3742   //
3743   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3744   // for the stronger condition:
3745   //
3746   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3747   //
3748   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3749   // we can just replace Neg with Neg' for the rest of the function.
3750   //
3751   // In other cases we check for the even stronger condition:
3752   //
3753   //     Neg == OpSize - Pos                                    [B]
3754   //
3755   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3756   // behavior if Pos == 0 (and consequently Neg == OpSize).
3757   //
3758   // We could actually use [A] whenever OpSize is a power of 2, but the
3759   // only extra cases that it would match are those uninteresting ones
3760   // where Neg and Pos are never in range at the same time.  E.g. for
3761   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3762   // as well as (sub 32, Pos), but:
3763   //
3764   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3765   //
3766   // always invokes undefined behavior for 32-bit X.
3767   //
3768   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3769   unsigned MaskLoBits = 0;
3770   if (Neg.getOpcode() == ISD::AND &&
3771       isPowerOf2_64(OpSize) &&
3772       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3773       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3774     Neg = Neg.getOperand(0);
3775     MaskLoBits = Log2_64(OpSize);
3776   }
3777
3778   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3779   if (Neg.getOpcode() != ISD::SUB)
3780     return 0;
3781   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3782   if (!NegC)
3783     return 0;
3784   SDValue NegOp1 = Neg.getOperand(1);
3785
3786   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3787   // Pos'.  The truncation is redundant for the purpose of the equality.
3788   if (MaskLoBits &&
3789       Pos.getOpcode() == ISD::AND &&
3790       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3791       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3792     Pos = Pos.getOperand(0);
3793
3794   // The condition we need is now:
3795   //
3796   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3797   //
3798   // If NegOp1 == Pos then we need:
3799   //
3800   //              OpSize & Mask == NegC & Mask
3801   //
3802   // (because "x & Mask" is a truncation and distributes through subtraction).
3803   APInt Width;
3804   if (Pos == NegOp1)
3805     Width = NegC->getAPIntValue();
3806   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3807   // Then the condition we want to prove becomes:
3808   //
3809   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3810   //
3811   // which, again because "x & Mask" is a truncation, becomes:
3812   //
3813   //                NegC & Mask == (OpSize - PosC) & Mask
3814   //              OpSize & Mask == (NegC + PosC) & Mask
3815   else if (Pos.getOpcode() == ISD::ADD &&
3816            Pos.getOperand(0) == NegOp1 &&
3817            Pos.getOperand(1).getOpcode() == ISD::Constant)
3818     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3819              NegC->getAPIntValue());
3820   else
3821     return false;
3822
3823   // Now we just need to check that OpSize & Mask == Width & Mask.
3824   if (MaskLoBits)
3825     // Opsize & Mask is 0 since Mask is Opsize - 1.
3826     return Width.getLoBits(MaskLoBits) == 0;
3827   return Width == OpSize;
3828 }
3829
3830 // A subroutine of MatchRotate used once we have found an OR of two opposite
3831 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3832 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3833 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3834 // Neg with outer conversions stripped away.
3835 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3836                                        SDValue Neg, SDValue InnerPos,
3837                                        SDValue InnerNeg, unsigned PosOpcode,
3838                                        unsigned NegOpcode, SDLoc DL) {
3839   // fold (or (shl x, (*ext y)),
3840   //          (srl x, (*ext (sub 32, y)))) ->
3841   //   (rotl x, y) or (rotr x, (sub 32, y))
3842   //
3843   // fold (or (shl x, (*ext (sub 32, y))),
3844   //          (srl x, (*ext y))) ->
3845   //   (rotr x, y) or (rotl x, (sub 32, y))
3846   EVT VT = Shifted.getValueType();
3847   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3848     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3849     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3850                        HasPos ? Pos : Neg).getNode();
3851   }
3852
3853   return nullptr;
3854 }
3855
3856 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3857 // idioms for rotate, and if the target supports rotation instructions, generate
3858 // a rot[lr].
3859 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3860   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3861   EVT VT = LHS.getValueType();
3862   if (!TLI.isTypeLegal(VT)) return nullptr;
3863
3864   // The target must have at least one rotate flavor.
3865   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3866   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3867   if (!HasROTL && !HasROTR) return nullptr;
3868
3869   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3870   SDValue LHSShift;   // The shift.
3871   SDValue LHSMask;    // AND value if any.
3872   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3873     return nullptr; // Not part of a rotate.
3874
3875   SDValue RHSShift;   // The shift.
3876   SDValue RHSMask;    // AND value if any.
3877   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3878     return nullptr; // Not part of a rotate.
3879
3880   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3881     return nullptr;   // Not shifting the same value.
3882
3883   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3884     return nullptr;   // Shifts must disagree.
3885
3886   // Canonicalize shl to left side in a shl/srl pair.
3887   if (RHSShift.getOpcode() == ISD::SHL) {
3888     std::swap(LHS, RHS);
3889     std::swap(LHSShift, RHSShift);
3890     std::swap(LHSMask , RHSMask );
3891   }
3892
3893   unsigned OpSizeInBits = VT.getSizeInBits();
3894   SDValue LHSShiftArg = LHSShift.getOperand(0);
3895   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3896   SDValue RHSShiftArg = RHSShift.getOperand(0);
3897   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3898
3899   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3900   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3901   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3902       RHSShiftAmt.getOpcode() == ISD::Constant) {
3903     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3904     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3905     if ((LShVal + RShVal) != OpSizeInBits)
3906       return nullptr;
3907
3908     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3909                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3910
3911     // If there is an AND of either shifted operand, apply it to the result.
3912     if (LHSMask.getNode() || RHSMask.getNode()) {
3913       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3914
3915       if (LHSMask.getNode()) {
3916         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3917         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3918       }
3919       if (RHSMask.getNode()) {
3920         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3921         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3922       }
3923
3924       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3925     }
3926
3927     return Rot.getNode();
3928   }
3929
3930   // If there is a mask here, and we have a variable shift, we can't be sure
3931   // that we're masking out the right stuff.
3932   if (LHSMask.getNode() || RHSMask.getNode())
3933     return nullptr;
3934
3935   // If the shift amount is sign/zext/any-extended just peel it off.
3936   SDValue LExtOp0 = LHSShiftAmt;
3937   SDValue RExtOp0 = RHSShiftAmt;
3938   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3939        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3940        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3941        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3942       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3943        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3944        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3945        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3946     LExtOp0 = LHSShiftAmt.getOperand(0);
3947     RExtOp0 = RHSShiftAmt.getOperand(0);
3948   }
3949
3950   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3951                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3952   if (TryL)
3953     return TryL;
3954
3955   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3956                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3957   if (TryR)
3958     return TryR;
3959
3960   return nullptr;
3961 }
3962
3963 SDValue DAGCombiner::visitXOR(SDNode *N) {
3964   SDValue N0 = N->getOperand(0);
3965   SDValue N1 = N->getOperand(1);
3966   EVT VT = N0.getValueType();
3967
3968   // fold vector ops
3969   if (VT.isVector()) {
3970     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3971       return FoldedVOp;
3972
3973     // fold (xor x, 0) -> x, vector edition
3974     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3975       return N1;
3976     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3977       return N0;
3978   }
3979
3980   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3981   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3982     return DAG.getConstant(0, SDLoc(N), VT);
3983   // fold (xor x, undef) -> undef
3984   if (N0.getOpcode() == ISD::UNDEF)
3985     return N0;
3986   if (N1.getOpcode() == ISD::UNDEF)
3987     return N1;
3988   // fold (xor c1, c2) -> c1^c2
3989   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3990   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3991   if (N0C && N1C)
3992     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3993   // canonicalize constant to RHS
3994   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3995      !isConstantIntBuildVectorOrConstantInt(N1))
3996     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3997   // fold (xor x, 0) -> x
3998   if (isNullConstant(N1))
3999     return N0;
4000   // reassociate xor
4001   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4002     return RXOR;
4003
4004   // fold !(x cc y) -> (x !cc y)
4005   SDValue LHS, RHS, CC;
4006   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4007     bool isInt = LHS.getValueType().isInteger();
4008     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4009                                                isInt);
4010
4011     if (!LegalOperations ||
4012         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4013       switch (N0.getOpcode()) {
4014       default:
4015         llvm_unreachable("Unhandled SetCC Equivalent!");
4016       case ISD::SETCC:
4017         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4018       case ISD::SELECT_CC:
4019         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4020                                N0.getOperand(3), NotCC);
4021       }
4022     }
4023   }
4024
4025   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4026   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4027       N0.getNode()->hasOneUse() &&
4028       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4029     SDValue V = N0.getOperand(0);
4030     SDLoc DL(N0);
4031     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4032                     DAG.getConstant(1, DL, V.getValueType()));
4033     AddToWorklist(V.getNode());
4034     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4035   }
4036
4037   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4038   if (isOneConstant(N1) && VT == MVT::i1 &&
4039       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4040     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4041     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4042       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4043       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4044       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4045       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4046       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4047     }
4048   }
4049   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4050   if (isAllOnesConstant(N1) &&
4051       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4052     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4053     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4054       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4055       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4056       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4057       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4058       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4059     }
4060   }
4061   // fold (xor (and x, y), y) -> (and (not x), y)
4062   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4063       N0->getOperand(1) == N1) {
4064     SDValue X = N0->getOperand(0);
4065     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4066     AddToWorklist(NotX.getNode());
4067     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4068   }
4069   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4070   if (N1C && N0.getOpcode() == ISD::XOR) {
4071     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4072       SDLoc DL(N);
4073       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4074                          DAG.getConstant(N1C->getAPIntValue() ^
4075                                          N00C->getAPIntValue(), DL, VT));
4076     }
4077     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4078       SDLoc DL(N);
4079       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4080                          DAG.getConstant(N1C->getAPIntValue() ^
4081                                          N01C->getAPIntValue(), DL, VT));
4082     }
4083   }
4084   // fold (xor x, x) -> 0
4085   if (N0 == N1)
4086     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4087
4088   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4089   // Here is a concrete example of this equivalence:
4090   // i16   x ==  14
4091   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4092   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4093   //
4094   // =>
4095   //
4096   // i16     ~1      == 0b1111111111111110
4097   // i16 rol(~1, 14) == 0b1011111111111111
4098   //
4099   // Some additional tips to help conceptualize this transform:
4100   // - Try to see the operation as placing a single zero in a value of all ones.
4101   // - There exists no value for x which would allow the result to contain zero.
4102   // - Values of x larger than the bitwidth are undefined and do not require a
4103   //   consistent result.
4104   // - Pushing the zero left requires shifting one bits in from the right.
4105   // A rotate left of ~1 is a nice way of achieving the desired result.
4106   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4107       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4108     SDLoc DL(N);
4109     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4110                        N0.getOperand(1));
4111   }
4112
4113   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4114   if (N0.getOpcode() == N1.getOpcode()) {
4115     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4116     if (Tmp.getNode()) return Tmp;
4117   }
4118
4119   // Simplify the expression using non-local knowledge.
4120   if (!VT.isVector() &&
4121       SimplifyDemandedBits(SDValue(N, 0)))
4122     return SDValue(N, 0);
4123
4124   return SDValue();
4125 }
4126
4127 /// Handle transforms common to the three shifts, when the shift amount is a
4128 /// constant.
4129 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4130   SDNode *LHS = N->getOperand(0).getNode();
4131   if (!LHS->hasOneUse()) return SDValue();
4132
4133   // We want to pull some binops through shifts, so that we have (and (shift))
4134   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4135   // thing happens with address calculations, so it's important to canonicalize
4136   // it.
4137   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4138
4139   switch (LHS->getOpcode()) {
4140   default: return SDValue();
4141   case ISD::OR:
4142   case ISD::XOR:
4143     HighBitSet = false; // We can only transform sra if the high bit is clear.
4144     break;
4145   case ISD::AND:
4146     HighBitSet = true;  // We can only transform sra if the high bit is set.
4147     break;
4148   case ISD::ADD:
4149     if (N->getOpcode() != ISD::SHL)
4150       return SDValue(); // only shl(add) not sr[al](add).
4151     HighBitSet = false; // We can only transform sra if the high bit is clear.
4152     break;
4153   }
4154
4155   // We require the RHS of the binop to be a constant and not opaque as well.
4156   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4157   if (!BinOpCst) return SDValue();
4158
4159   // FIXME: disable this unless the input to the binop is a shift by a constant.
4160   // If it is not a shift, it pessimizes some common cases like:
4161   //
4162   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4163   //    int bar(int *X, int i) { return X[i & 255]; }
4164   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4165   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4166        BinOpLHSVal->getOpcode() != ISD::SRA &&
4167        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4168       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4169     return SDValue();
4170
4171   EVT VT = N->getValueType(0);
4172
4173   // If this is a signed shift right, and the high bit is modified by the
4174   // logical operation, do not perform the transformation. The highBitSet
4175   // boolean indicates the value of the high bit of the constant which would
4176   // cause it to be modified for this operation.
4177   if (N->getOpcode() == ISD::SRA) {
4178     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4179     if (BinOpRHSSignSet != HighBitSet)
4180       return SDValue();
4181   }
4182
4183   if (!TLI.isDesirableToCommuteWithShift(LHS))
4184     return SDValue();
4185
4186   // Fold the constants, shifting the binop RHS by the shift amount.
4187   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4188                                N->getValueType(0),
4189                                LHS->getOperand(1), N->getOperand(1));
4190   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4191
4192   // Create the new shift.
4193   SDValue NewShift = DAG.getNode(N->getOpcode(),
4194                                  SDLoc(LHS->getOperand(0)),
4195                                  VT, LHS->getOperand(0), N->getOperand(1));
4196
4197   // Create the new binop.
4198   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4199 }
4200
4201 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4202   assert(N->getOpcode() == ISD::TRUNCATE);
4203   assert(N->getOperand(0).getOpcode() == ISD::AND);
4204
4205   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4206   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4207     SDValue N01 = N->getOperand(0).getOperand(1);
4208
4209     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4210       if (!N01C->isOpaque()) {
4211         EVT TruncVT = N->getValueType(0);
4212         SDValue N00 = N->getOperand(0).getOperand(0);
4213         APInt TruncC = N01C->getAPIntValue();
4214         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4215         SDLoc DL(N);
4216
4217         return DAG.getNode(ISD::AND, DL, TruncVT,
4218                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4219                            DAG.getConstant(TruncC, DL, TruncVT));
4220       }
4221     }
4222   }
4223
4224   return SDValue();
4225 }
4226
4227 SDValue DAGCombiner::visitRotate(SDNode *N) {
4228   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4229   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4230       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4231     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4232     if (NewOp1.getNode())
4233       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4234                          N->getOperand(0), NewOp1);
4235   }
4236   return SDValue();
4237 }
4238
4239 SDValue DAGCombiner::visitSHL(SDNode *N) {
4240   SDValue N0 = N->getOperand(0);
4241   SDValue N1 = N->getOperand(1);
4242   EVT VT = N0.getValueType();
4243   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4244
4245   // fold vector ops
4246   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4247   if (VT.isVector()) {
4248     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4249       return FoldedVOp;
4250
4251     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4252     // If setcc produces all-one true value then:
4253     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4254     if (N1CV && N1CV->isConstant()) {
4255       if (N0.getOpcode() == ISD::AND) {
4256         SDValue N00 = N0->getOperand(0);
4257         SDValue N01 = N0->getOperand(1);
4258         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4259
4260         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4261             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4262                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4263           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4264                                                      N01CV, N1CV))
4265             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4266         }
4267       } else {
4268         N1C = isConstOrConstSplat(N1);
4269       }
4270     }
4271   }
4272
4273   // fold (shl c1, c2) -> c1<<c2
4274   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4275   if (N0C && N1C && !N1C->isOpaque())
4276     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4277   // fold (shl 0, x) -> 0
4278   if (isNullConstant(N0))
4279     return N0;
4280   // fold (shl x, c >= size(x)) -> undef
4281   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4282     return DAG.getUNDEF(VT);
4283   // fold (shl x, 0) -> x
4284   if (N1C && N1C->isNullValue())
4285     return N0;
4286   // fold (shl undef, x) -> 0
4287   if (N0.getOpcode() == ISD::UNDEF)
4288     return DAG.getConstant(0, SDLoc(N), VT);
4289   // if (shl x, c) is known to be zero, return 0
4290   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4291                             APInt::getAllOnesValue(OpSizeInBits)))
4292     return DAG.getConstant(0, SDLoc(N), VT);
4293   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4294   if (N1.getOpcode() == ISD::TRUNCATE &&
4295       N1.getOperand(0).getOpcode() == ISD::AND) {
4296     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4297     if (NewOp1.getNode())
4298       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4299   }
4300
4301   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4302     return SDValue(N, 0);
4303
4304   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4305   if (N1C && N0.getOpcode() == ISD::SHL) {
4306     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4307       uint64_t c1 = N0C1->getZExtValue();
4308       uint64_t c2 = N1C->getZExtValue();
4309       SDLoc DL(N);
4310       if (c1 + c2 >= OpSizeInBits)
4311         return DAG.getConstant(0, DL, VT);
4312       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4313                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4314     }
4315   }
4316
4317   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4318   // For this to be valid, the second form must not preserve any of the bits
4319   // that are shifted out by the inner shift in the first form.  This means
4320   // the outer shift size must be >= the number of bits added by the ext.
4321   // As a corollary, we don't care what kind of ext it is.
4322   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4323               N0.getOpcode() == ISD::ANY_EXTEND ||
4324               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4325       N0.getOperand(0).getOpcode() == ISD::SHL) {
4326     SDValue N0Op0 = N0.getOperand(0);
4327     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4328       uint64_t c1 = N0Op0C1->getZExtValue();
4329       uint64_t c2 = N1C->getZExtValue();
4330       EVT InnerShiftVT = N0Op0.getValueType();
4331       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4332       if (c2 >= OpSizeInBits - InnerShiftSize) {
4333         SDLoc DL(N0);
4334         if (c1 + c2 >= OpSizeInBits)
4335           return DAG.getConstant(0, DL, VT);
4336         return DAG.getNode(ISD::SHL, DL, VT,
4337                            DAG.getNode(N0.getOpcode(), DL, VT,
4338                                        N0Op0->getOperand(0)),
4339                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4340       }
4341     }
4342   }
4343
4344   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4345   // Only fold this if the inner zext has no other uses to avoid increasing
4346   // the total number of instructions.
4347   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4348       N0.getOperand(0).getOpcode() == ISD::SRL) {
4349     SDValue N0Op0 = N0.getOperand(0);
4350     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4351       uint64_t c1 = N0Op0C1->getZExtValue();
4352       if (c1 < VT.getScalarSizeInBits()) {
4353         uint64_t c2 = N1C->getZExtValue();
4354         if (c1 == c2) {
4355           SDValue NewOp0 = N0.getOperand(0);
4356           EVT CountVT = NewOp0.getOperand(1).getValueType();
4357           SDLoc DL(N);
4358           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4359                                        NewOp0,
4360                                        DAG.getConstant(c2, DL, CountVT));
4361           AddToWorklist(NewSHL.getNode());
4362           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4363         }
4364       }
4365     }
4366   }
4367
4368   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4369   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4370   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4371       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4372     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4373       uint64_t C1 = N0C1->getZExtValue();
4374       uint64_t C2 = N1C->getZExtValue();
4375       SDLoc DL(N);
4376       if (C1 <= C2)
4377         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4378                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4379       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4380                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4381     }
4382   }
4383
4384   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4385   //                               (and (srl x, (sub c1, c2), MASK)
4386   // Only fold this if the inner shift has no other uses -- if it does, folding
4387   // this will increase the total number of instructions.
4388   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4389     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4390       uint64_t c1 = N0C1->getZExtValue();
4391       if (c1 < OpSizeInBits) {
4392         uint64_t c2 = N1C->getZExtValue();
4393         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4394         SDValue Shift;
4395         if (c2 > c1) {
4396           Mask = Mask.shl(c2 - c1);
4397           SDLoc DL(N);
4398           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4399                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4400         } else {
4401           Mask = Mask.lshr(c1 - c2);
4402           SDLoc DL(N);
4403           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4404                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4405         }
4406         SDLoc DL(N0);
4407         return DAG.getNode(ISD::AND, DL, VT, Shift,
4408                            DAG.getConstant(Mask, DL, VT));
4409       }
4410     }
4411   }
4412   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4413   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4414     unsigned BitSize = VT.getScalarSizeInBits();
4415     SDLoc DL(N);
4416     SDValue HiBitsMask =
4417       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4418                                             BitSize - N1C->getZExtValue()),
4419                       DL, VT);
4420     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4421                        HiBitsMask);
4422   }
4423
4424   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4425   // Variant of version done on multiply, except mul by a power of 2 is turned
4426   // into a shift.
4427   APInt Val;
4428   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4429       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4430        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4431     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4432     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4433     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4434   }
4435
4436   if (N1C && !N1C->isOpaque()) {
4437     SDValue NewSHL = visitShiftByConstant(N, N1C);
4438     if (NewSHL.getNode())
4439       return NewSHL;
4440   }
4441
4442   return SDValue();
4443 }
4444
4445 SDValue DAGCombiner::visitSRA(SDNode *N) {
4446   SDValue N0 = N->getOperand(0);
4447   SDValue N1 = N->getOperand(1);
4448   EVT VT = N0.getValueType();
4449   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4450
4451   // fold vector ops
4452   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4453   if (VT.isVector()) {
4454     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4455       return FoldedVOp;
4456
4457     N1C = isConstOrConstSplat(N1);
4458   }
4459
4460   // fold (sra c1, c2) -> (sra c1, c2)
4461   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4462   if (N0C && N1C && !N1C->isOpaque())
4463     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4464   // fold (sra 0, x) -> 0
4465   if (isNullConstant(N0))
4466     return N0;
4467   // fold (sra -1, x) -> -1
4468   if (isAllOnesConstant(N0))
4469     return N0;
4470   // fold (sra x, (setge c, size(x))) -> undef
4471   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4472     return DAG.getUNDEF(VT);
4473   // fold (sra x, 0) -> x
4474   if (N1C && N1C->isNullValue())
4475     return N0;
4476   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4477   // sext_inreg.
4478   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4479     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4480     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4481     if (VT.isVector())
4482       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4483                                ExtVT, VT.getVectorNumElements());
4484     if ((!LegalOperations ||
4485          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4486       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4487                          N0.getOperand(0), DAG.getValueType(ExtVT));
4488   }
4489
4490   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4491   if (N1C && N0.getOpcode() == ISD::SRA) {
4492     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4493       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4494       if (Sum >= OpSizeInBits)
4495         Sum = OpSizeInBits - 1;
4496       SDLoc DL(N);
4497       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4498                          DAG.getConstant(Sum, DL, N1.getValueType()));
4499     }
4500   }
4501
4502   // fold (sra (shl X, m), (sub result_size, n))
4503   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4504   // result_size - n != m.
4505   // If truncate is free for the target sext(shl) is likely to result in better
4506   // code.
4507   if (N0.getOpcode() == ISD::SHL && N1C) {
4508     // Get the two constanst of the shifts, CN0 = m, CN = n.
4509     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4510     if (N01C) {
4511       LLVMContext &Ctx = *DAG.getContext();
4512       // Determine what the truncate's result bitsize and type would be.
4513       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4514
4515       if (VT.isVector())
4516         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4517
4518       // Determine the residual right-shift amount.
4519       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4520
4521       // If the shift is not a no-op (in which case this should be just a sign
4522       // extend already), the truncated to type is legal, sign_extend is legal
4523       // on that type, and the truncate to that type is both legal and free,
4524       // perform the transform.
4525       if ((ShiftAmt > 0) &&
4526           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4527           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4528           TLI.isTruncateFree(VT, TruncVT)) {
4529
4530         SDLoc DL(N);
4531         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4532             getShiftAmountTy(N0.getOperand(0).getValueType()));
4533         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4534                                     N0.getOperand(0), Amt);
4535         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4536                                     Shift);
4537         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4538                            N->getValueType(0), Trunc);
4539       }
4540     }
4541   }
4542
4543   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4544   if (N1.getOpcode() == ISD::TRUNCATE &&
4545       N1.getOperand(0).getOpcode() == ISD::AND) {
4546     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4547     if (NewOp1.getNode())
4548       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4549   }
4550
4551   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4552   //      if c1 is equal to the number of bits the trunc removes
4553   if (N0.getOpcode() == ISD::TRUNCATE &&
4554       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4555        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4556       N0.getOperand(0).hasOneUse() &&
4557       N0.getOperand(0).getOperand(1).hasOneUse() &&
4558       N1C) {
4559     SDValue N0Op0 = N0.getOperand(0);
4560     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4561       unsigned LargeShiftVal = LargeShift->getZExtValue();
4562       EVT LargeVT = N0Op0.getValueType();
4563
4564       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4565         SDLoc DL(N);
4566         SDValue Amt =
4567           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4568                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4569         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4570                                   N0Op0.getOperand(0), Amt);
4571         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4572       }
4573     }
4574   }
4575
4576   // Simplify, based on bits shifted out of the LHS.
4577   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4578     return SDValue(N, 0);
4579
4580
4581   // If the sign bit is known to be zero, switch this to a SRL.
4582   if (DAG.SignBitIsZero(N0))
4583     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4584
4585   if (N1C && !N1C->isOpaque()) {
4586     SDValue NewSRA = visitShiftByConstant(N, N1C);
4587     if (NewSRA.getNode())
4588       return NewSRA;
4589   }
4590
4591   return SDValue();
4592 }
4593
4594 SDValue DAGCombiner::visitSRL(SDNode *N) {
4595   SDValue N0 = N->getOperand(0);
4596   SDValue N1 = N->getOperand(1);
4597   EVT VT = N0.getValueType();
4598   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4599
4600   // fold vector ops
4601   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4602   if (VT.isVector()) {
4603     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4604       return FoldedVOp;
4605
4606     N1C = isConstOrConstSplat(N1);
4607   }
4608
4609   // fold (srl c1, c2) -> c1 >>u c2
4610   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4611   if (N0C && N1C && !N1C->isOpaque())
4612     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4613   // fold (srl 0, x) -> 0
4614   if (isNullConstant(N0))
4615     return N0;
4616   // fold (srl x, c >= size(x)) -> undef
4617   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4618     return DAG.getUNDEF(VT);
4619   // fold (srl x, 0) -> x
4620   if (N1C && N1C->isNullValue())
4621     return N0;
4622   // if (srl x, c) is known to be zero, return 0
4623   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4624                                    APInt::getAllOnesValue(OpSizeInBits)))
4625     return DAG.getConstant(0, SDLoc(N), VT);
4626
4627   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4628   if (N1C && N0.getOpcode() == ISD::SRL) {
4629     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4630       uint64_t c1 = N01C->getZExtValue();
4631       uint64_t c2 = N1C->getZExtValue();
4632       SDLoc DL(N);
4633       if (c1 + c2 >= OpSizeInBits)
4634         return DAG.getConstant(0, DL, VT);
4635       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4636                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4637     }
4638   }
4639
4640   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4641   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4642       N0.getOperand(0).getOpcode() == ISD::SRL &&
4643       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4644     uint64_t c1 =
4645       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4646     uint64_t c2 = N1C->getZExtValue();
4647     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4648     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4649     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4650     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4651     if (c1 + OpSizeInBits == InnerShiftSize) {
4652       SDLoc DL(N0);
4653       if (c1 + c2 >= InnerShiftSize)
4654         return DAG.getConstant(0, DL, VT);
4655       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4656                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4657                                      N0.getOperand(0)->getOperand(0),
4658                                      DAG.getConstant(c1 + c2, DL,
4659                                                      ShiftCountVT)));
4660     }
4661   }
4662
4663   // fold (srl (shl x, c), c) -> (and x, cst2)
4664   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4665     unsigned BitSize = N0.getScalarValueSizeInBits();
4666     if (BitSize <= 64) {
4667       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4668       SDLoc DL(N);
4669       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4670                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4671     }
4672   }
4673
4674   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4675   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4676     // Shifting in all undef bits?
4677     EVT SmallVT = N0.getOperand(0).getValueType();
4678     unsigned BitSize = SmallVT.getScalarSizeInBits();
4679     if (N1C->getZExtValue() >= BitSize)
4680       return DAG.getUNDEF(VT);
4681
4682     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4683       uint64_t ShiftAmt = N1C->getZExtValue();
4684       SDLoc DL0(N0);
4685       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4686                                        N0.getOperand(0),
4687                           DAG.getConstant(ShiftAmt, DL0,
4688                                           getShiftAmountTy(SmallVT)));
4689       AddToWorklist(SmallShift.getNode());
4690       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4691       SDLoc DL(N);
4692       return DAG.getNode(ISD::AND, DL, VT,
4693                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4694                          DAG.getConstant(Mask, DL, VT));
4695     }
4696   }
4697
4698   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4699   // bit, which is unmodified by sra.
4700   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4701     if (N0.getOpcode() == ISD::SRA)
4702       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4703   }
4704
4705   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4706   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4707       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4708     APInt KnownZero, KnownOne;
4709     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4710
4711     // If any of the input bits are KnownOne, then the input couldn't be all
4712     // zeros, thus the result of the srl will always be zero.
4713     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4714
4715     // If all of the bits input the to ctlz node are known to be zero, then
4716     // the result of the ctlz is "32" and the result of the shift is one.
4717     APInt UnknownBits = ~KnownZero;
4718     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4719
4720     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4721     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4722       // Okay, we know that only that the single bit specified by UnknownBits
4723       // could be set on input to the CTLZ node. If this bit is set, the SRL
4724       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4725       // to an SRL/XOR pair, which is likely to simplify more.
4726       unsigned ShAmt = UnknownBits.countTrailingZeros();
4727       SDValue Op = N0.getOperand(0);
4728
4729       if (ShAmt) {
4730         SDLoc DL(N0);
4731         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4732                   DAG.getConstant(ShAmt, DL,
4733                                   getShiftAmountTy(Op.getValueType())));
4734         AddToWorklist(Op.getNode());
4735       }
4736
4737       SDLoc DL(N);
4738       return DAG.getNode(ISD::XOR, DL, VT,
4739                          Op, DAG.getConstant(1, DL, VT));
4740     }
4741   }
4742
4743   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4744   if (N1.getOpcode() == ISD::TRUNCATE &&
4745       N1.getOperand(0).getOpcode() == ISD::AND) {
4746     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4747     if (NewOp1.getNode())
4748       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4749   }
4750
4751   // fold operands of srl based on knowledge that the low bits are not
4752   // demanded.
4753   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4754     return SDValue(N, 0);
4755
4756   if (N1C && !N1C->isOpaque()) {
4757     SDValue NewSRL = visitShiftByConstant(N, N1C);
4758     if (NewSRL.getNode())
4759       return NewSRL;
4760   }
4761
4762   // Attempt to convert a srl of a load into a narrower zero-extending load.
4763   SDValue NarrowLoad = ReduceLoadWidth(N);
4764   if (NarrowLoad.getNode())
4765     return NarrowLoad;
4766
4767   // Here is a common situation. We want to optimize:
4768   //
4769   //   %a = ...
4770   //   %b = and i32 %a, 2
4771   //   %c = srl i32 %b, 1
4772   //   brcond i32 %c ...
4773   //
4774   // into
4775   //
4776   //   %a = ...
4777   //   %b = and %a, 2
4778   //   %c = setcc eq %b, 0
4779   //   brcond %c ...
4780   //
4781   // However when after the source operand of SRL is optimized into AND, the SRL
4782   // itself may not be optimized further. Look for it and add the BRCOND into
4783   // the worklist.
4784   if (N->hasOneUse()) {
4785     SDNode *Use = *N->use_begin();
4786     if (Use->getOpcode() == ISD::BRCOND)
4787       AddToWorklist(Use);
4788     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4789       // Also look pass the truncate.
4790       Use = *Use->use_begin();
4791       if (Use->getOpcode() == ISD::BRCOND)
4792         AddToWorklist(Use);
4793     }
4794   }
4795
4796   return SDValue();
4797 }
4798
4799 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4800   SDValue N0 = N->getOperand(0);
4801   EVT VT = N->getValueType(0);
4802
4803   // fold (bswap c1) -> c2
4804   if (isConstantIntBuildVectorOrConstantInt(N0))
4805     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4806   // fold (bswap (bswap x)) -> x
4807   if (N0.getOpcode() == ISD::BSWAP)
4808     return N0->getOperand(0);
4809   return SDValue();
4810 }
4811
4812 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4813   SDValue N0 = N->getOperand(0);
4814   EVT VT = N->getValueType(0);
4815
4816   // fold (ctlz c1) -> c2
4817   if (isConstantIntBuildVectorOrConstantInt(N0))
4818     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4819   return SDValue();
4820 }
4821
4822 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4823   SDValue N0 = N->getOperand(0);
4824   EVT VT = N->getValueType(0);
4825
4826   // fold (ctlz_zero_undef c1) -> c2
4827   if (isConstantIntBuildVectorOrConstantInt(N0))
4828     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4829   return SDValue();
4830 }
4831
4832 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4833   SDValue N0 = N->getOperand(0);
4834   EVT VT = N->getValueType(0);
4835
4836   // fold (cttz c1) -> c2
4837   if (isConstantIntBuildVectorOrConstantInt(N0))
4838     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4839   return SDValue();
4840 }
4841
4842 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4843   SDValue N0 = N->getOperand(0);
4844   EVT VT = N->getValueType(0);
4845
4846   // fold (cttz_zero_undef c1) -> c2
4847   if (isConstantIntBuildVectorOrConstantInt(N0))
4848     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4849   return SDValue();
4850 }
4851
4852 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4853   SDValue N0 = N->getOperand(0);
4854   EVT VT = N->getValueType(0);
4855
4856   // fold (ctpop c1) -> c2
4857   if (isConstantIntBuildVectorOrConstantInt(N0))
4858     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4859   return SDValue();
4860 }
4861
4862
4863 /// \brief Generate Min/Max node
4864 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4865                                    SDValue True, SDValue False,
4866                                    ISD::CondCode CC, const TargetLowering &TLI,
4867                                    SelectionDAG &DAG) {
4868   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4869     return SDValue();
4870
4871   switch (CC) {
4872   case ISD::SETOLT:
4873   case ISD::SETOLE:
4874   case ISD::SETLT:
4875   case ISD::SETLE:
4876   case ISD::SETULT:
4877   case ISD::SETULE: {
4878     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4879     if (TLI.isOperationLegal(Opcode, VT))
4880       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4881     return SDValue();
4882   }
4883   case ISD::SETOGT:
4884   case ISD::SETOGE:
4885   case ISD::SETGT:
4886   case ISD::SETGE:
4887   case ISD::SETUGT:
4888   case ISD::SETUGE: {
4889     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4890     if (TLI.isOperationLegal(Opcode, VT))
4891       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4892     return SDValue();
4893   }
4894   default:
4895     return SDValue();
4896   }
4897 }
4898
4899 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4900   SDValue N0 = N->getOperand(0);
4901   SDValue N1 = N->getOperand(1);
4902   SDValue N2 = N->getOperand(2);
4903   EVT VT = N->getValueType(0);
4904   EVT VT0 = N0.getValueType();
4905
4906   // fold (select C, X, X) -> X
4907   if (N1 == N2)
4908     return N1;
4909   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4910     // fold (select true, X, Y) -> X
4911     // fold (select false, X, Y) -> Y
4912     return !N0C->isNullValue() ? N1 : N2;
4913   }
4914   // fold (select C, 1, X) -> (or C, X)
4915   if (VT == MVT::i1 && isOneConstant(N1))
4916     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4917   // fold (select C, 0, 1) -> (xor C, 1)
4918   // We can't do this reliably if integer based booleans have different contents
4919   // to floating point based booleans. This is because we can't tell whether we
4920   // have an integer-based boolean or a floating-point-based boolean unless we
4921   // can find the SETCC that produced it and inspect its operands. This is
4922   // fairly easy if C is the SETCC node, but it can potentially be
4923   // undiscoverable (or not reasonably discoverable). For example, it could be
4924   // in another basic block or it could require searching a complicated
4925   // expression.
4926   if (VT.isInteger() &&
4927       (VT0 == MVT::i1 || (VT0.isInteger() &&
4928                           TLI.getBooleanContents(false, false) ==
4929                               TLI.getBooleanContents(false, true) &&
4930                           TLI.getBooleanContents(false, false) ==
4931                               TargetLowering::ZeroOrOneBooleanContent)) &&
4932       isNullConstant(N1) && isOneConstant(N2)) {
4933     SDValue XORNode;
4934     if (VT == VT0) {
4935       SDLoc DL(N);
4936       return DAG.getNode(ISD::XOR, DL, VT0,
4937                          N0, DAG.getConstant(1, DL, VT0));
4938     }
4939     SDLoc DL0(N0);
4940     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4941                           N0, DAG.getConstant(1, DL0, VT0));
4942     AddToWorklist(XORNode.getNode());
4943     if (VT.bitsGT(VT0))
4944       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4945     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4946   }
4947   // fold (select C, 0, X) -> (and (not C), X)
4948   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4949     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4950     AddToWorklist(NOTNode.getNode());
4951     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4952   }
4953   // fold (select C, X, 1) -> (or (not C), X)
4954   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4955     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4956     AddToWorklist(NOTNode.getNode());
4957     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4958   }
4959   // fold (select C, X, 0) -> (and C, X)
4960   if (VT == MVT::i1 && isNullConstant(N2))
4961     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4962   // fold (select X, X, Y) -> (or X, Y)
4963   // fold (select X, 1, Y) -> (or X, Y)
4964   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4965     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4966   // fold (select X, Y, X) -> (and X, Y)
4967   // fold (select X, Y, 0) -> (and X, Y)
4968   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4969     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4970
4971   // If we can fold this based on the true/false value, do so.
4972   if (SimplifySelectOps(N, N1, N2))
4973     return SDValue(N, 0);  // Don't revisit N.
4974
4975   // fold selects based on a setcc into other things, such as min/max/abs
4976   if (N0.getOpcode() == ISD::SETCC) {
4977     // select x, y (fcmp lt x, y) -> fminnum x, y
4978     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4979     //
4980     // This is OK if we don't care about what happens if either operand is a
4981     // NaN.
4982     //
4983
4984     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4985     // no signed zeros as well as no nans.
4986     const TargetOptions &Options = DAG.getTarget().Options;
4987     if (Options.UnsafeFPMath &&
4988         VT.isFloatingPoint() && N0.hasOneUse() &&
4989         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4990       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4991
4992       SDValue FMinMax =
4993           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4994                               N1, N2, CC, TLI, DAG);
4995       if (FMinMax)
4996         return FMinMax;
4997     }
4998
4999     if ((!LegalOperations &&
5000          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5001         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5002       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5003                          N0.getOperand(0), N0.getOperand(1),
5004                          N1, N2, N0.getOperand(2));
5005     return SimplifySelect(SDLoc(N), N0, N1, N2);
5006   }
5007
5008   if (VT0 == MVT::i1) {
5009     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5010       // select (and Cond0, Cond1), X, Y
5011       //   -> select Cond0, (select Cond1, X, Y), Y
5012       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5013         SDValue Cond0 = N0->getOperand(0);
5014         SDValue Cond1 = N0->getOperand(1);
5015         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5016                                           N1.getValueType(), Cond1, N1, N2);
5017         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5018                            InnerSelect, N2);
5019       }
5020       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5021       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5022         SDValue Cond0 = N0->getOperand(0);
5023         SDValue Cond1 = N0->getOperand(1);
5024         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5025                                           N1.getValueType(), Cond1, N1, N2);
5026         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5027                            InnerSelect);
5028       }
5029     }
5030
5031     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5032     if (N1->getOpcode() == ISD::SELECT) {
5033       SDValue N1_0 = N1->getOperand(0);
5034       SDValue N1_1 = N1->getOperand(1);
5035       SDValue N1_2 = N1->getOperand(2);
5036       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5037         // Create the actual and node if we can generate good code for it.
5038         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5039           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5040                                     N0, N1_0);
5041           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5042                              N1_1, N2);
5043         }
5044         // Otherwise see if we can optimize the "and" to a better pattern.
5045         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5046           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5047                              N1_1, N2);
5048       }
5049     }
5050     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5051     if (N2->getOpcode() == ISD::SELECT) {
5052       SDValue N2_0 = N2->getOperand(0);
5053       SDValue N2_1 = N2->getOperand(1);
5054       SDValue N2_2 = N2->getOperand(2);
5055       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5056         // Create the actual or node if we can generate good code for it.
5057         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5058           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5059                                    N0, N2_0);
5060           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5061                              N1, N2_2);
5062         }
5063         // Otherwise see if we can optimize to a better pattern.
5064         if (SDValue Combined = visitORLike(N0, N2_0, N))
5065           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5066                              N1, N2_2);
5067       }
5068     }
5069   }
5070
5071   return SDValue();
5072 }
5073
5074 static
5075 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5076   SDLoc DL(N);
5077   EVT LoVT, HiVT;
5078   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5079
5080   // Split the inputs.
5081   SDValue Lo, Hi, LL, LH, RL, RH;
5082   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5083   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5084
5085   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5086   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5087
5088   return std::make_pair(Lo, Hi);
5089 }
5090
5091 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5092 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5093 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5094   SDLoc dl(N);
5095   SDValue Cond = N->getOperand(0);
5096   SDValue LHS = N->getOperand(1);
5097   SDValue RHS = N->getOperand(2);
5098   EVT VT = N->getValueType(0);
5099   int NumElems = VT.getVectorNumElements();
5100   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5101          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5102          Cond.getOpcode() == ISD::BUILD_VECTOR);
5103
5104   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5105   // binary ones here.
5106   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5107     return SDValue();
5108
5109   // We're sure we have an even number of elements due to the
5110   // concat_vectors we have as arguments to vselect.
5111   // Skip BV elements until we find one that's not an UNDEF
5112   // After we find an UNDEF element, keep looping until we get to half the
5113   // length of the BV and see if all the non-undef nodes are the same.
5114   ConstantSDNode *BottomHalf = nullptr;
5115   for (int i = 0; i < NumElems / 2; ++i) {
5116     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5117       continue;
5118
5119     if (BottomHalf == nullptr)
5120       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5121     else if (Cond->getOperand(i).getNode() != BottomHalf)
5122       return SDValue();
5123   }
5124
5125   // Do the same for the second half of the BuildVector
5126   ConstantSDNode *TopHalf = nullptr;
5127   for (int i = NumElems / 2; i < NumElems; ++i) {
5128     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5129       continue;
5130
5131     if (TopHalf == nullptr)
5132       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5133     else if (Cond->getOperand(i).getNode() != TopHalf)
5134       return SDValue();
5135   }
5136
5137   assert(TopHalf && BottomHalf &&
5138          "One half of the selector was all UNDEFs and the other was all the "
5139          "same value. This should have been addressed before this function.");
5140   return DAG.getNode(
5141       ISD::CONCAT_VECTORS, dl, VT,
5142       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5143       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5144 }
5145
5146 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5147
5148   if (Level >= AfterLegalizeTypes)
5149     return SDValue();
5150
5151   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5152   SDValue Mask = MSC->getMask();
5153   SDValue Data  = MSC->getValue();
5154   SDLoc DL(N);
5155
5156   // If the MSCATTER data type requires splitting and the mask is provided by a
5157   // SETCC, then split both nodes and its operands before legalization. This
5158   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5159   // and enables future optimizations (e.g. min/max pattern matching on X86).
5160   if (Mask.getOpcode() != ISD::SETCC)
5161     return SDValue();
5162
5163   // Check if any splitting is required.
5164   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5165       TargetLowering::TypeSplitVector)
5166     return SDValue();
5167   SDValue MaskLo, MaskHi, Lo, Hi;
5168   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5169
5170   EVT LoVT, HiVT;
5171   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5172
5173   SDValue Chain = MSC->getChain();
5174
5175   EVT MemoryVT = MSC->getMemoryVT();
5176   unsigned Alignment = MSC->getOriginalAlignment();
5177
5178   EVT LoMemVT, HiMemVT;
5179   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5180
5181   SDValue DataLo, DataHi;
5182   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5183
5184   SDValue BasePtr = MSC->getBasePtr();
5185   SDValue IndexLo, IndexHi;
5186   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5187
5188   MachineMemOperand *MMO = DAG.getMachineFunction().
5189     getMachineMemOperand(MSC->getPointerInfo(),
5190                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5191                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5192
5193   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5194   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5195                             DL, OpsLo, MMO);
5196
5197   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5198   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5199                             DL, OpsHi, MMO);
5200
5201   AddToWorklist(Lo.getNode());
5202   AddToWorklist(Hi.getNode());
5203
5204   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5205 }
5206
5207 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5208
5209   if (Level >= AfterLegalizeTypes)
5210     return SDValue();
5211
5212   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5213   SDValue Mask = MST->getMask();
5214   SDValue Data  = MST->getValue();
5215   SDLoc DL(N);
5216
5217   // If the MSTORE data type requires splitting and the mask is provided by a
5218   // SETCC, then split both nodes and its operands before legalization. This
5219   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5220   // and enables future optimizations (e.g. min/max pattern matching on X86).
5221   if (Mask.getOpcode() == ISD::SETCC) {
5222
5223     // Check if any splitting is required.
5224     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5225         TargetLowering::TypeSplitVector)
5226       return SDValue();
5227
5228     SDValue MaskLo, MaskHi, Lo, Hi;
5229     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5230
5231     EVT LoVT, HiVT;
5232     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5233
5234     SDValue Chain = MST->getChain();
5235     SDValue Ptr   = MST->getBasePtr();
5236
5237     EVT MemoryVT = MST->getMemoryVT();
5238     unsigned Alignment = MST->getOriginalAlignment();
5239
5240     // if Alignment is equal to the vector size,
5241     // take the half of it for the second part
5242     unsigned SecondHalfAlignment =
5243       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5244          Alignment/2 : Alignment;
5245
5246     EVT LoMemVT, HiMemVT;
5247     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5248
5249     SDValue DataLo, DataHi;
5250     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5251
5252     MachineMemOperand *MMO = DAG.getMachineFunction().
5253       getMachineMemOperand(MST->getPointerInfo(),
5254                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5255                            Alignment, MST->getAAInfo(), MST->getRanges());
5256
5257     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5258                             MST->isTruncatingStore());
5259
5260     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5261     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5262                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5263
5264     MMO = DAG.getMachineFunction().
5265       getMachineMemOperand(MST->getPointerInfo(),
5266                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5267                            SecondHalfAlignment, MST->getAAInfo(),
5268                            MST->getRanges());
5269
5270     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5271                             MST->isTruncatingStore());
5272
5273     AddToWorklist(Lo.getNode());
5274     AddToWorklist(Hi.getNode());
5275
5276     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5277   }
5278   return SDValue();
5279 }
5280
5281 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5282
5283   if (Level >= AfterLegalizeTypes)
5284     return SDValue();
5285
5286   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5287   SDValue Mask = MGT->getMask();
5288   SDLoc DL(N);
5289
5290   // If the MGATHER result requires splitting and the mask is provided by a
5291   // SETCC, then split both nodes and its operands before legalization. This
5292   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5293   // and enables future optimizations (e.g. min/max pattern matching on X86).
5294
5295   if (Mask.getOpcode() != ISD::SETCC)
5296     return SDValue();
5297
5298   EVT VT = N->getValueType(0);
5299
5300   // Check if any splitting is required.
5301   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5302       TargetLowering::TypeSplitVector)
5303     return SDValue();
5304
5305   SDValue MaskLo, MaskHi, Lo, Hi;
5306   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5307
5308   SDValue Src0 = MGT->getValue();
5309   SDValue Src0Lo, Src0Hi;
5310   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5311
5312   EVT LoVT, HiVT;
5313   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5314
5315   SDValue Chain = MGT->getChain();
5316   EVT MemoryVT = MGT->getMemoryVT();
5317   unsigned Alignment = MGT->getOriginalAlignment();
5318
5319   EVT LoMemVT, HiMemVT;
5320   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5321
5322   SDValue BasePtr = MGT->getBasePtr();
5323   SDValue Index = MGT->getIndex();
5324   SDValue IndexLo, IndexHi;
5325   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5326
5327   MachineMemOperand *MMO = DAG.getMachineFunction().
5328     getMachineMemOperand(MGT->getPointerInfo(),
5329                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5330                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5331
5332   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5333   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5334                             MMO);
5335
5336   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5337   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5338                             MMO);
5339
5340   AddToWorklist(Lo.getNode());
5341   AddToWorklist(Hi.getNode());
5342
5343   // Build a factor node to remember that this load is independent of the
5344   // other one.
5345   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5346                       Hi.getValue(1));
5347
5348   // Legalized the chain result - switch anything that used the old chain to
5349   // use the new one.
5350   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5351
5352   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5353
5354   SDValue RetOps[] = { GatherRes, Chain };
5355   return DAG.getMergeValues(RetOps, DL);
5356 }
5357
5358 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5359
5360   if (Level >= AfterLegalizeTypes)
5361     return SDValue();
5362
5363   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5364   SDValue Mask = MLD->getMask();
5365   SDLoc DL(N);
5366
5367   // If the MLOAD result requires splitting and the mask is provided by a
5368   // SETCC, then split both nodes and its operands before legalization. This
5369   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5370   // and enables future optimizations (e.g. min/max pattern matching on X86).
5371
5372   if (Mask.getOpcode() == ISD::SETCC) {
5373     EVT VT = N->getValueType(0);
5374
5375     // Check if any splitting is required.
5376     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5377         TargetLowering::TypeSplitVector)
5378       return SDValue();
5379
5380     SDValue MaskLo, MaskHi, Lo, Hi;
5381     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5382
5383     SDValue Src0 = MLD->getSrc0();
5384     SDValue Src0Lo, Src0Hi;
5385     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5386
5387     EVT LoVT, HiVT;
5388     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5389
5390     SDValue Chain = MLD->getChain();
5391     SDValue Ptr   = MLD->getBasePtr();
5392     EVT MemoryVT = MLD->getMemoryVT();
5393     unsigned Alignment = MLD->getOriginalAlignment();
5394
5395     // if Alignment is equal to the vector size,
5396     // take the half of it for the second part
5397     unsigned SecondHalfAlignment =
5398       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5399          Alignment/2 : Alignment;
5400
5401     EVT LoMemVT, HiMemVT;
5402     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5403
5404     MachineMemOperand *MMO = DAG.getMachineFunction().
5405     getMachineMemOperand(MLD->getPointerInfo(),
5406                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5407                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5408
5409     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5410                            ISD::NON_EXTLOAD);
5411
5412     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5413     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5414                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5415
5416     MMO = DAG.getMachineFunction().
5417     getMachineMemOperand(MLD->getPointerInfo(),
5418                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5419                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5420
5421     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5422                            ISD::NON_EXTLOAD);
5423
5424     AddToWorklist(Lo.getNode());
5425     AddToWorklist(Hi.getNode());
5426
5427     // Build a factor node to remember that this load is independent of the
5428     // other one.
5429     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5430                         Hi.getValue(1));
5431
5432     // Legalized the chain result - switch anything that used the old chain to
5433     // use the new one.
5434     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5435
5436     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5437
5438     SDValue RetOps[] = { LoadRes, Chain };
5439     return DAG.getMergeValues(RetOps, DL);
5440   }
5441   return SDValue();
5442 }
5443
5444 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5445   SDValue N0 = N->getOperand(0);
5446   SDValue N1 = N->getOperand(1);
5447   SDValue N2 = N->getOperand(2);
5448   SDLoc DL(N);
5449
5450   // Canonicalize integer abs.
5451   // vselect (setg[te] X,  0),  X, -X ->
5452   // vselect (setgt    X, -1),  X, -X ->
5453   // vselect (setl[te] X,  0), -X,  X ->
5454   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5455   if (N0.getOpcode() == ISD::SETCC) {
5456     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5457     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5458     bool isAbs = false;
5459     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5460
5461     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5462          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5463         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5464       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5465     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5466              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5467       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5468
5469     if (isAbs) {
5470       EVT VT = LHS.getValueType();
5471       SDValue Shift = DAG.getNode(
5472           ISD::SRA, DL, VT, LHS,
5473           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5474       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5475       AddToWorklist(Shift.getNode());
5476       AddToWorklist(Add.getNode());
5477       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5478     }
5479   }
5480
5481   if (SimplifySelectOps(N, N1, N2))
5482     return SDValue(N, 0);  // Don't revisit N.
5483
5484   // If the VSELECT result requires splitting and the mask is provided by a
5485   // SETCC, then split both nodes and its operands before legalization. This
5486   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5487   // and enables future optimizations (e.g. min/max pattern matching on X86).
5488   if (N0.getOpcode() == ISD::SETCC) {
5489     EVT VT = N->getValueType(0);
5490
5491     // Check if any splitting is required.
5492     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5493         TargetLowering::TypeSplitVector)
5494       return SDValue();
5495
5496     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5497     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5498     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5499     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5500
5501     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5502     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5503
5504     // Add the new VSELECT nodes to the work list in case they need to be split
5505     // again.
5506     AddToWorklist(Lo.getNode());
5507     AddToWorklist(Hi.getNode());
5508
5509     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5510   }
5511
5512   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5513   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5514     return N1;
5515   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5516   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5517     return N2;
5518
5519   // The ConvertSelectToConcatVector function is assuming both the above
5520   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5521   // and addressed.
5522   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5523       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5524       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5525     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5526     if (CV.getNode())
5527       return CV;
5528   }
5529
5530   return SDValue();
5531 }
5532
5533 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5534   SDValue N0 = N->getOperand(0);
5535   SDValue N1 = N->getOperand(1);
5536   SDValue N2 = N->getOperand(2);
5537   SDValue N3 = N->getOperand(3);
5538   SDValue N4 = N->getOperand(4);
5539   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5540
5541   // fold select_cc lhs, rhs, x, x, cc -> x
5542   if (N2 == N3)
5543     return N2;
5544
5545   // Determine if the condition we're dealing with is constant
5546   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5547                               N0, N1, CC, SDLoc(N), false);
5548   if (SCC.getNode()) {
5549     AddToWorklist(SCC.getNode());
5550
5551     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5552       if (!SCCC->isNullValue())
5553         return N2;    // cond always true -> true val
5554       else
5555         return N3;    // cond always false -> false val
5556     } else if (SCC->getOpcode() == ISD::UNDEF) {
5557       // When the condition is UNDEF, just return the first operand. This is
5558       // coherent the DAG creation, no setcc node is created in this case
5559       return N2;
5560     } else if (SCC.getOpcode() == ISD::SETCC) {
5561       // Fold to a simpler select_cc
5562       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5563                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5564                          SCC.getOperand(2));
5565     }
5566   }
5567
5568   // If we can fold this based on the true/false value, do so.
5569   if (SimplifySelectOps(N, N2, N3))
5570     return SDValue(N, 0);  // Don't revisit N.
5571
5572   // fold select_cc into other things, such as min/max/abs
5573   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5574 }
5575
5576 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5577   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5578                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5579                        SDLoc(N));
5580 }
5581
5582 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5583 // dag node into a ConstantSDNode or a build_vector of constants.
5584 // This function is called by the DAGCombiner when visiting sext/zext/aext
5585 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5586 // Vector extends are not folded if operations are legal; this is to
5587 // avoid introducing illegal build_vector dag nodes.
5588 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5589                                          SelectionDAG &DAG, bool LegalTypes,
5590                                          bool LegalOperations) {
5591   unsigned Opcode = N->getOpcode();
5592   SDValue N0 = N->getOperand(0);
5593   EVT VT = N->getValueType(0);
5594
5595   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5596          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5597          && "Expected EXTEND dag node in input!");
5598
5599   // fold (sext c1) -> c1
5600   // fold (zext c1) -> c1
5601   // fold (aext c1) -> c1
5602   if (isa<ConstantSDNode>(N0))
5603     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5604
5605   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5606   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5607   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5608   EVT SVT = VT.getScalarType();
5609   if (!(VT.isVector() &&
5610       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5611       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5612     return nullptr;
5613
5614   // We can fold this node into a build_vector.
5615   unsigned VTBits = SVT.getSizeInBits();
5616   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5617   unsigned ShAmt = VTBits - EVTBits;
5618   SmallVector<SDValue, 8> Elts;
5619   unsigned NumElts = VT.getVectorNumElements();
5620   SDLoc DL(N);
5621
5622   for (unsigned i=0; i != NumElts; ++i) {
5623     SDValue Op = N0->getOperand(i);
5624     if (Op->getOpcode() == ISD::UNDEF) {
5625       Elts.push_back(DAG.getUNDEF(SVT));
5626       continue;
5627     }
5628
5629     SDLoc DL(Op);
5630     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5631     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5632     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5633       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5634                                      DL, SVT));
5635     else
5636       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5637                                      DL, SVT));
5638   }
5639
5640   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5641 }
5642
5643 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5644 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5645 // transformation. Returns true if extension are possible and the above
5646 // mentioned transformation is profitable.
5647 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5648                                     unsigned ExtOpc,
5649                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5650                                     const TargetLowering &TLI) {
5651   bool HasCopyToRegUses = false;
5652   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5653   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5654                             UE = N0.getNode()->use_end();
5655        UI != UE; ++UI) {
5656     SDNode *User = *UI;
5657     if (User == N)
5658       continue;
5659     if (UI.getUse().getResNo() != N0.getResNo())
5660       continue;
5661     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5662     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5663       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5664       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5665         // Sign bits will be lost after a zext.
5666         return false;
5667       bool Add = false;
5668       for (unsigned i = 0; i != 2; ++i) {
5669         SDValue UseOp = User->getOperand(i);
5670         if (UseOp == N0)
5671           continue;
5672         if (!isa<ConstantSDNode>(UseOp))
5673           return false;
5674         Add = true;
5675       }
5676       if (Add)
5677         ExtendNodes.push_back(User);
5678       continue;
5679     }
5680     // If truncates aren't free and there are users we can't
5681     // extend, it isn't worthwhile.
5682     if (!isTruncFree)
5683       return false;
5684     // Remember if this value is live-out.
5685     if (User->getOpcode() == ISD::CopyToReg)
5686       HasCopyToRegUses = true;
5687   }
5688
5689   if (HasCopyToRegUses) {
5690     bool BothLiveOut = false;
5691     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5692          UI != UE; ++UI) {
5693       SDUse &Use = UI.getUse();
5694       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5695         BothLiveOut = true;
5696         break;
5697       }
5698     }
5699     if (BothLiveOut)
5700       // Both unextended and extended values are live out. There had better be
5701       // a good reason for the transformation.
5702       return ExtendNodes.size();
5703   }
5704   return true;
5705 }
5706
5707 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5708                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5709                                   ISD::NodeType ExtType) {
5710   // Extend SetCC uses if necessary.
5711   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5712     SDNode *SetCC = SetCCs[i];
5713     SmallVector<SDValue, 4> Ops;
5714
5715     for (unsigned j = 0; j != 2; ++j) {
5716       SDValue SOp = SetCC->getOperand(j);
5717       if (SOp == Trunc)
5718         Ops.push_back(ExtLoad);
5719       else
5720         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5721     }
5722
5723     Ops.push_back(SetCC->getOperand(2));
5724     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5725   }
5726 }
5727
5728 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5729 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5730   SDValue N0 = N->getOperand(0);
5731   EVT DstVT = N->getValueType(0);
5732   EVT SrcVT = N0.getValueType();
5733
5734   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5735           N->getOpcode() == ISD::ZERO_EXTEND) &&
5736          "Unexpected node type (not an extend)!");
5737
5738   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5739   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5740   //   (v8i32 (sext (v8i16 (load x))))
5741   // into:
5742   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5743   //                          (v4i32 (sextload (x + 16)))))
5744   // Where uses of the original load, i.e.:
5745   //   (v8i16 (load x))
5746   // are replaced with:
5747   //   (v8i16 (truncate
5748   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5749   //                            (v4i32 (sextload (x + 16)))))))
5750   //
5751   // This combine is only applicable to illegal, but splittable, vectors.
5752   // All legal types, and illegal non-vector types, are handled elsewhere.
5753   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5754   //
5755   if (N0->getOpcode() != ISD::LOAD)
5756     return SDValue();
5757
5758   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5759
5760   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5761       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5762       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5763     return SDValue();
5764
5765   SmallVector<SDNode *, 4> SetCCs;
5766   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5767     return SDValue();
5768
5769   ISD::LoadExtType ExtType =
5770       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5771
5772   // Try to split the vector types to get down to legal types.
5773   EVT SplitSrcVT = SrcVT;
5774   EVT SplitDstVT = DstVT;
5775   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5776          SplitSrcVT.getVectorNumElements() > 1) {
5777     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5778     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5779   }
5780
5781   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5782     return SDValue();
5783
5784   SDLoc DL(N);
5785   const unsigned NumSplits =
5786       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5787   const unsigned Stride = SplitSrcVT.getStoreSize();
5788   SmallVector<SDValue, 4> Loads;
5789   SmallVector<SDValue, 4> Chains;
5790
5791   SDValue BasePtr = LN0->getBasePtr();
5792   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5793     const unsigned Offset = Idx * Stride;
5794     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5795
5796     SDValue SplitLoad = DAG.getExtLoad(
5797         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5798         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5799         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5800         Align, LN0->getAAInfo());
5801
5802     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5803                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5804
5805     Loads.push_back(SplitLoad.getValue(0));
5806     Chains.push_back(SplitLoad.getValue(1));
5807   }
5808
5809   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5810   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5811
5812   CombineTo(N, NewValue);
5813
5814   // Replace uses of the original load (before extension)
5815   // with a truncate of the concatenated sextloaded vectors.
5816   SDValue Trunc =
5817       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5818   CombineTo(N0.getNode(), Trunc, NewChain);
5819   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5820                   (ISD::NodeType)N->getOpcode());
5821   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5822 }
5823
5824 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5825   SDValue N0 = N->getOperand(0);
5826   EVT VT = N->getValueType(0);
5827
5828   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5829                                               LegalOperations))
5830     return SDValue(Res, 0);
5831
5832   // fold (sext (sext x)) -> (sext x)
5833   // fold (sext (aext x)) -> (sext x)
5834   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5835     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5836                        N0.getOperand(0));
5837
5838   if (N0.getOpcode() == ISD::TRUNCATE) {
5839     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5840     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5841     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5842     if (NarrowLoad.getNode()) {
5843       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5844       if (NarrowLoad.getNode() != N0.getNode()) {
5845         CombineTo(N0.getNode(), NarrowLoad);
5846         // CombineTo deleted the truncate, if needed, but not what's under it.
5847         AddToWorklist(oye);
5848       }
5849       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5850     }
5851
5852     // See if the value being truncated is already sign extended.  If so, just
5853     // eliminate the trunc/sext pair.
5854     SDValue Op = N0.getOperand(0);
5855     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5856     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5857     unsigned DestBits = VT.getScalarType().getSizeInBits();
5858     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5859
5860     if (OpBits == DestBits) {
5861       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5862       // bits, it is already ready.
5863       if (NumSignBits > DestBits-MidBits)
5864         return Op;
5865     } else if (OpBits < DestBits) {
5866       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5867       // bits, just sext from i32.
5868       if (NumSignBits > OpBits-MidBits)
5869         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5870     } else {
5871       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5872       // bits, just truncate to i32.
5873       if (NumSignBits > OpBits-MidBits)
5874         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5875     }
5876
5877     // fold (sext (truncate x)) -> (sextinreg x).
5878     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5879                                                  N0.getValueType())) {
5880       if (OpBits < DestBits)
5881         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5882       else if (OpBits > DestBits)
5883         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5884       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5885                          DAG.getValueType(N0.getValueType()));
5886     }
5887   }
5888
5889   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5890   // Only generate vector extloads when 1) they're legal, and 2) they are
5891   // deemed desirable by the target.
5892   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5893       ((!LegalOperations && !VT.isVector() &&
5894         !cast<LoadSDNode>(N0)->isVolatile()) ||
5895        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5896     bool DoXform = true;
5897     SmallVector<SDNode*, 4> SetCCs;
5898     if (!N0.hasOneUse())
5899       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5900     if (VT.isVector())
5901       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5902     if (DoXform) {
5903       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5904       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5905                                        LN0->getChain(),
5906                                        LN0->getBasePtr(), N0.getValueType(),
5907                                        LN0->getMemOperand());
5908       CombineTo(N, ExtLoad);
5909       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5910                                   N0.getValueType(), ExtLoad);
5911       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5912       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5913                       ISD::SIGN_EXTEND);
5914       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5915     }
5916   }
5917
5918   // fold (sext (load x)) to multiple smaller sextloads.
5919   // Only on illegal but splittable vectors.
5920   if (SDValue ExtLoad = CombineExtLoad(N))
5921     return ExtLoad;
5922
5923   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5924   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5925   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5926       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5927     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5928     EVT MemVT = LN0->getMemoryVT();
5929     if ((!LegalOperations && !LN0->isVolatile()) ||
5930         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5931       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5932                                        LN0->getChain(),
5933                                        LN0->getBasePtr(), MemVT,
5934                                        LN0->getMemOperand());
5935       CombineTo(N, ExtLoad);
5936       CombineTo(N0.getNode(),
5937                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5938                             N0.getValueType(), ExtLoad),
5939                 ExtLoad.getValue(1));
5940       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5941     }
5942   }
5943
5944   // fold (sext (and/or/xor (load x), cst)) ->
5945   //      (and/or/xor (sextload x), (sext cst))
5946   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5947        N0.getOpcode() == ISD::XOR) &&
5948       isa<LoadSDNode>(N0.getOperand(0)) &&
5949       N0.getOperand(1).getOpcode() == ISD::Constant &&
5950       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5951       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5952     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5953     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5954       bool DoXform = true;
5955       SmallVector<SDNode*, 4> SetCCs;
5956       if (!N0.hasOneUse())
5957         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5958                                           SetCCs, TLI);
5959       if (DoXform) {
5960         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5961                                          LN0->getChain(), LN0->getBasePtr(),
5962                                          LN0->getMemoryVT(),
5963                                          LN0->getMemOperand());
5964         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5965         Mask = Mask.sext(VT.getSizeInBits());
5966         SDLoc DL(N);
5967         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5968                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5969         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5970                                     SDLoc(N0.getOperand(0)),
5971                                     N0.getOperand(0).getValueType(), ExtLoad);
5972         CombineTo(N, And);
5973         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5974         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5975                         ISD::SIGN_EXTEND);
5976         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5977       }
5978     }
5979   }
5980
5981   if (N0.getOpcode() == ISD::SETCC) {
5982     EVT N0VT = N0.getOperand(0).getValueType();
5983     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5984     // Only do this before legalize for now.
5985     if (VT.isVector() && !LegalOperations &&
5986         TLI.getBooleanContents(N0VT) ==
5987             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5988       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5989       // of the same size as the compared operands. Only optimize sext(setcc())
5990       // if this is the case.
5991       EVT SVT = getSetCCResultType(N0VT);
5992
5993       // We know that the # elements of the results is the same as the
5994       // # elements of the compare (and the # elements of the compare result
5995       // for that matter).  Check to see that they are the same size.  If so,
5996       // we know that the element size of the sext'd result matches the
5997       // element size of the compare operands.
5998       if (VT.getSizeInBits() == SVT.getSizeInBits())
5999         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6000                              N0.getOperand(1),
6001                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6002
6003       // If the desired elements are smaller or larger than the source
6004       // elements we can use a matching integer vector type and then
6005       // truncate/sign extend
6006       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6007       if (SVT == MatchingVectorType) {
6008         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6009                                N0.getOperand(0), N0.getOperand(1),
6010                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6011         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6012       }
6013     }
6014
6015     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6016     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6017     SDLoc DL(N);
6018     SDValue NegOne =
6019       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6020     SDValue SCC =
6021       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6022                        NegOne, DAG.getConstant(0, DL, VT),
6023                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6024     if (SCC.getNode()) return SCC;
6025
6026     if (!VT.isVector()) {
6027       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6028       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6029         SDLoc DL(N);
6030         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6031         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6032                                      N0.getOperand(0), N0.getOperand(1), CC);
6033         return DAG.getSelect(DL, VT, SetCC,
6034                              NegOne, DAG.getConstant(0, DL, VT));
6035       }
6036     }
6037   }
6038
6039   // fold (sext x) -> (zext x) if the sign bit is known zero.
6040   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6041       DAG.SignBitIsZero(N0))
6042     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6043
6044   return SDValue();
6045 }
6046
6047 // isTruncateOf - If N is a truncate of some other value, return true, record
6048 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6049 // This function computes KnownZero to avoid a duplicated call to
6050 // computeKnownBits in the caller.
6051 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6052                          APInt &KnownZero) {
6053   APInt KnownOne;
6054   if (N->getOpcode() == ISD::TRUNCATE) {
6055     Op = N->getOperand(0);
6056     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6057     return true;
6058   }
6059
6060   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6061       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6062     return false;
6063
6064   SDValue Op0 = N->getOperand(0);
6065   SDValue Op1 = N->getOperand(1);
6066   assert(Op0.getValueType() == Op1.getValueType());
6067
6068   if (isNullConstant(Op0))
6069     Op = Op1;
6070   else if (isNullConstant(Op1))
6071     Op = Op0;
6072   else
6073     return false;
6074
6075   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6076
6077   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6078     return false;
6079
6080   return true;
6081 }
6082
6083 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6084   SDValue N0 = N->getOperand(0);
6085   EVT VT = N->getValueType(0);
6086
6087   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6088                                               LegalOperations))
6089     return SDValue(Res, 0);
6090
6091   // fold (zext (zext x)) -> (zext x)
6092   // fold (zext (aext x)) -> (zext x)
6093   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6094     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6095                        N0.getOperand(0));
6096
6097   // fold (zext (truncate x)) -> (zext x) or
6098   //      (zext (truncate x)) -> (truncate x)
6099   // This is valid when the truncated bits of x are already zero.
6100   // FIXME: We should extend this to work for vectors too.
6101   SDValue Op;
6102   APInt KnownZero;
6103   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6104     APInt TruncatedBits =
6105       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6106       APInt(Op.getValueSizeInBits(), 0) :
6107       APInt::getBitsSet(Op.getValueSizeInBits(),
6108                         N0.getValueSizeInBits(),
6109                         std::min(Op.getValueSizeInBits(),
6110                                  VT.getSizeInBits()));
6111     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6112       if (VT.bitsGT(Op.getValueType()))
6113         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6114       if (VT.bitsLT(Op.getValueType()))
6115         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6116
6117       return Op;
6118     }
6119   }
6120
6121   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6122   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6123   if (N0.getOpcode() == ISD::TRUNCATE) {
6124     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6125     if (NarrowLoad.getNode()) {
6126       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6127       if (NarrowLoad.getNode() != N0.getNode()) {
6128         CombineTo(N0.getNode(), NarrowLoad);
6129         // CombineTo deleted the truncate, if needed, but not what's under it.
6130         AddToWorklist(oye);
6131       }
6132       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6133     }
6134   }
6135
6136   // fold (zext (truncate x)) -> (and x, mask)
6137   if (N0.getOpcode() == ISD::TRUNCATE &&
6138       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6139
6140     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6141     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6142     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6143     if (NarrowLoad.getNode()) {
6144       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6145       if (NarrowLoad.getNode() != N0.getNode()) {
6146         CombineTo(N0.getNode(), NarrowLoad);
6147         // CombineTo deleted the truncate, if needed, but not what's under it.
6148         AddToWorklist(oye);
6149       }
6150       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6151     }
6152
6153     SDValue Op = N0.getOperand(0);
6154     if (Op.getValueType().bitsLT(VT)) {
6155       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6156       AddToWorklist(Op.getNode());
6157     } else if (Op.getValueType().bitsGT(VT)) {
6158       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6159       AddToWorklist(Op.getNode());
6160     }
6161     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6162                                   N0.getValueType().getScalarType());
6163   }
6164
6165   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6166   // if either of the casts is not free.
6167   if (N0.getOpcode() == ISD::AND &&
6168       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6169       N0.getOperand(1).getOpcode() == ISD::Constant &&
6170       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6171                            N0.getValueType()) ||
6172        !TLI.isZExtFree(N0.getValueType(), VT))) {
6173     SDValue X = N0.getOperand(0).getOperand(0);
6174     if (X.getValueType().bitsLT(VT)) {
6175       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6176     } else if (X.getValueType().bitsGT(VT)) {
6177       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6178     }
6179     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6180     Mask = Mask.zext(VT.getSizeInBits());
6181     SDLoc DL(N);
6182     return DAG.getNode(ISD::AND, DL, VT,
6183                        X, DAG.getConstant(Mask, DL, VT));
6184   }
6185
6186   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6187   // Only generate vector extloads when 1) they're legal, and 2) they are
6188   // deemed desirable by the target.
6189   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6190       ((!LegalOperations && !VT.isVector() &&
6191         !cast<LoadSDNode>(N0)->isVolatile()) ||
6192        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6193     bool DoXform = true;
6194     SmallVector<SDNode*, 4> SetCCs;
6195     if (!N0.hasOneUse())
6196       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6197     if (VT.isVector())
6198       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6199     if (DoXform) {
6200       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6201       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6202                                        LN0->getChain(),
6203                                        LN0->getBasePtr(), N0.getValueType(),
6204                                        LN0->getMemOperand());
6205       CombineTo(N, ExtLoad);
6206       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6207                                   N0.getValueType(), ExtLoad);
6208       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6209
6210       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6211                       ISD::ZERO_EXTEND);
6212       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6213     }
6214   }
6215
6216   // fold (zext (load x)) to multiple smaller zextloads.
6217   // Only on illegal but splittable vectors.
6218   if (SDValue ExtLoad = CombineExtLoad(N))
6219     return ExtLoad;
6220
6221   // fold (zext (and/or/xor (load x), cst)) ->
6222   //      (and/or/xor (zextload x), (zext cst))
6223   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6224        N0.getOpcode() == ISD::XOR) &&
6225       isa<LoadSDNode>(N0.getOperand(0)) &&
6226       N0.getOperand(1).getOpcode() == ISD::Constant &&
6227       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6228       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6229     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6230     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6231       bool DoXform = true;
6232       SmallVector<SDNode*, 4> SetCCs;
6233       if (!N0.hasOneUse())
6234         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6235                                           SetCCs, TLI);
6236       if (DoXform) {
6237         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6238                                          LN0->getChain(), LN0->getBasePtr(),
6239                                          LN0->getMemoryVT(),
6240                                          LN0->getMemOperand());
6241         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6242         Mask = Mask.zext(VT.getSizeInBits());
6243         SDLoc DL(N);
6244         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6245                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6246         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6247                                     SDLoc(N0.getOperand(0)),
6248                                     N0.getOperand(0).getValueType(), ExtLoad);
6249         CombineTo(N, And);
6250         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6251         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6252                         ISD::ZERO_EXTEND);
6253         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6254       }
6255     }
6256   }
6257
6258   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6259   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6260   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6261       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6262     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6263     EVT MemVT = LN0->getMemoryVT();
6264     if ((!LegalOperations && !LN0->isVolatile()) ||
6265         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6266       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6267                                        LN0->getChain(),
6268                                        LN0->getBasePtr(), MemVT,
6269                                        LN0->getMemOperand());
6270       CombineTo(N, ExtLoad);
6271       CombineTo(N0.getNode(),
6272                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6273                             ExtLoad),
6274                 ExtLoad.getValue(1));
6275       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6276     }
6277   }
6278
6279   if (N0.getOpcode() == ISD::SETCC) {
6280     if (!LegalOperations && VT.isVector() &&
6281         N0.getValueType().getVectorElementType() == MVT::i1) {
6282       EVT N0VT = N0.getOperand(0).getValueType();
6283       if (getSetCCResultType(N0VT) == N0.getValueType())
6284         return SDValue();
6285
6286       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6287       // Only do this before legalize for now.
6288       EVT EltVT = VT.getVectorElementType();
6289       SDLoc DL(N);
6290       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6291                                     DAG.getConstant(1, DL, EltVT));
6292       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6293         // We know that the # elements of the results is the same as the
6294         // # elements of the compare (and the # elements of the compare result
6295         // for that matter).  Check to see that they are the same size.  If so,
6296         // we know that the element size of the sext'd result matches the
6297         // element size of the compare operands.
6298         return DAG.getNode(ISD::AND, DL, VT,
6299                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6300                                          N0.getOperand(1),
6301                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6302                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6303                                        OneOps));
6304
6305       // If the desired elements are smaller or larger than the source
6306       // elements we can use a matching integer vector type and then
6307       // truncate/sign extend
6308       EVT MatchingElementType =
6309         EVT::getIntegerVT(*DAG.getContext(),
6310                           N0VT.getScalarType().getSizeInBits());
6311       EVT MatchingVectorType =
6312         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6313                          N0VT.getVectorNumElements());
6314       SDValue VsetCC =
6315         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6316                       N0.getOperand(1),
6317                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6318       return DAG.getNode(ISD::AND, DL, VT,
6319                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6320                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6321     }
6322
6323     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6324     SDLoc DL(N);
6325     SDValue SCC =
6326       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6327                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6328                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6329     if (SCC.getNode()) return SCC;
6330   }
6331
6332   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6333   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6334       isa<ConstantSDNode>(N0.getOperand(1)) &&
6335       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6336       N0.hasOneUse()) {
6337     SDValue ShAmt = N0.getOperand(1);
6338     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6339     if (N0.getOpcode() == ISD::SHL) {
6340       SDValue InnerZExt = N0.getOperand(0);
6341       // If the original shl may be shifting out bits, do not perform this
6342       // transformation.
6343       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6344         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6345       if (ShAmtVal > KnownZeroBits)
6346         return SDValue();
6347     }
6348
6349     SDLoc DL(N);
6350
6351     // Ensure that the shift amount is wide enough for the shifted value.
6352     if (VT.getSizeInBits() >= 256)
6353       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6354
6355     return DAG.getNode(N0.getOpcode(), DL, VT,
6356                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6357                        ShAmt);
6358   }
6359
6360   return SDValue();
6361 }
6362
6363 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6364   SDValue N0 = N->getOperand(0);
6365   EVT VT = N->getValueType(0);
6366
6367   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6368                                               LegalOperations))
6369     return SDValue(Res, 0);
6370
6371   // fold (aext (aext x)) -> (aext x)
6372   // fold (aext (zext x)) -> (zext x)
6373   // fold (aext (sext x)) -> (sext x)
6374   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6375       N0.getOpcode() == ISD::ZERO_EXTEND ||
6376       N0.getOpcode() == ISD::SIGN_EXTEND)
6377     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6378
6379   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6380   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6381   if (N0.getOpcode() == ISD::TRUNCATE) {
6382     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6383     if (NarrowLoad.getNode()) {
6384       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6385       if (NarrowLoad.getNode() != N0.getNode()) {
6386         CombineTo(N0.getNode(), NarrowLoad);
6387         // CombineTo deleted the truncate, if needed, but not what's under it.
6388         AddToWorklist(oye);
6389       }
6390       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6391     }
6392   }
6393
6394   // fold (aext (truncate x))
6395   if (N0.getOpcode() == ISD::TRUNCATE) {
6396     SDValue TruncOp = N0.getOperand(0);
6397     if (TruncOp.getValueType() == VT)
6398       return TruncOp; // x iff x size == zext size.
6399     if (TruncOp.getValueType().bitsGT(VT))
6400       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6401     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6402   }
6403
6404   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6405   // if the trunc is not free.
6406   if (N0.getOpcode() == ISD::AND &&
6407       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6408       N0.getOperand(1).getOpcode() == ISD::Constant &&
6409       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6410                           N0.getValueType())) {
6411     SDValue X = N0.getOperand(0).getOperand(0);
6412     if (X.getValueType().bitsLT(VT)) {
6413       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6414     } else if (X.getValueType().bitsGT(VT)) {
6415       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6416     }
6417     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6418     Mask = Mask.zext(VT.getSizeInBits());
6419     SDLoc DL(N);
6420     return DAG.getNode(ISD::AND, DL, VT,
6421                        X, DAG.getConstant(Mask, DL, VT));
6422   }
6423
6424   // fold (aext (load x)) -> (aext (truncate (extload x)))
6425   // None of the supported targets knows how to perform load and any_ext
6426   // on vectors in one instruction.  We only perform this transformation on
6427   // scalars.
6428   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6429       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6430       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6431     bool DoXform = true;
6432     SmallVector<SDNode*, 4> SetCCs;
6433     if (!N0.hasOneUse())
6434       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6435     if (DoXform) {
6436       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6437       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6438                                        LN0->getChain(),
6439                                        LN0->getBasePtr(), N0.getValueType(),
6440                                        LN0->getMemOperand());
6441       CombineTo(N, ExtLoad);
6442       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6443                                   N0.getValueType(), ExtLoad);
6444       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6445       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6446                       ISD::ANY_EXTEND);
6447       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6448     }
6449   }
6450
6451   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6452   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6453   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6454   if (N0.getOpcode() == ISD::LOAD &&
6455       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6456       N0.hasOneUse()) {
6457     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6458     ISD::LoadExtType ExtType = LN0->getExtensionType();
6459     EVT MemVT = LN0->getMemoryVT();
6460     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6461       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6462                                        VT, LN0->getChain(), LN0->getBasePtr(),
6463                                        MemVT, LN0->getMemOperand());
6464       CombineTo(N, ExtLoad);
6465       CombineTo(N0.getNode(),
6466                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6467                             N0.getValueType(), ExtLoad),
6468                 ExtLoad.getValue(1));
6469       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6470     }
6471   }
6472
6473   if (N0.getOpcode() == ISD::SETCC) {
6474     // For vectors:
6475     // aext(setcc) -> vsetcc
6476     // aext(setcc) -> truncate(vsetcc)
6477     // aext(setcc) -> aext(vsetcc)
6478     // Only do this before legalize for now.
6479     if (VT.isVector() && !LegalOperations) {
6480       EVT N0VT = N0.getOperand(0).getValueType();
6481         // We know that the # elements of the results is the same as the
6482         // # elements of the compare (and the # elements of the compare result
6483         // for that matter).  Check to see that they are the same size.  If so,
6484         // we know that the element size of the sext'd result matches the
6485         // element size of the compare operands.
6486       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6487         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6488                              N0.getOperand(1),
6489                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6490       // If the desired elements are smaller or larger than the source
6491       // elements we can use a matching integer vector type and then
6492       // truncate/any extend
6493       else {
6494         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6495         SDValue VsetCC =
6496           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6497                         N0.getOperand(1),
6498                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6499         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6500       }
6501     }
6502
6503     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6504     SDLoc DL(N);
6505     SDValue SCC =
6506       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6507                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6508                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6509     if (SCC.getNode())
6510       return SCC;
6511   }
6512
6513   return SDValue();
6514 }
6515
6516 /// See if the specified operand can be simplified with the knowledge that only
6517 /// the bits specified by Mask are used.  If so, return the simpler operand,
6518 /// otherwise return a null SDValue.
6519 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6520   switch (V.getOpcode()) {
6521   default: break;
6522   case ISD::Constant: {
6523     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6524     assert(CV && "Const value should be ConstSDNode.");
6525     const APInt &CVal = CV->getAPIntValue();
6526     APInt NewVal = CVal & Mask;
6527     if (NewVal != CVal)
6528       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6529     break;
6530   }
6531   case ISD::OR:
6532   case ISD::XOR:
6533     // If the LHS or RHS don't contribute bits to the or, drop them.
6534     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6535       return V.getOperand(1);
6536     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6537       return V.getOperand(0);
6538     break;
6539   case ISD::SRL:
6540     // Only look at single-use SRLs.
6541     if (!V.getNode()->hasOneUse())
6542       break;
6543     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6544       // See if we can recursively simplify the LHS.
6545       unsigned Amt = RHSC->getZExtValue();
6546
6547       // Watch out for shift count overflow though.
6548       if (Amt >= Mask.getBitWidth()) break;
6549       APInt NewMask = Mask << Amt;
6550       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6551       if (SimplifyLHS.getNode())
6552         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6553                            SimplifyLHS, V.getOperand(1));
6554     }
6555   }
6556   return SDValue();
6557 }
6558
6559 /// If the result of a wider load is shifted to right of N  bits and then
6560 /// truncated to a narrower type and where N is a multiple of number of bits of
6561 /// the narrower type, transform it to a narrower load from address + N / num of
6562 /// bits of new type. If the result is to be extended, also fold the extension
6563 /// to form a extending load.
6564 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6565   unsigned Opc = N->getOpcode();
6566
6567   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6568   SDValue N0 = N->getOperand(0);
6569   EVT VT = N->getValueType(0);
6570   EVT ExtVT = VT;
6571
6572   // This transformation isn't valid for vector loads.
6573   if (VT.isVector())
6574     return SDValue();
6575
6576   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6577   // extended to VT.
6578   if (Opc == ISD::SIGN_EXTEND_INREG) {
6579     ExtType = ISD::SEXTLOAD;
6580     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6581   } else if (Opc == ISD::SRL) {
6582     // Another special-case: SRL is basically zero-extending a narrower value.
6583     ExtType = ISD::ZEXTLOAD;
6584     N0 = SDValue(N, 0);
6585     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6586     if (!N01) return SDValue();
6587     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6588                               VT.getSizeInBits() - N01->getZExtValue());
6589   }
6590   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6591     return SDValue();
6592
6593   unsigned EVTBits = ExtVT.getSizeInBits();
6594
6595   // Do not generate loads of non-round integer types since these can
6596   // be expensive (and would be wrong if the type is not byte sized).
6597   if (!ExtVT.isRound())
6598     return SDValue();
6599
6600   unsigned ShAmt = 0;
6601   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6602     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6603       ShAmt = N01->getZExtValue();
6604       // Is the shift amount a multiple of size of VT?
6605       if ((ShAmt & (EVTBits-1)) == 0) {
6606         N0 = N0.getOperand(0);
6607         // Is the load width a multiple of size of VT?
6608         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6609           return SDValue();
6610       }
6611
6612       // At this point, we must have a load or else we can't do the transform.
6613       if (!isa<LoadSDNode>(N0)) return SDValue();
6614
6615       // Because a SRL must be assumed to *need* to zero-extend the high bits
6616       // (as opposed to anyext the high bits), we can't combine the zextload
6617       // lowering of SRL and an sextload.
6618       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6619         return SDValue();
6620
6621       // If the shift amount is larger than the input type then we're not
6622       // accessing any of the loaded bytes.  If the load was a zextload/extload
6623       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6624       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6625         return SDValue();
6626     }
6627   }
6628
6629   // If the load is shifted left (and the result isn't shifted back right),
6630   // we can fold the truncate through the shift.
6631   unsigned ShLeftAmt = 0;
6632   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6633       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6634     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6635       ShLeftAmt = N01->getZExtValue();
6636       N0 = N0.getOperand(0);
6637     }
6638   }
6639
6640   // If we haven't found a load, we can't narrow it.  Don't transform one with
6641   // multiple uses, this would require adding a new load.
6642   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6643     return SDValue();
6644
6645   // Don't change the width of a volatile load.
6646   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6647   if (LN0->isVolatile())
6648     return SDValue();
6649
6650   // Verify that we are actually reducing a load width here.
6651   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6652     return SDValue();
6653
6654   // For the transform to be legal, the load must produce only two values
6655   // (the value loaded and the chain).  Don't transform a pre-increment
6656   // load, for example, which produces an extra value.  Otherwise the
6657   // transformation is not equivalent, and the downstream logic to replace
6658   // uses gets things wrong.
6659   if (LN0->getNumValues() > 2)
6660     return SDValue();
6661
6662   // If the load that we're shrinking is an extload and we're not just
6663   // discarding the extension we can't simply shrink the load. Bail.
6664   // TODO: It would be possible to merge the extensions in some cases.
6665   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6666       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6667     return SDValue();
6668
6669   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6670     return SDValue();
6671
6672   EVT PtrType = N0.getOperand(1).getValueType();
6673
6674   if (PtrType == MVT::Untyped || PtrType.isExtended())
6675     // It's not possible to generate a constant of extended or untyped type.
6676     return SDValue();
6677
6678   // For big endian targets, we need to adjust the offset to the pointer to
6679   // load the correct bytes.
6680   if (TLI.isBigEndian()) {
6681     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6682     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6683     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6684   }
6685
6686   uint64_t PtrOff = ShAmt / 8;
6687   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6688   SDLoc DL(LN0);
6689   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6690                                PtrType, LN0->getBasePtr(),
6691                                DAG.getConstant(PtrOff, DL, PtrType));
6692   AddToWorklist(NewPtr.getNode());
6693
6694   SDValue Load;
6695   if (ExtType == ISD::NON_EXTLOAD)
6696     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6697                         LN0->getPointerInfo().getWithOffset(PtrOff),
6698                         LN0->isVolatile(), LN0->isNonTemporal(),
6699                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6700   else
6701     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6702                           LN0->getPointerInfo().getWithOffset(PtrOff),
6703                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6704                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6705
6706   // Replace the old load's chain with the new load's chain.
6707   WorklistRemover DeadNodes(*this);
6708   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6709
6710   // Shift the result left, if we've swallowed a left shift.
6711   SDValue Result = Load;
6712   if (ShLeftAmt != 0) {
6713     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6714     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6715       ShImmTy = VT;
6716     // If the shift amount is as large as the result size (but, presumably,
6717     // no larger than the source) then the useful bits of the result are
6718     // zero; we can't simply return the shortened shift, because the result
6719     // of that operation is undefined.
6720     SDLoc DL(N0);
6721     if (ShLeftAmt >= VT.getSizeInBits())
6722       Result = DAG.getConstant(0, DL, VT);
6723     else
6724       Result = DAG.getNode(ISD::SHL, DL, VT,
6725                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6726   }
6727
6728   // Return the new loaded value.
6729   return Result;
6730 }
6731
6732 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6733   SDValue N0 = N->getOperand(0);
6734   SDValue N1 = N->getOperand(1);
6735   EVT VT = N->getValueType(0);
6736   EVT EVT = cast<VTSDNode>(N1)->getVT();
6737   unsigned VTBits = VT.getScalarType().getSizeInBits();
6738   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6739
6740   // fold (sext_in_reg c1) -> c1
6741   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6742     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6743
6744   // If the input is already sign extended, just drop the extension.
6745   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6746     return N0;
6747
6748   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6749   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6750       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6751     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6752                        N0.getOperand(0), N1);
6753
6754   // fold (sext_in_reg (sext x)) -> (sext x)
6755   // fold (sext_in_reg (aext x)) -> (sext x)
6756   // if x is small enough.
6757   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6758     SDValue N00 = N0.getOperand(0);
6759     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6760         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6761       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6762   }
6763
6764   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6765   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6766     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6767
6768   // fold operands of sext_in_reg based on knowledge that the top bits are not
6769   // demanded.
6770   if (SimplifyDemandedBits(SDValue(N, 0)))
6771     return SDValue(N, 0);
6772
6773   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6774   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6775   SDValue NarrowLoad = ReduceLoadWidth(N);
6776   if (NarrowLoad.getNode())
6777     return NarrowLoad;
6778
6779   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6780   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6781   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6782   if (N0.getOpcode() == ISD::SRL) {
6783     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6784       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6785         // We can turn this into an SRA iff the input to the SRL is already sign
6786         // extended enough.
6787         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6788         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6789           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6790                              N0.getOperand(0), N0.getOperand(1));
6791       }
6792   }
6793
6794   // fold (sext_inreg (extload x)) -> (sextload x)
6795   if (ISD::isEXTLoad(N0.getNode()) &&
6796       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6797       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6798       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6799        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6800     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6801     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6802                                      LN0->getChain(),
6803                                      LN0->getBasePtr(), EVT,
6804                                      LN0->getMemOperand());
6805     CombineTo(N, ExtLoad);
6806     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6807     AddToWorklist(ExtLoad.getNode());
6808     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6809   }
6810   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6811   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6812       N0.hasOneUse() &&
6813       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6814       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6815        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6816     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6817     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6818                                      LN0->getChain(),
6819                                      LN0->getBasePtr(), EVT,
6820                                      LN0->getMemOperand());
6821     CombineTo(N, ExtLoad);
6822     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6823     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6824   }
6825
6826   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6827   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6828     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6829                                        N0.getOperand(1), false);
6830     if (BSwap.getNode())
6831       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6832                          BSwap, N1);
6833   }
6834
6835   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6836   // into a build_vector.
6837   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6838     SmallVector<SDValue, 8> Elts;
6839     unsigned NumElts = N0->getNumOperands();
6840     unsigned ShAmt = VTBits - EVTBits;
6841
6842     for (unsigned i = 0; i != NumElts; ++i) {
6843       SDValue Op = N0->getOperand(i);
6844       if (Op->getOpcode() == ISD::UNDEF) {
6845         Elts.push_back(Op);
6846         continue;
6847       }
6848
6849       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6850       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6851       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6852                                      SDLoc(Op), Op.getValueType()));
6853     }
6854
6855     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6856   }
6857
6858   return SDValue();
6859 }
6860
6861 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6862   SDValue N0 = N->getOperand(0);
6863   EVT VT = N->getValueType(0);
6864
6865   if (N0.getOpcode() == ISD::UNDEF)
6866     return DAG.getUNDEF(VT);
6867
6868   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6869                                               LegalOperations))
6870     return SDValue(Res, 0);
6871
6872   return SDValue();
6873 }
6874
6875 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6876   SDValue N0 = N->getOperand(0);
6877   EVT VT = N->getValueType(0);
6878   bool isLE = TLI.isLittleEndian();
6879
6880   // noop truncate
6881   if (N0.getValueType() == N->getValueType(0))
6882     return N0;
6883   // fold (truncate c1) -> c1
6884   if (isConstantIntBuildVectorOrConstantInt(N0))
6885     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6886   // fold (truncate (truncate x)) -> (truncate x)
6887   if (N0.getOpcode() == ISD::TRUNCATE)
6888     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6889   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6890   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6891       N0.getOpcode() == ISD::SIGN_EXTEND ||
6892       N0.getOpcode() == ISD::ANY_EXTEND) {
6893     if (N0.getOperand(0).getValueType().bitsLT(VT))
6894       // if the source is smaller than the dest, we still need an extend
6895       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6896                          N0.getOperand(0));
6897     if (N0.getOperand(0).getValueType().bitsGT(VT))
6898       // if the source is larger than the dest, than we just need the truncate
6899       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6900     // if the source and dest are the same type, we can drop both the extend
6901     // and the truncate.
6902     return N0.getOperand(0);
6903   }
6904
6905   // Fold extract-and-trunc into a narrow extract. For example:
6906   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6907   //   i32 y = TRUNCATE(i64 x)
6908   //        -- becomes --
6909   //   v16i8 b = BITCAST (v2i64 val)
6910   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6911   //
6912   // Note: We only run this optimization after type legalization (which often
6913   // creates this pattern) and before operation legalization after which
6914   // we need to be more careful about the vector instructions that we generate.
6915   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6916       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6917
6918     EVT VecTy = N0.getOperand(0).getValueType();
6919     EVT ExTy = N0.getValueType();
6920     EVT TrTy = N->getValueType(0);
6921
6922     unsigned NumElem = VecTy.getVectorNumElements();
6923     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6924
6925     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6926     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6927
6928     SDValue EltNo = N0->getOperand(1);
6929     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6930       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6931       EVT IndexTy = TLI.getVectorIdxTy();
6932       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6933
6934       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6935                               NVT, N0.getOperand(0));
6936
6937       SDLoc DL(N);
6938       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6939                          DL, TrTy, V,
6940                          DAG.getConstant(Index, DL, IndexTy));
6941     }
6942   }
6943
6944   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6945   if (N0.getOpcode() == ISD::SELECT) {
6946     EVT SrcVT = N0.getValueType();
6947     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6948         TLI.isTruncateFree(SrcVT, VT)) {
6949       SDLoc SL(N0);
6950       SDValue Cond = N0.getOperand(0);
6951       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6952       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6953       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6954     }
6955   }
6956
6957   // Fold a series of buildvector, bitcast, and truncate if possible.
6958   // For example fold
6959   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6960   //   (2xi32 (buildvector x, y)).
6961   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6962       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6963       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6964       N0.getOperand(0).hasOneUse()) {
6965
6966     SDValue BuildVect = N0.getOperand(0);
6967     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6968     EVT TruncVecEltTy = VT.getVectorElementType();
6969
6970     // Check that the element types match.
6971     if (BuildVectEltTy == TruncVecEltTy) {
6972       // Now we only need to compute the offset of the truncated elements.
6973       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6974       unsigned TruncVecNumElts = VT.getVectorNumElements();
6975       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6976
6977       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6978              "Invalid number of elements");
6979
6980       SmallVector<SDValue, 8> Opnds;
6981       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6982         Opnds.push_back(BuildVect.getOperand(i));
6983
6984       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6985     }
6986   }
6987
6988   // See if we can simplify the input to this truncate through knowledge that
6989   // only the low bits are being used.
6990   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6991   // Currently we only perform this optimization on scalars because vectors
6992   // may have different active low bits.
6993   if (!VT.isVector()) {
6994     SDValue Shorter =
6995       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6996                                                VT.getSizeInBits()));
6997     if (Shorter.getNode())
6998       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6999   }
7000   // fold (truncate (load x)) -> (smaller load x)
7001   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7002   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7003     SDValue Reduced = ReduceLoadWidth(N);
7004     if (Reduced.getNode())
7005       return Reduced;
7006     // Handle the case where the load remains an extending load even
7007     // after truncation.
7008     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7009       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7010       if (!LN0->isVolatile() &&
7011           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7012         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7013                                          VT, LN0->getChain(), LN0->getBasePtr(),
7014                                          LN0->getMemoryVT(),
7015                                          LN0->getMemOperand());
7016         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7017         return NewLoad;
7018       }
7019     }
7020   }
7021   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7022   // where ... are all 'undef'.
7023   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7024     SmallVector<EVT, 8> VTs;
7025     SDValue V;
7026     unsigned Idx = 0;
7027     unsigned NumDefs = 0;
7028
7029     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7030       SDValue X = N0.getOperand(i);
7031       if (X.getOpcode() != ISD::UNDEF) {
7032         V = X;
7033         Idx = i;
7034         NumDefs++;
7035       }
7036       // Stop if more than one members are non-undef.
7037       if (NumDefs > 1)
7038         break;
7039       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7040                                      VT.getVectorElementType(),
7041                                      X.getValueType().getVectorNumElements()));
7042     }
7043
7044     if (NumDefs == 0)
7045       return DAG.getUNDEF(VT);
7046
7047     if (NumDefs == 1) {
7048       assert(V.getNode() && "The single defined operand is empty!");
7049       SmallVector<SDValue, 8> Opnds;
7050       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7051         if (i != Idx) {
7052           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7053           continue;
7054         }
7055         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7056         AddToWorklist(NV.getNode());
7057         Opnds.push_back(NV);
7058       }
7059       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7060     }
7061   }
7062
7063   // Simplify the operands using demanded-bits information.
7064   if (!VT.isVector() &&
7065       SimplifyDemandedBits(SDValue(N, 0)))
7066     return SDValue(N, 0);
7067
7068   return SDValue();
7069 }
7070
7071 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7072   SDValue Elt = N->getOperand(i);
7073   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7074     return Elt.getNode();
7075   return Elt.getOperand(Elt.getResNo()).getNode();
7076 }
7077
7078 /// build_pair (load, load) -> load
7079 /// if load locations are consecutive.
7080 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7081   assert(N->getOpcode() == ISD::BUILD_PAIR);
7082
7083   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7084   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7085   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7086       LD1->getAddressSpace() != LD2->getAddressSpace())
7087     return SDValue();
7088   EVT LD1VT = LD1->getValueType(0);
7089
7090   if (ISD::isNON_EXTLoad(LD2) &&
7091       LD2->hasOneUse() &&
7092       // If both are volatile this would reduce the number of volatile loads.
7093       // If one is volatile it might be ok, but play conservative and bail out.
7094       !LD1->isVolatile() &&
7095       !LD2->isVolatile() &&
7096       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7097     unsigned Align = LD1->getAlignment();
7098     unsigned NewAlign = TLI.getDataLayout()->
7099       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7100
7101     if (NewAlign <= Align &&
7102         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7103       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7104                          LD1->getBasePtr(), LD1->getPointerInfo(),
7105                          false, false, false, Align);
7106   }
7107
7108   return SDValue();
7109 }
7110
7111 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7112   SDValue N0 = N->getOperand(0);
7113   EVT VT = N->getValueType(0);
7114
7115   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7116   // Only do this before legalize, since afterward the target may be depending
7117   // on the bitconvert.
7118   // First check to see if this is all constant.
7119   if (!LegalTypes &&
7120       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7121       VT.isVector()) {
7122     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7123
7124     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7125     assert(!DestEltVT.isVector() &&
7126            "Element type of vector ValueType must not be vector!");
7127     if (isSimple)
7128       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7129   }
7130
7131   // If the input is a constant, let getNode fold it.
7132   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7133     // If we can't allow illegal operations, we need to check that this is just
7134     // a fp -> int or int -> conversion and that the resulting operation will
7135     // be legal.
7136     if (!LegalOperations ||
7137         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7138          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7139         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7140          TLI.isOperationLegal(ISD::Constant, VT)))
7141       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7142   }
7143
7144   // (conv (conv x, t1), t2) -> (conv x, t2)
7145   if (N0.getOpcode() == ISD::BITCAST)
7146     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7147                        N0.getOperand(0));
7148
7149   // fold (conv (load x)) -> (load (conv*)x)
7150   // If the resultant load doesn't need a higher alignment than the original!
7151   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7152       // Do not change the width of a volatile load.
7153       !cast<LoadSDNode>(N0)->isVolatile() &&
7154       // Do not remove the cast if the types differ in endian layout.
7155       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7156       TLI.hasBigEndianPartOrdering(VT) &&
7157       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7158       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7159     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7160     unsigned Align = TLI.getDataLayout()->
7161       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7162     unsigned OrigAlign = LN0->getAlignment();
7163
7164     if (Align <= OrigAlign) {
7165       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7166                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7167                                  LN0->isVolatile(), LN0->isNonTemporal(),
7168                                  LN0->isInvariant(), OrigAlign,
7169                                  LN0->getAAInfo());
7170       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7171       return Load;
7172     }
7173   }
7174
7175   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7176   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7177   // This often reduces constant pool loads.
7178   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7179        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7180       N0.getNode()->hasOneUse() && VT.isInteger() &&
7181       !VT.isVector() && !N0.getValueType().isVector()) {
7182     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7183                                   N0.getOperand(0));
7184     AddToWorklist(NewConv.getNode());
7185
7186     SDLoc DL(N);
7187     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7188     if (N0.getOpcode() == ISD::FNEG)
7189       return DAG.getNode(ISD::XOR, DL, VT,
7190                          NewConv, DAG.getConstant(SignBit, DL, VT));
7191     assert(N0.getOpcode() == ISD::FABS);
7192     return DAG.getNode(ISD::AND, DL, VT,
7193                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7194   }
7195
7196   // fold (bitconvert (fcopysign cst, x)) ->
7197   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7198   // Note that we don't handle (copysign x, cst) because this can always be
7199   // folded to an fneg or fabs.
7200   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7201       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7202       VT.isInteger() && !VT.isVector()) {
7203     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7204     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7205     if (isTypeLegal(IntXVT)) {
7206       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7207                               IntXVT, N0.getOperand(1));
7208       AddToWorklist(X.getNode());
7209
7210       // If X has a different width than the result/lhs, sext it or truncate it.
7211       unsigned VTWidth = VT.getSizeInBits();
7212       if (OrigXWidth < VTWidth) {
7213         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7214         AddToWorklist(X.getNode());
7215       } else if (OrigXWidth > VTWidth) {
7216         // To get the sign bit in the right place, we have to shift it right
7217         // before truncating.
7218         SDLoc DL(X);
7219         X = DAG.getNode(ISD::SRL, DL,
7220                         X.getValueType(), X,
7221                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7222                                         X.getValueType()));
7223         AddToWorklist(X.getNode());
7224         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7225         AddToWorklist(X.getNode());
7226       }
7227
7228       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7229       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7230                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7231       AddToWorklist(X.getNode());
7232
7233       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7234                                 VT, N0.getOperand(0));
7235       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7236                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7237       AddToWorklist(Cst.getNode());
7238
7239       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7240     }
7241   }
7242
7243   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7244   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7245     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7246     if (CombineLD.getNode())
7247       return CombineLD;
7248   }
7249
7250   // Remove double bitcasts from shuffles - this is often a legacy of
7251   // XformToShuffleWithZero being used to combine bitmaskings (of
7252   // float vectors bitcast to integer vectors) into shuffles.
7253   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7254   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7255       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7256       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7257       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7258     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7259
7260     // If operands are a bitcast, peek through if it casts the original VT.
7261     // If operands are a UNDEF or constant, just bitcast back to original VT.
7262     auto PeekThroughBitcast = [&](SDValue Op) {
7263       if (Op.getOpcode() == ISD::BITCAST &&
7264           Op.getOperand(0)->getValueType(0) == VT)
7265         return SDValue(Op.getOperand(0));
7266       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7267           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7268         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7269       return SDValue();
7270     };
7271
7272     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7273     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7274     if (!(SV0 && SV1))
7275       return SDValue();
7276
7277     int MaskScale =
7278         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7279     SmallVector<int, 8> NewMask;
7280     for (int M : SVN->getMask())
7281       for (int i = 0; i != MaskScale; ++i)
7282         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7283
7284     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7285     if (!LegalMask) {
7286       std::swap(SV0, SV1);
7287       ShuffleVectorSDNode::commuteMask(NewMask);
7288       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7289     }
7290
7291     if (LegalMask)
7292       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7293   }
7294
7295   return SDValue();
7296 }
7297
7298 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7299   EVT VT = N->getValueType(0);
7300   return CombineConsecutiveLoads(N, VT);
7301 }
7302
7303 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7304 /// operands. DstEltVT indicates the destination element value type.
7305 SDValue DAGCombiner::
7306 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7307   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7308
7309   // If this is already the right type, we're done.
7310   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7311
7312   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7313   unsigned DstBitSize = DstEltVT.getSizeInBits();
7314
7315   // If this is a conversion of N elements of one type to N elements of another
7316   // type, convert each element.  This handles FP<->INT cases.
7317   if (SrcBitSize == DstBitSize) {
7318     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7319                               BV->getValueType(0).getVectorNumElements());
7320
7321     // Due to the FP element handling below calling this routine recursively,
7322     // we can end up with a scalar-to-vector node here.
7323     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7324       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7325                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7326                                      DstEltVT, BV->getOperand(0)));
7327
7328     SmallVector<SDValue, 8> Ops;
7329     for (SDValue Op : BV->op_values()) {
7330       // If the vector element type is not legal, the BUILD_VECTOR operands
7331       // are promoted and implicitly truncated.  Make that explicit here.
7332       if (Op.getValueType() != SrcEltVT)
7333         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7334       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7335                                 DstEltVT, Op));
7336       AddToWorklist(Ops.back().getNode());
7337     }
7338     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7339   }
7340
7341   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7342   // handle annoying details of growing/shrinking FP values, we convert them to
7343   // int first.
7344   if (SrcEltVT.isFloatingPoint()) {
7345     // Convert the input float vector to a int vector where the elements are the
7346     // same sizes.
7347     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7348     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7349     SrcEltVT = IntVT;
7350   }
7351
7352   // Now we know the input is an integer vector.  If the output is a FP type,
7353   // convert to integer first, then to FP of the right size.
7354   if (DstEltVT.isFloatingPoint()) {
7355     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7356     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7357
7358     // Next, convert to FP elements of the same size.
7359     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7360   }
7361
7362   SDLoc DL(BV);
7363
7364   // Okay, we know the src/dst types are both integers of differing types.
7365   // Handling growing first.
7366   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7367   if (SrcBitSize < DstBitSize) {
7368     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7369
7370     SmallVector<SDValue, 8> Ops;
7371     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7372          i += NumInputsPerOutput) {
7373       bool isLE = TLI.isLittleEndian();
7374       APInt NewBits = APInt(DstBitSize, 0);
7375       bool EltIsUndef = true;
7376       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7377         // Shift the previously computed bits over.
7378         NewBits <<= SrcBitSize;
7379         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7380         if (Op.getOpcode() == ISD::UNDEF) continue;
7381         EltIsUndef = false;
7382
7383         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7384                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7385       }
7386
7387       if (EltIsUndef)
7388         Ops.push_back(DAG.getUNDEF(DstEltVT));
7389       else
7390         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7391     }
7392
7393     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7394     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7395   }
7396
7397   // Finally, this must be the case where we are shrinking elements: each input
7398   // turns into multiple outputs.
7399   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7400   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7401                             NumOutputsPerInput*BV->getNumOperands());
7402   SmallVector<SDValue, 8> Ops;
7403
7404   for (const SDValue &Op : BV->op_values()) {
7405     if (Op.getOpcode() == ISD::UNDEF) {
7406       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7407       continue;
7408     }
7409
7410     APInt OpVal = cast<ConstantSDNode>(Op)->
7411                   getAPIntValue().zextOrTrunc(SrcBitSize);
7412
7413     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7414       APInt ThisVal = OpVal.trunc(DstBitSize);
7415       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7416       OpVal = OpVal.lshr(DstBitSize);
7417     }
7418
7419     // For big endian targets, swap the order of the pieces of each element.
7420     if (TLI.isBigEndian())
7421       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7422   }
7423
7424   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7425 }
7426
7427 /// Try to perform FMA combining on a given FADD node.
7428 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7429   SDValue N0 = N->getOperand(0);
7430   SDValue N1 = N->getOperand(1);
7431   EVT VT = N->getValueType(0);
7432   SDLoc SL(N);
7433
7434   const TargetOptions &Options = DAG.getTarget().Options;
7435   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7436                        Options.UnsafeFPMath);
7437
7438   // Floating-point multiply-add with intermediate rounding.
7439   bool HasFMAD = (LegalOperations &&
7440                   TLI.isOperationLegal(ISD::FMAD, VT));
7441
7442   // Floating-point multiply-add without intermediate rounding.
7443   bool HasFMA = ((!LegalOperations ||
7444                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7445                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7446                  UnsafeFPMath);
7447
7448   // No valid opcode, do not combine.
7449   if (!HasFMAD && !HasFMA)
7450     return SDValue();
7451
7452   // Always prefer FMAD to FMA for precision.
7453   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7454   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7455   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7456
7457   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7458   if (N0.getOpcode() == ISD::FMUL &&
7459       (Aggressive || N0->hasOneUse())) {
7460     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7461                        N0.getOperand(0), N0.getOperand(1), N1);
7462   }
7463
7464   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7465   // Note: Commutes FADD operands.
7466   if (N1.getOpcode() == ISD::FMUL &&
7467       (Aggressive || N1->hasOneUse())) {
7468     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7469                        N1.getOperand(0), N1.getOperand(1), N0);
7470   }
7471
7472   // Look through FP_EXTEND nodes to do more combining.
7473   if (UnsafeFPMath && LookThroughFPExt) {
7474     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7475     if (N0.getOpcode() == ISD::FP_EXTEND) {
7476       SDValue N00 = N0.getOperand(0);
7477       if (N00.getOpcode() == ISD::FMUL)
7478         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7479                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7480                                        N00.getOperand(0)),
7481                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7482                                        N00.getOperand(1)), N1);
7483     }
7484
7485     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7486     // Note: Commutes FADD operands.
7487     if (N1.getOpcode() == ISD::FP_EXTEND) {
7488       SDValue N10 = N1.getOperand(0);
7489       if (N10.getOpcode() == ISD::FMUL)
7490         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7491                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7492                                        N10.getOperand(0)),
7493                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7494                                        N10.getOperand(1)), N0);
7495     }
7496   }
7497
7498   // More folding opportunities when target permits.
7499   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7500     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7501     if (N0.getOpcode() == PreferredFusedOpcode &&
7502         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7503       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7504                          N0.getOperand(0), N0.getOperand(1),
7505                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7506                                      N0.getOperand(2).getOperand(0),
7507                                      N0.getOperand(2).getOperand(1),
7508                                      N1));
7509     }
7510
7511     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7512     if (N1->getOpcode() == PreferredFusedOpcode &&
7513         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7514       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7515                          N1.getOperand(0), N1.getOperand(1),
7516                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7517                                      N1.getOperand(2).getOperand(0),
7518                                      N1.getOperand(2).getOperand(1),
7519                                      N0));
7520     }
7521
7522     if (UnsafeFPMath && LookThroughFPExt) {
7523       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7524       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7525       auto FoldFAddFMAFPExtFMul = [&] (
7526           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7527         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7528                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7529                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7530                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7531                                        Z));
7532       };
7533       if (N0.getOpcode() == PreferredFusedOpcode) {
7534         SDValue N02 = N0.getOperand(2);
7535         if (N02.getOpcode() == ISD::FP_EXTEND) {
7536           SDValue N020 = N02.getOperand(0);
7537           if (N020.getOpcode() == ISD::FMUL)
7538             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7539                                         N020.getOperand(0), N020.getOperand(1),
7540                                         N1);
7541         }
7542       }
7543
7544       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7545       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7546       // FIXME: This turns two single-precision and one double-precision
7547       // operation into two double-precision operations, which might not be
7548       // interesting for all targets, especially GPUs.
7549       auto FoldFAddFPExtFMAFMul = [&] (
7550           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7551         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7552                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7553                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7554                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7555                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7556                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7557                                        Z));
7558       };
7559       if (N0.getOpcode() == ISD::FP_EXTEND) {
7560         SDValue N00 = N0.getOperand(0);
7561         if (N00.getOpcode() == PreferredFusedOpcode) {
7562           SDValue N002 = N00.getOperand(2);
7563           if (N002.getOpcode() == ISD::FMUL)
7564             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7565                                         N002.getOperand(0), N002.getOperand(1),
7566                                         N1);
7567         }
7568       }
7569
7570       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7571       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7572       if (N1.getOpcode() == PreferredFusedOpcode) {
7573         SDValue N12 = N1.getOperand(2);
7574         if (N12.getOpcode() == ISD::FP_EXTEND) {
7575           SDValue N120 = N12.getOperand(0);
7576           if (N120.getOpcode() == ISD::FMUL)
7577             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7578                                         N120.getOperand(0), N120.getOperand(1),
7579                                         N0);
7580         }
7581       }
7582
7583       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7584       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7585       // FIXME: This turns two single-precision and one double-precision
7586       // operation into two double-precision operations, which might not be
7587       // interesting for all targets, especially GPUs.
7588       if (N1.getOpcode() == ISD::FP_EXTEND) {
7589         SDValue N10 = N1.getOperand(0);
7590         if (N10.getOpcode() == PreferredFusedOpcode) {
7591           SDValue N102 = N10.getOperand(2);
7592           if (N102.getOpcode() == ISD::FMUL)
7593             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7594                                         N102.getOperand(0), N102.getOperand(1),
7595                                         N0);
7596         }
7597       }
7598     }
7599   }
7600
7601   return SDValue();
7602 }
7603
7604 /// Try to perform FMA combining on a given FSUB node.
7605 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7606   SDValue N0 = N->getOperand(0);
7607   SDValue N1 = N->getOperand(1);
7608   EVT VT = N->getValueType(0);
7609   SDLoc SL(N);
7610
7611   const TargetOptions &Options = DAG.getTarget().Options;
7612   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7613                        Options.UnsafeFPMath);
7614
7615   // Floating-point multiply-add with intermediate rounding.
7616   bool HasFMAD = (LegalOperations &&
7617                   TLI.isOperationLegal(ISD::FMAD, VT));
7618
7619   // Floating-point multiply-add without intermediate rounding.
7620   bool HasFMA = ((!LegalOperations ||
7621                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7622                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7623                  UnsafeFPMath);
7624
7625   // No valid opcode, do not combine.
7626   if (!HasFMAD && !HasFMA)
7627     return SDValue();
7628
7629   // Always prefer FMAD to FMA for precision.
7630   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7631   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7632   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7633
7634   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7635   if (N0.getOpcode() == ISD::FMUL &&
7636       (Aggressive || N0->hasOneUse())) {
7637     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7638                        N0.getOperand(0), N0.getOperand(1),
7639                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7640   }
7641
7642   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7643   // Note: Commutes FSUB operands.
7644   if (N1.getOpcode() == ISD::FMUL &&
7645       (Aggressive || N1->hasOneUse()))
7646     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7647                        DAG.getNode(ISD::FNEG, SL, VT,
7648                                    N1.getOperand(0)),
7649                        N1.getOperand(1), N0);
7650
7651   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7652   if (N0.getOpcode() == ISD::FNEG &&
7653       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7654       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7655     SDValue N00 = N0.getOperand(0).getOperand(0);
7656     SDValue N01 = N0.getOperand(0).getOperand(1);
7657     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7658                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7659                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7660   }
7661
7662   // Look through FP_EXTEND nodes to do more combining.
7663   if (UnsafeFPMath && LookThroughFPExt) {
7664     // fold (fsub (fpext (fmul x, y)), z)
7665     //   -> (fma (fpext x), (fpext y), (fneg z))
7666     if (N0.getOpcode() == ISD::FP_EXTEND) {
7667       SDValue N00 = N0.getOperand(0);
7668       if (N00.getOpcode() == ISD::FMUL)
7669         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7670                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7671                                        N00.getOperand(0)),
7672                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7673                                        N00.getOperand(1)),
7674                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7675     }
7676
7677     // fold (fsub x, (fpext (fmul y, z)))
7678     //   -> (fma (fneg (fpext y)), (fpext z), x)
7679     // Note: Commutes FSUB operands.
7680     if (N1.getOpcode() == ISD::FP_EXTEND) {
7681       SDValue N10 = N1.getOperand(0);
7682       if (N10.getOpcode() == ISD::FMUL)
7683         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7684                            DAG.getNode(ISD::FNEG, SL, VT,
7685                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7686                                                    N10.getOperand(0))),
7687                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7688                                        N10.getOperand(1)),
7689                            N0);
7690     }
7691
7692     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7693     //   -> (fneg (fma (fpext x), (fpext y), z))
7694     // Note: This could be removed with appropriate canonicalization of the
7695     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7696     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7697     // from implementing the canonicalization in visitFSUB.
7698     if (N0.getOpcode() == ISD::FP_EXTEND) {
7699       SDValue N00 = N0.getOperand(0);
7700       if (N00.getOpcode() == ISD::FNEG) {
7701         SDValue N000 = N00.getOperand(0);
7702         if (N000.getOpcode() == ISD::FMUL) {
7703           return DAG.getNode(ISD::FNEG, SL, VT,
7704                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7705                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7706                                                      N000.getOperand(0)),
7707                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7708                                                      N000.getOperand(1)),
7709                                          N1));
7710         }
7711       }
7712     }
7713
7714     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7715     //   -> (fneg (fma (fpext x)), (fpext y), z)
7716     // Note: This could be removed with appropriate canonicalization of the
7717     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7718     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7719     // from implementing the canonicalization in visitFSUB.
7720     if (N0.getOpcode() == ISD::FNEG) {
7721       SDValue N00 = N0.getOperand(0);
7722       if (N00.getOpcode() == ISD::FP_EXTEND) {
7723         SDValue N000 = N00.getOperand(0);
7724         if (N000.getOpcode() == ISD::FMUL) {
7725           return DAG.getNode(ISD::FNEG, SL, VT,
7726                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7727                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7728                                                      N000.getOperand(0)),
7729                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7730                                                      N000.getOperand(1)),
7731                                          N1));
7732         }
7733       }
7734     }
7735
7736   }
7737
7738   // More folding opportunities when target permits.
7739   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7740     // fold (fsub (fma x, y, (fmul u, v)), z)
7741     //   -> (fma x, y (fma u, v, (fneg z)))
7742     if (N0.getOpcode() == PreferredFusedOpcode &&
7743         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7744       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7745                          N0.getOperand(0), N0.getOperand(1),
7746                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7747                                      N0.getOperand(2).getOperand(0),
7748                                      N0.getOperand(2).getOperand(1),
7749                                      DAG.getNode(ISD::FNEG, SL, VT,
7750                                                  N1)));
7751     }
7752
7753     // fold (fsub x, (fma y, z, (fmul u, v)))
7754     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7755     if (N1.getOpcode() == PreferredFusedOpcode &&
7756         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7757       SDValue N20 = N1.getOperand(2).getOperand(0);
7758       SDValue N21 = N1.getOperand(2).getOperand(1);
7759       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7760                          DAG.getNode(ISD::FNEG, SL, VT,
7761                                      N1.getOperand(0)),
7762                          N1.getOperand(1),
7763                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7764                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7765
7766                                      N21, N0));
7767     }
7768
7769     if (UnsafeFPMath && LookThroughFPExt) {
7770       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7771       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7772       if (N0.getOpcode() == PreferredFusedOpcode) {
7773         SDValue N02 = N0.getOperand(2);
7774         if (N02.getOpcode() == ISD::FP_EXTEND) {
7775           SDValue N020 = N02.getOperand(0);
7776           if (N020.getOpcode() == ISD::FMUL)
7777             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7778                                N0.getOperand(0), N0.getOperand(1),
7779                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7780                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7781                                                        N020.getOperand(0)),
7782                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7783                                                        N020.getOperand(1)),
7784                                            DAG.getNode(ISD::FNEG, SL, VT,
7785                                                        N1)));
7786         }
7787       }
7788
7789       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7790       //   -> (fma (fpext x), (fpext y),
7791       //           (fma (fpext u), (fpext v), (fneg z)))
7792       // FIXME: This turns two single-precision and one double-precision
7793       // operation into two double-precision operations, which might not be
7794       // interesting for all targets, especially GPUs.
7795       if (N0.getOpcode() == ISD::FP_EXTEND) {
7796         SDValue N00 = N0.getOperand(0);
7797         if (N00.getOpcode() == PreferredFusedOpcode) {
7798           SDValue N002 = N00.getOperand(2);
7799           if (N002.getOpcode() == ISD::FMUL)
7800             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7801                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7802                                            N00.getOperand(0)),
7803                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7804                                            N00.getOperand(1)),
7805                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7806                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7807                                                        N002.getOperand(0)),
7808                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7809                                                        N002.getOperand(1)),
7810                                            DAG.getNode(ISD::FNEG, SL, VT,
7811                                                        N1)));
7812         }
7813       }
7814
7815       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7816       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7817       if (N1.getOpcode() == PreferredFusedOpcode &&
7818         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7819         SDValue N120 = N1.getOperand(2).getOperand(0);
7820         if (N120.getOpcode() == ISD::FMUL) {
7821           SDValue N1200 = N120.getOperand(0);
7822           SDValue N1201 = N120.getOperand(1);
7823           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7824                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7825                              N1.getOperand(1),
7826                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7827                                          DAG.getNode(ISD::FNEG, SL, VT,
7828                                              DAG.getNode(ISD::FP_EXTEND, SL,
7829                                                          VT, N1200)),
7830                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7831                                                      N1201),
7832                                          N0));
7833         }
7834       }
7835
7836       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7837       //   -> (fma (fneg (fpext y)), (fpext z),
7838       //           (fma (fneg (fpext u)), (fpext v), x))
7839       // FIXME: This turns two single-precision and one double-precision
7840       // operation into two double-precision operations, which might not be
7841       // interesting for all targets, especially GPUs.
7842       if (N1.getOpcode() == ISD::FP_EXTEND &&
7843         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7844         SDValue N100 = N1.getOperand(0).getOperand(0);
7845         SDValue N101 = N1.getOperand(0).getOperand(1);
7846         SDValue N102 = N1.getOperand(0).getOperand(2);
7847         if (N102.getOpcode() == ISD::FMUL) {
7848           SDValue N1020 = N102.getOperand(0);
7849           SDValue N1021 = N102.getOperand(1);
7850           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7851                              DAG.getNode(ISD::FNEG, SL, VT,
7852                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7853                                                      N100)),
7854                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7855                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7856                                          DAG.getNode(ISD::FNEG, SL, VT,
7857                                              DAG.getNode(ISD::FP_EXTEND, SL,
7858                                                          VT, N1020)),
7859                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7860                                                      N1021),
7861                                          N0));
7862         }
7863       }
7864     }
7865   }
7866
7867   return SDValue();
7868 }
7869
7870 SDValue DAGCombiner::visitFADD(SDNode *N) {
7871   SDValue N0 = N->getOperand(0);
7872   SDValue N1 = N->getOperand(1);
7873   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7874   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7875   EVT VT = N->getValueType(0);
7876   SDLoc DL(N);
7877   const TargetOptions &Options = DAG.getTarget().Options;
7878
7879   // fold vector ops
7880   if (VT.isVector())
7881     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7882       return FoldedVOp;
7883
7884   // fold (fadd c1, c2) -> c1 + c2
7885   if (N0CFP && N1CFP)
7886     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7887
7888   // canonicalize constant to RHS
7889   if (N0CFP && !N1CFP)
7890     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7891
7892   // fold (fadd A, (fneg B)) -> (fsub A, B)
7893   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7894       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7895     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7896                        GetNegatedExpression(N1, DAG, LegalOperations));
7897
7898   // fold (fadd (fneg A), B) -> (fsub B, A)
7899   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7900       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7901     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7902                        GetNegatedExpression(N0, DAG, LegalOperations));
7903
7904   // If 'unsafe math' is enabled, fold lots of things.
7905   if (Options.UnsafeFPMath) {
7906     // No FP constant should be created after legalization as Instruction
7907     // Selection pass has a hard time dealing with FP constants.
7908     bool AllowNewConst = (Level < AfterLegalizeDAG);
7909
7910     // fold (fadd A, 0) -> A
7911     if (N1CFP && N1CFP->isZero())
7912       return N0;
7913
7914     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7915     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7916         isa<ConstantFPSDNode>(N0.getOperand(1)))
7917       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7918                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7919
7920     // If allowed, fold (fadd (fneg x), x) -> 0.0
7921     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7922       return DAG.getConstantFP(0.0, DL, VT);
7923
7924     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7925     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7926       return DAG.getConstantFP(0.0, DL, VT);
7927
7928     // We can fold chains of FADD's of the same value into multiplications.
7929     // This transform is not safe in general because we are reducing the number
7930     // of rounding steps.
7931     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7932       if (N0.getOpcode() == ISD::FMUL) {
7933         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7934         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7935
7936         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7937         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7938           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7939                                        DAG.getConstantFP(1.0, DL, VT));
7940           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7941         }
7942
7943         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7944         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7945             N1.getOperand(0) == N1.getOperand(1) &&
7946             N0.getOperand(0) == N1.getOperand(0)) {
7947           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7948                                        DAG.getConstantFP(2.0, DL, VT));
7949           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7950         }
7951       }
7952
7953       if (N1.getOpcode() == ISD::FMUL) {
7954         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7955         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7956
7957         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7958         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7959           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7960                                        DAG.getConstantFP(1.0, DL, VT));
7961           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7962         }
7963
7964         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7965         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7966             N0.getOperand(0) == N0.getOperand(1) &&
7967             N1.getOperand(0) == N0.getOperand(0)) {
7968           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7969                                        DAG.getConstantFP(2.0, DL, VT));
7970           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7971         }
7972       }
7973
7974       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7975         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7976         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7977         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7978             (N0.getOperand(0) == N1)) {
7979           return DAG.getNode(ISD::FMUL, DL, VT,
7980                              N1, DAG.getConstantFP(3.0, DL, VT));
7981         }
7982       }
7983
7984       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7985         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7986         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7987         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7988             N1.getOperand(0) == N0) {
7989           return DAG.getNode(ISD::FMUL, DL, VT,
7990                              N0, DAG.getConstantFP(3.0, DL, VT));
7991         }
7992       }
7993
7994       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7995       if (AllowNewConst &&
7996           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7997           N0.getOperand(0) == N0.getOperand(1) &&
7998           N1.getOperand(0) == N1.getOperand(1) &&
7999           N0.getOperand(0) == N1.getOperand(0)) {
8000         return DAG.getNode(ISD::FMUL, DL, VT,
8001                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
8002       }
8003     }
8004   } // enable-unsafe-fp-math
8005
8006   // FADD -> FMA combines:
8007   SDValue Fused = visitFADDForFMACombine(N);
8008   if (Fused) {
8009     AddToWorklist(Fused.getNode());
8010     return Fused;
8011   }
8012
8013   return SDValue();
8014 }
8015
8016 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8017   SDValue N0 = N->getOperand(0);
8018   SDValue N1 = N->getOperand(1);
8019   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8020   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8021   EVT VT = N->getValueType(0);
8022   SDLoc dl(N);
8023   const TargetOptions &Options = DAG.getTarget().Options;
8024
8025   // fold vector ops
8026   if (VT.isVector())
8027     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8028       return FoldedVOp;
8029
8030   // fold (fsub c1, c2) -> c1-c2
8031   if (N0CFP && N1CFP)
8032     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8033
8034   // fold (fsub A, (fneg B)) -> (fadd A, B)
8035   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8036     return DAG.getNode(ISD::FADD, dl, VT, N0,
8037                        GetNegatedExpression(N1, DAG, LegalOperations));
8038
8039   // If 'unsafe math' is enabled, fold lots of things.
8040   if (Options.UnsafeFPMath) {
8041     // (fsub A, 0) -> A
8042     if (N1CFP && N1CFP->isZero())
8043       return N0;
8044
8045     // (fsub 0, B) -> -B
8046     if (N0CFP && N0CFP->isZero()) {
8047       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8048         return GetNegatedExpression(N1, DAG, LegalOperations);
8049       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8050         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8051     }
8052
8053     // (fsub x, x) -> 0.0
8054     if (N0 == N1)
8055       return DAG.getConstantFP(0.0f, dl, VT);
8056
8057     // (fsub x, (fadd x, y)) -> (fneg y)
8058     // (fsub x, (fadd y, x)) -> (fneg y)
8059     if (N1.getOpcode() == ISD::FADD) {
8060       SDValue N10 = N1->getOperand(0);
8061       SDValue N11 = N1->getOperand(1);
8062
8063       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8064         return GetNegatedExpression(N11, DAG, LegalOperations);
8065
8066       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8067         return GetNegatedExpression(N10, DAG, LegalOperations);
8068     }
8069   }
8070
8071   // FSUB -> FMA combines:
8072   SDValue Fused = visitFSUBForFMACombine(N);
8073   if (Fused) {
8074     AddToWorklist(Fused.getNode());
8075     return Fused;
8076   }
8077
8078   return SDValue();
8079 }
8080
8081 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8082   SDValue N0 = N->getOperand(0);
8083   SDValue N1 = N->getOperand(1);
8084   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8085   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8086   EVT VT = N->getValueType(0);
8087   SDLoc DL(N);
8088   const TargetOptions &Options = DAG.getTarget().Options;
8089
8090   // fold vector ops
8091   if (VT.isVector()) {
8092     // This just handles C1 * C2 for vectors. Other vector folds are below.
8093     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8094       return FoldedVOp;
8095   }
8096
8097   // fold (fmul c1, c2) -> c1*c2
8098   if (N0CFP && N1CFP)
8099     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8100
8101   // canonicalize constant to RHS
8102   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8103      !isConstantFPBuildVectorOrConstantFP(N1))
8104     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8105
8106   // fold (fmul A, 1.0) -> A
8107   if (N1CFP && N1CFP->isExactlyValue(1.0))
8108     return N0;
8109
8110   if (Options.UnsafeFPMath) {
8111     // fold (fmul A, 0) -> 0
8112     if (N1CFP && N1CFP->isZero())
8113       return N1;
8114
8115     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8116     if (N0.getOpcode() == ISD::FMUL) {
8117       // Fold scalars or any vector constants (not just splats).
8118       // This fold is done in general by InstCombine, but extra fmul insts
8119       // may have been generated during lowering.
8120       SDValue N00 = N0.getOperand(0);
8121       SDValue N01 = N0.getOperand(1);
8122       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8123       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8124       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8125
8126       // Check 1: Make sure that the first operand of the inner multiply is NOT
8127       // a constant. Otherwise, we may induce infinite looping.
8128       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8129         // Check 2: Make sure that the second operand of the inner multiply and
8130         // the second operand of the outer multiply are constants.
8131         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8132             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8133           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8134           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8135         }
8136       }
8137     }
8138
8139     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8140     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8141     // during an early run of DAGCombiner can prevent folding with fmuls
8142     // inserted during lowering.
8143     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8144       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8145       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8146       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8147     }
8148   }
8149
8150   // fold (fmul X, 2.0) -> (fadd X, X)
8151   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8152     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8153
8154   // fold (fmul X, -1.0) -> (fneg X)
8155   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8156     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8157       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8158
8159   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8160   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8161     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8162       // Both can be negated for free, check to see if at least one is cheaper
8163       // negated.
8164       if (LHSNeg == 2 || RHSNeg == 2)
8165         return DAG.getNode(ISD::FMUL, DL, VT,
8166                            GetNegatedExpression(N0, DAG, LegalOperations),
8167                            GetNegatedExpression(N1, DAG, LegalOperations));
8168     }
8169   }
8170
8171   return SDValue();
8172 }
8173
8174 SDValue DAGCombiner::visitFMA(SDNode *N) {
8175   SDValue N0 = N->getOperand(0);
8176   SDValue N1 = N->getOperand(1);
8177   SDValue N2 = N->getOperand(2);
8178   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8179   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8180   EVT VT = N->getValueType(0);
8181   SDLoc dl(N);
8182   const TargetOptions &Options = DAG.getTarget().Options;
8183
8184   // Constant fold FMA.
8185   if (isa<ConstantFPSDNode>(N0) &&
8186       isa<ConstantFPSDNode>(N1) &&
8187       isa<ConstantFPSDNode>(N2)) {
8188     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8189   }
8190
8191   if (Options.UnsafeFPMath) {
8192     if (N0CFP && N0CFP->isZero())
8193       return N2;
8194     if (N1CFP && N1CFP->isZero())
8195       return N2;
8196   }
8197   if (N0CFP && N0CFP->isExactlyValue(1.0))
8198     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8199   if (N1CFP && N1CFP->isExactlyValue(1.0))
8200     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8201
8202   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8203   if (N0CFP && !N1CFP)
8204     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8205
8206   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8207   if (Options.UnsafeFPMath && N1CFP &&
8208       N2.getOpcode() == ISD::FMUL &&
8209       N0 == N2.getOperand(0) &&
8210       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8211     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8212                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8213   }
8214
8215
8216   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8217   if (Options.UnsafeFPMath &&
8218       N0.getOpcode() == ISD::FMUL && N1CFP &&
8219       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8220     return DAG.getNode(ISD::FMA, dl, VT,
8221                        N0.getOperand(0),
8222                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8223                        N2);
8224   }
8225
8226   // (fma x, 1, y) -> (fadd x, y)
8227   // (fma x, -1, y) -> (fadd (fneg x), y)
8228   if (N1CFP) {
8229     if (N1CFP->isExactlyValue(1.0))
8230       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8231
8232     if (N1CFP->isExactlyValue(-1.0) &&
8233         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8234       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8235       AddToWorklist(RHSNeg.getNode());
8236       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8237     }
8238   }
8239
8240   // (fma x, c, x) -> (fmul x, (c+1))
8241   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8242     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8243                        DAG.getNode(ISD::FADD, dl, VT,
8244                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8245
8246   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8247   if (Options.UnsafeFPMath && N1CFP &&
8248       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8249     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8250                        DAG.getNode(ISD::FADD, dl, VT,
8251                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8252
8253
8254   return SDValue();
8255 }
8256
8257 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8258   SDValue N0 = N->getOperand(0);
8259   SDValue N1 = N->getOperand(1);
8260   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8261   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8262   EVT VT = N->getValueType(0);
8263   SDLoc DL(N);
8264   const TargetOptions &Options = DAG.getTarget().Options;
8265
8266   // fold vector ops
8267   if (VT.isVector())
8268     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8269       return FoldedVOp;
8270
8271   // fold (fdiv c1, c2) -> c1/c2
8272   if (N0CFP && N1CFP)
8273     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8274
8275   if (Options.UnsafeFPMath) {
8276     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8277     if (N1CFP) {
8278       // Compute the reciprocal 1.0 / c2.
8279       APFloat N1APF = N1CFP->getValueAPF();
8280       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8281       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8282       // Only do the transform if the reciprocal is a legal fp immediate that
8283       // isn't too nasty (eg NaN, denormal, ...).
8284       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8285           (!LegalOperations ||
8286            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8287            // backend)... we should handle this gracefully after Legalize.
8288            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8289            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8290            TLI.isFPImmLegal(Recip, VT)))
8291         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8292                            DAG.getConstantFP(Recip, DL, VT));
8293     }
8294
8295     // If this FDIV is part of a reciprocal square root, it may be folded
8296     // into a target-specific square root estimate instruction.
8297     if (N1.getOpcode() == ISD::FSQRT) {
8298       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8299         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8300       }
8301     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8302                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8303       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8304         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8305         AddToWorklist(RV.getNode());
8306         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8307       }
8308     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8309                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8310       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8311         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8312         AddToWorklist(RV.getNode());
8313         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8314       }
8315     } else if (N1.getOpcode() == ISD::FMUL) {
8316       // Look through an FMUL. Even though this won't remove the FDIV directly,
8317       // it's still worthwhile to get rid of the FSQRT if possible.
8318       SDValue SqrtOp;
8319       SDValue OtherOp;
8320       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8321         SqrtOp = N1.getOperand(0);
8322         OtherOp = N1.getOperand(1);
8323       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8324         SqrtOp = N1.getOperand(1);
8325         OtherOp = N1.getOperand(0);
8326       }
8327       if (SqrtOp.getNode()) {
8328         // We found a FSQRT, so try to make this fold:
8329         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8330         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8331           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8332           AddToWorklist(RV.getNode());
8333           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8334         }
8335       }
8336     }
8337
8338     // Fold into a reciprocal estimate and multiply instead of a real divide.
8339     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8340       AddToWorklist(RV.getNode());
8341       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8342     }
8343   }
8344
8345   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8346   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8347     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8348       // Both can be negated for free, check to see if at least one is cheaper
8349       // negated.
8350       if (LHSNeg == 2 || RHSNeg == 2)
8351         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8352                            GetNegatedExpression(N0, DAG, LegalOperations),
8353                            GetNegatedExpression(N1, DAG, LegalOperations));
8354     }
8355   }
8356
8357   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8358   // reciprocal.
8359   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8360   // Notice that this is not always beneficial. One reason is different target
8361   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8362   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8363   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8364   if (Options.UnsafeFPMath) {
8365     // Skip if current node is a reciprocal.
8366     if (N0CFP && N0CFP->isExactlyValue(1.0))
8367       return SDValue();
8368
8369     SmallVector<SDNode *, 4> Users;
8370     // Find all FDIV users of the same divisor.
8371     for (auto *U : N1->uses()) {
8372       if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8373         Users.push_back(U);
8374     }
8375
8376     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8377       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8378       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8379
8380       // Dividend / Divisor -> Dividend * Reciprocal
8381       for (auto *U : Users) {
8382         SDValue Dividend = U->getOperand(0);
8383         if (Dividend != FPOne) {
8384           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8385                                         Reciprocal);
8386           DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8387         }
8388       }
8389       return SDValue();
8390     }
8391   }
8392
8393   return SDValue();
8394 }
8395
8396 SDValue DAGCombiner::visitFREM(SDNode *N) {
8397   SDValue N0 = N->getOperand(0);
8398   SDValue N1 = N->getOperand(1);
8399   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8400   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8401   EVT VT = N->getValueType(0);
8402
8403   // fold (frem c1, c2) -> fmod(c1,c2)
8404   if (N0CFP && N1CFP)
8405     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8406
8407   return SDValue();
8408 }
8409
8410 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8411   if (DAG.getTarget().Options.UnsafeFPMath &&
8412       !TLI.isFsqrtCheap()) {
8413     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8414     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8415       EVT VT = RV.getValueType();
8416       SDLoc DL(N);
8417       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8418       AddToWorklist(RV.getNode());
8419
8420       // Unfortunately, RV is now NaN if the input was exactly 0.
8421       // Select out this case and force the answer to 0.
8422       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8423       SDValue ZeroCmp =
8424         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8425                      N->getOperand(0), Zero, ISD::SETEQ);
8426       AddToWorklist(ZeroCmp.getNode());
8427       AddToWorklist(RV.getNode());
8428
8429       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8430                        DL, VT, ZeroCmp, Zero, RV);
8431       return RV;
8432     }
8433   }
8434   return SDValue();
8435 }
8436
8437 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8438   SDValue N0 = N->getOperand(0);
8439   SDValue N1 = N->getOperand(1);
8440   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8441   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8442   EVT VT = N->getValueType(0);
8443
8444   if (N0CFP && N1CFP)  // Constant fold
8445     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8446
8447   if (N1CFP) {
8448     const APFloat& V = N1CFP->getValueAPF();
8449     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8450     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8451     if (!V.isNegative()) {
8452       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8453         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8454     } else {
8455       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8456         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8457                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8458     }
8459   }
8460
8461   // copysign(fabs(x), y) -> copysign(x, y)
8462   // copysign(fneg(x), y) -> copysign(x, y)
8463   // copysign(copysign(x,z), y) -> copysign(x, y)
8464   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8465       N0.getOpcode() == ISD::FCOPYSIGN)
8466     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8467                        N0.getOperand(0), N1);
8468
8469   // copysign(x, abs(y)) -> abs(x)
8470   if (N1.getOpcode() == ISD::FABS)
8471     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8472
8473   // copysign(x, copysign(y,z)) -> copysign(x, z)
8474   if (N1.getOpcode() == ISD::FCOPYSIGN)
8475     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8476                        N0, N1.getOperand(1));
8477
8478   // copysign(x, fp_extend(y)) -> copysign(x, y)
8479   // copysign(x, fp_round(y)) -> copysign(x, y)
8480   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8481     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8482                        N0, N1.getOperand(0));
8483
8484   return SDValue();
8485 }
8486
8487 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8488   SDValue N0 = N->getOperand(0);
8489   EVT VT = N->getValueType(0);
8490   EVT OpVT = N0.getValueType();
8491
8492   // fold (sint_to_fp c1) -> c1fp
8493   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8494       // ...but only if the target supports immediate floating-point values
8495       (!LegalOperations ||
8496        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8497     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8498
8499   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8500   // but UINT_TO_FP is legal on this target, try to convert.
8501   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8502       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8503     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8504     if (DAG.SignBitIsZero(N0))
8505       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8506   }
8507
8508   // The next optimizations are desirable only if SELECT_CC can be lowered.
8509   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8510     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8511     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8512         !VT.isVector() &&
8513         (!LegalOperations ||
8514          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8515       SDLoc DL(N);
8516       SDValue Ops[] =
8517         { N0.getOperand(0), N0.getOperand(1),
8518           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8519           N0.getOperand(2) };
8520       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8521     }
8522
8523     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8524     //      (select_cc x, y, 1.0, 0.0,, cc)
8525     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8526         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8527         (!LegalOperations ||
8528          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8529       SDLoc DL(N);
8530       SDValue Ops[] =
8531         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8532           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8533           N0.getOperand(0).getOperand(2) };
8534       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8535     }
8536   }
8537
8538   return SDValue();
8539 }
8540
8541 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8542   SDValue N0 = N->getOperand(0);
8543   EVT VT = N->getValueType(0);
8544   EVT OpVT = N0.getValueType();
8545
8546   // fold (uint_to_fp c1) -> c1fp
8547   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8548       // ...but only if the target supports immediate floating-point values
8549       (!LegalOperations ||
8550        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8551     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8552
8553   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8554   // but SINT_TO_FP is legal on this target, try to convert.
8555   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8556       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8557     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8558     if (DAG.SignBitIsZero(N0))
8559       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8560   }
8561
8562   // The next optimizations are desirable only if SELECT_CC can be lowered.
8563   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8564     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8565
8566     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8567         (!LegalOperations ||
8568          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8569       SDLoc DL(N);
8570       SDValue Ops[] =
8571         { N0.getOperand(0), N0.getOperand(1),
8572           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8573           N0.getOperand(2) };
8574       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8575     }
8576   }
8577
8578   return SDValue();
8579 }
8580
8581 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8582 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8583   SDValue N0 = N->getOperand(0);
8584   EVT VT = N->getValueType(0);
8585
8586   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8587     return SDValue();
8588
8589   SDValue Src = N0.getOperand(0);
8590   EVT SrcVT = Src.getValueType();
8591   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8592   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8593
8594   // We can safely assume the conversion won't overflow the output range,
8595   // because (for example) (uint8_t)18293.f is undefined behavior.
8596
8597   // Since we can assume the conversion won't overflow, our decision as to
8598   // whether the input will fit in the float should depend on the minimum
8599   // of the input range and output range.
8600
8601   // This means this is also safe for a signed input and unsigned output, since
8602   // a negative input would lead to undefined behavior.
8603   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8604   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8605   unsigned ActualSize = std::min(InputSize, OutputSize);
8606   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8607
8608   // We can only fold away the float conversion if the input range can be
8609   // represented exactly in the float range.
8610   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8611     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8612       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8613                                                        : ISD::ZERO_EXTEND;
8614       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8615     }
8616     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8617       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8618     if (SrcVT == VT)
8619       return Src;
8620     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8621   }
8622   return SDValue();
8623 }
8624
8625 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8626   SDValue N0 = N->getOperand(0);
8627   EVT VT = N->getValueType(0);
8628
8629   // fold (fp_to_sint c1fp) -> c1
8630   if (isConstantFPBuildVectorOrConstantFP(N0))
8631     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8632
8633   return FoldIntToFPToInt(N, DAG);
8634 }
8635
8636 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8637   SDValue N0 = N->getOperand(0);
8638   EVT VT = N->getValueType(0);
8639
8640   // fold (fp_to_uint c1fp) -> c1
8641   if (isConstantFPBuildVectorOrConstantFP(N0))
8642     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8643
8644   return FoldIntToFPToInt(N, DAG);
8645 }
8646
8647 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8648   SDValue N0 = N->getOperand(0);
8649   SDValue N1 = N->getOperand(1);
8650   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8651   EVT VT = N->getValueType(0);
8652
8653   // fold (fp_round c1fp) -> c1fp
8654   if (N0CFP)
8655     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8656
8657   // fold (fp_round (fp_extend x)) -> x
8658   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8659     return N0.getOperand(0);
8660
8661   // fold (fp_round (fp_round x)) -> (fp_round x)
8662   if (N0.getOpcode() == ISD::FP_ROUND) {
8663     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8664     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8665     // If the first fp_round isn't a value preserving truncation, it might
8666     // introduce a tie in the second fp_round, that wouldn't occur in the
8667     // single-step fp_round we want to fold to.
8668     // In other words, double rounding isn't the same as rounding.
8669     // Also, this is a value preserving truncation iff both fp_round's are.
8670     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8671       SDLoc DL(N);
8672       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8673                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8674     }
8675   }
8676
8677   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8678   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8679     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8680                               N0.getOperand(0), N1);
8681     AddToWorklist(Tmp.getNode());
8682     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8683                        Tmp, N0.getOperand(1));
8684   }
8685
8686   return SDValue();
8687 }
8688
8689 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8690   SDValue N0 = N->getOperand(0);
8691   EVT VT = N->getValueType(0);
8692   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8693   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8694
8695   // fold (fp_round_inreg c1fp) -> c1fp
8696   if (N0CFP && isTypeLegal(EVT)) {
8697     SDLoc DL(N);
8698     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8699     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8700   }
8701
8702   return SDValue();
8703 }
8704
8705 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8706   SDValue N0 = N->getOperand(0);
8707   EVT VT = N->getValueType(0);
8708
8709   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8710   if (N->hasOneUse() &&
8711       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8712     return SDValue();
8713
8714   // fold (fp_extend c1fp) -> c1fp
8715   if (isConstantFPBuildVectorOrConstantFP(N0))
8716     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8717
8718   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8719   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8720       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8721     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8722
8723   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8724   // value of X.
8725   if (N0.getOpcode() == ISD::FP_ROUND
8726       && N0.getNode()->getConstantOperandVal(1) == 1) {
8727     SDValue In = N0.getOperand(0);
8728     if (In.getValueType() == VT) return In;
8729     if (VT.bitsLT(In.getValueType()))
8730       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8731                          In, N0.getOperand(1));
8732     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8733   }
8734
8735   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8736   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8737        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8738     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8739     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8740                                      LN0->getChain(),
8741                                      LN0->getBasePtr(), N0.getValueType(),
8742                                      LN0->getMemOperand());
8743     CombineTo(N, ExtLoad);
8744     CombineTo(N0.getNode(),
8745               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8746                           N0.getValueType(), ExtLoad,
8747                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8748               ExtLoad.getValue(1));
8749     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8750   }
8751
8752   return SDValue();
8753 }
8754
8755 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8756   SDValue N0 = N->getOperand(0);
8757   EVT VT = N->getValueType(0);
8758
8759   // fold (fceil c1) -> fceil(c1)
8760   if (isConstantFPBuildVectorOrConstantFP(N0))
8761     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8762
8763   return SDValue();
8764 }
8765
8766 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8767   SDValue N0 = N->getOperand(0);
8768   EVT VT = N->getValueType(0);
8769
8770   // fold (ftrunc c1) -> ftrunc(c1)
8771   if (isConstantFPBuildVectorOrConstantFP(N0))
8772     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8773
8774   return SDValue();
8775 }
8776
8777 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8778   SDValue N0 = N->getOperand(0);
8779   EVT VT = N->getValueType(0);
8780
8781   // fold (ffloor c1) -> ffloor(c1)
8782   if (isConstantFPBuildVectorOrConstantFP(N0))
8783     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8784
8785   return SDValue();
8786 }
8787
8788 // FIXME: FNEG and FABS have a lot in common; refactor.
8789 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8790   SDValue N0 = N->getOperand(0);
8791   EVT VT = N->getValueType(0);
8792
8793   // Constant fold FNEG.
8794   if (isConstantFPBuildVectorOrConstantFP(N0))
8795     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8796
8797   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8798                          &DAG.getTarget().Options))
8799     return GetNegatedExpression(N0, DAG, LegalOperations);
8800
8801   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8802   // constant pool values.
8803   if (!TLI.isFNegFree(VT) &&
8804       N0.getOpcode() == ISD::BITCAST &&
8805       N0.getNode()->hasOneUse()) {
8806     SDValue Int = N0.getOperand(0);
8807     EVT IntVT = Int.getValueType();
8808     if (IntVT.isInteger() && !IntVT.isVector()) {
8809       APInt SignMask;
8810       if (N0.getValueType().isVector()) {
8811         // For a vector, get a mask such as 0x80... per scalar element
8812         // and splat it.
8813         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8814         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8815       } else {
8816         // For a scalar, just generate 0x80...
8817         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8818       }
8819       SDLoc DL0(N0);
8820       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8821                         DAG.getConstant(SignMask, DL0, IntVT));
8822       AddToWorklist(Int.getNode());
8823       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8824     }
8825   }
8826
8827   // (fneg (fmul c, x)) -> (fmul -c, x)
8828   if (N0.getOpcode() == ISD::FMUL &&
8829       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8830     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8831     if (CFP1) {
8832       APFloat CVal = CFP1->getValueAPF();
8833       CVal.changeSign();
8834       if (Level >= AfterLegalizeDAG &&
8835           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8836            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8837         return DAG.getNode(
8838             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8839             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8840     }
8841   }
8842
8843   return SDValue();
8844 }
8845
8846 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8847   SDValue N0 = N->getOperand(0);
8848   SDValue N1 = N->getOperand(1);
8849   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8850   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8851
8852   if (N0CFP && N1CFP) {
8853     const APFloat &C0 = N0CFP->getValueAPF();
8854     const APFloat &C1 = N1CFP->getValueAPF();
8855     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8856   }
8857
8858   if (N0CFP) {
8859     EVT VT = N->getValueType(0);
8860     // Canonicalize to constant on RHS.
8861     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8862   }
8863
8864   return SDValue();
8865 }
8866
8867 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8868   SDValue N0 = N->getOperand(0);
8869   SDValue N1 = N->getOperand(1);
8870   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8871   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8872
8873   if (N0CFP && N1CFP) {
8874     const APFloat &C0 = N0CFP->getValueAPF();
8875     const APFloat &C1 = N1CFP->getValueAPF();
8876     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8877   }
8878
8879   if (N0CFP) {
8880     EVT VT = N->getValueType(0);
8881     // Canonicalize to constant on RHS.
8882     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8883   }
8884
8885   return SDValue();
8886 }
8887
8888 SDValue DAGCombiner::visitFABS(SDNode *N) {
8889   SDValue N0 = N->getOperand(0);
8890   EVT VT = N->getValueType(0);
8891
8892   // fold (fabs c1) -> fabs(c1)
8893   if (isConstantFPBuildVectorOrConstantFP(N0))
8894     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8895
8896   // fold (fabs (fabs x)) -> (fabs x)
8897   if (N0.getOpcode() == ISD::FABS)
8898     return N->getOperand(0);
8899
8900   // fold (fabs (fneg x)) -> (fabs x)
8901   // fold (fabs (fcopysign x, y)) -> (fabs x)
8902   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8903     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8904
8905   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8906   // constant pool values.
8907   if (!TLI.isFAbsFree(VT) &&
8908       N0.getOpcode() == ISD::BITCAST &&
8909       N0.getNode()->hasOneUse()) {
8910     SDValue Int = N0.getOperand(0);
8911     EVT IntVT = Int.getValueType();
8912     if (IntVT.isInteger() && !IntVT.isVector()) {
8913       APInt SignMask;
8914       if (N0.getValueType().isVector()) {
8915         // For a vector, get a mask such as 0x7f... per scalar element
8916         // and splat it.
8917         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8918         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8919       } else {
8920         // For a scalar, just generate 0x7f...
8921         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8922       }
8923       SDLoc DL(N0);
8924       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8925                         DAG.getConstant(SignMask, DL, IntVT));
8926       AddToWorklist(Int.getNode());
8927       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8928     }
8929   }
8930
8931   return SDValue();
8932 }
8933
8934 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8935   SDValue Chain = N->getOperand(0);
8936   SDValue N1 = N->getOperand(1);
8937   SDValue N2 = N->getOperand(2);
8938
8939   // If N is a constant we could fold this into a fallthrough or unconditional
8940   // branch. However that doesn't happen very often in normal code, because
8941   // Instcombine/SimplifyCFG should have handled the available opportunities.
8942   // If we did this folding here, it would be necessary to update the
8943   // MachineBasicBlock CFG, which is awkward.
8944
8945   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8946   // on the target.
8947   if (N1.getOpcode() == ISD::SETCC &&
8948       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8949                                    N1.getOperand(0).getValueType())) {
8950     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8951                        Chain, N1.getOperand(2),
8952                        N1.getOperand(0), N1.getOperand(1), N2);
8953   }
8954
8955   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8956       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8957        (N1.getOperand(0).hasOneUse() &&
8958         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8959     SDNode *Trunc = nullptr;
8960     if (N1.getOpcode() == ISD::TRUNCATE) {
8961       // Look pass the truncate.
8962       Trunc = N1.getNode();
8963       N1 = N1.getOperand(0);
8964     }
8965
8966     // Match this pattern so that we can generate simpler code:
8967     //
8968     //   %a = ...
8969     //   %b = and i32 %a, 2
8970     //   %c = srl i32 %b, 1
8971     //   brcond i32 %c ...
8972     //
8973     // into
8974     //
8975     //   %a = ...
8976     //   %b = and i32 %a, 2
8977     //   %c = setcc eq %b, 0
8978     //   brcond %c ...
8979     //
8980     // This applies only when the AND constant value has one bit set and the
8981     // SRL constant is equal to the log2 of the AND constant. The back-end is
8982     // smart enough to convert the result into a TEST/JMP sequence.
8983     SDValue Op0 = N1.getOperand(0);
8984     SDValue Op1 = N1.getOperand(1);
8985
8986     if (Op0.getOpcode() == ISD::AND &&
8987         Op1.getOpcode() == ISD::Constant) {
8988       SDValue AndOp1 = Op0.getOperand(1);
8989
8990       if (AndOp1.getOpcode() == ISD::Constant) {
8991         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8992
8993         if (AndConst.isPowerOf2() &&
8994             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8995           SDLoc DL(N);
8996           SDValue SetCC =
8997             DAG.getSetCC(DL,
8998                          getSetCCResultType(Op0.getValueType()),
8999                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9000                          ISD::SETNE);
9001
9002           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9003                                           MVT::Other, Chain, SetCC, N2);
9004           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9005           // will convert it back to (X & C1) >> C2.
9006           CombineTo(N, NewBRCond, false);
9007           // Truncate is dead.
9008           if (Trunc)
9009             deleteAndRecombine(Trunc);
9010           // Replace the uses of SRL with SETCC
9011           WorklistRemover DeadNodes(*this);
9012           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9013           deleteAndRecombine(N1.getNode());
9014           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9015         }
9016       }
9017     }
9018
9019     if (Trunc)
9020       // Restore N1 if the above transformation doesn't match.
9021       N1 = N->getOperand(1);
9022   }
9023
9024   // Transform br(xor(x, y)) -> br(x != y)
9025   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9026   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9027     SDNode *TheXor = N1.getNode();
9028     SDValue Op0 = TheXor->getOperand(0);
9029     SDValue Op1 = TheXor->getOperand(1);
9030     if (Op0.getOpcode() == Op1.getOpcode()) {
9031       // Avoid missing important xor optimizations.
9032       SDValue Tmp = visitXOR(TheXor);
9033       if (Tmp.getNode()) {
9034         if (Tmp.getNode() != TheXor) {
9035           DEBUG(dbgs() << "\nReplacing.8 ";
9036                 TheXor->dump(&DAG);
9037                 dbgs() << "\nWith: ";
9038                 Tmp.getNode()->dump(&DAG);
9039                 dbgs() << '\n');
9040           WorklistRemover DeadNodes(*this);
9041           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9042           deleteAndRecombine(TheXor);
9043           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9044                              MVT::Other, Chain, Tmp, N2);
9045         }
9046
9047         // visitXOR has changed XOR's operands or replaced the XOR completely,
9048         // bail out.
9049         return SDValue(N, 0);
9050       }
9051     }
9052
9053     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9054       bool Equal = false;
9055       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9056           Op0.getOpcode() == ISD::XOR) {
9057         TheXor = Op0.getNode();
9058         Equal = true;
9059       }
9060
9061       EVT SetCCVT = N1.getValueType();
9062       if (LegalTypes)
9063         SetCCVT = getSetCCResultType(SetCCVT);
9064       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9065                                    SetCCVT,
9066                                    Op0, Op1,
9067                                    Equal ? ISD::SETEQ : ISD::SETNE);
9068       // Replace the uses of XOR with SETCC
9069       WorklistRemover DeadNodes(*this);
9070       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9071       deleteAndRecombine(N1.getNode());
9072       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9073                          MVT::Other, Chain, SetCC, N2);
9074     }
9075   }
9076
9077   return SDValue();
9078 }
9079
9080 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9081 //
9082 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9083   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9084   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9085
9086   // If N is a constant we could fold this into a fallthrough or unconditional
9087   // branch. However that doesn't happen very often in normal code, because
9088   // Instcombine/SimplifyCFG should have handled the available opportunities.
9089   // If we did this folding here, it would be necessary to update the
9090   // MachineBasicBlock CFG, which is awkward.
9091
9092   // Use SimplifySetCC to simplify SETCC's.
9093   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9094                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9095                                false);
9096   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9097
9098   // fold to a simpler setcc
9099   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9100     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9101                        N->getOperand(0), Simp.getOperand(2),
9102                        Simp.getOperand(0), Simp.getOperand(1),
9103                        N->getOperand(4));
9104
9105   return SDValue();
9106 }
9107
9108 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9109 /// and that N may be folded in the load / store addressing mode.
9110 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9111                                     SelectionDAG &DAG,
9112                                     const TargetLowering &TLI) {
9113   EVT VT;
9114   unsigned AS;
9115
9116   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9117     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9118       return false;
9119     VT = LD->getMemoryVT();
9120     AS = LD->getAddressSpace();
9121   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9122     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9123       return false;
9124     VT = ST->getMemoryVT();
9125     AS = ST->getAddressSpace();
9126   } else
9127     return false;
9128
9129   TargetLowering::AddrMode AM;
9130   if (N->getOpcode() == ISD::ADD) {
9131     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9132     if (Offset)
9133       // [reg +/- imm]
9134       AM.BaseOffs = Offset->getSExtValue();
9135     else
9136       // [reg +/- reg]
9137       AM.Scale = 1;
9138   } else if (N->getOpcode() == ISD::SUB) {
9139     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9140     if (Offset)
9141       // [reg +/- imm]
9142       AM.BaseOffs = -Offset->getSExtValue();
9143     else
9144       // [reg +/- reg]
9145       AM.Scale = 1;
9146   } else
9147     return false;
9148
9149   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()), AS);
9150 }
9151
9152 /// Try turning a load/store into a pre-indexed load/store when the base
9153 /// pointer is an add or subtract and it has other uses besides the load/store.
9154 /// After the transformation, the new indexed load/store has effectively folded
9155 /// the add/subtract in and all of its other uses are redirected to the
9156 /// new load/store.
9157 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9158   if (Level < AfterLegalizeDAG)
9159     return false;
9160
9161   bool isLoad = true;
9162   SDValue Ptr;
9163   EVT VT;
9164   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9165     if (LD->isIndexed())
9166       return false;
9167     VT = LD->getMemoryVT();
9168     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9169         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9170       return false;
9171     Ptr = LD->getBasePtr();
9172   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9173     if (ST->isIndexed())
9174       return false;
9175     VT = ST->getMemoryVT();
9176     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9177         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9178       return false;
9179     Ptr = ST->getBasePtr();
9180     isLoad = false;
9181   } else {
9182     return false;
9183   }
9184
9185   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9186   // out.  There is no reason to make this a preinc/predec.
9187   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9188       Ptr.getNode()->hasOneUse())
9189     return false;
9190
9191   // Ask the target to do addressing mode selection.
9192   SDValue BasePtr;
9193   SDValue Offset;
9194   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9195   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9196     return false;
9197
9198   // Backends without true r+i pre-indexed forms may need to pass a
9199   // constant base with a variable offset so that constant coercion
9200   // will work with the patterns in canonical form.
9201   bool Swapped = false;
9202   if (isa<ConstantSDNode>(BasePtr)) {
9203     std::swap(BasePtr, Offset);
9204     Swapped = true;
9205   }
9206
9207   // Don't create a indexed load / store with zero offset.
9208   if (isNullConstant(Offset))
9209     return false;
9210
9211   // Try turning it into a pre-indexed load / store except when:
9212   // 1) The new base ptr is a frame index.
9213   // 2) If N is a store and the new base ptr is either the same as or is a
9214   //    predecessor of the value being stored.
9215   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9216   //    that would create a cycle.
9217   // 4) All uses are load / store ops that use it as old base ptr.
9218
9219   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9220   // (plus the implicit offset) to a register to preinc anyway.
9221   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9222     return false;
9223
9224   // Check #2.
9225   if (!isLoad) {
9226     SDValue Val = cast<StoreSDNode>(N)->getValue();
9227     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9228       return false;
9229   }
9230
9231   // If the offset is a constant, there may be other adds of constants that
9232   // can be folded with this one. We should do this to avoid having to keep
9233   // a copy of the original base pointer.
9234   SmallVector<SDNode *, 16> OtherUses;
9235   if (isa<ConstantSDNode>(Offset))
9236     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9237                               UE = BasePtr.getNode()->use_end();
9238          UI != UE; ++UI) {
9239       SDUse &Use = UI.getUse();
9240       // Skip the use that is Ptr and uses of other results from BasePtr's
9241       // node (important for nodes that return multiple results).
9242       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9243         continue;
9244
9245       if (Use.getUser()->isPredecessorOf(N))
9246         continue;
9247
9248       if (Use.getUser()->getOpcode() != ISD::ADD &&
9249           Use.getUser()->getOpcode() != ISD::SUB) {
9250         OtherUses.clear();
9251         break;
9252       }
9253
9254       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9255       if (!isa<ConstantSDNode>(Op1)) {
9256         OtherUses.clear();
9257         break;
9258       }
9259
9260       // FIXME: In some cases, we can be smarter about this.
9261       if (Op1.getValueType() != Offset.getValueType()) {
9262         OtherUses.clear();
9263         break;
9264       }
9265
9266       OtherUses.push_back(Use.getUser());
9267     }
9268
9269   if (Swapped)
9270     std::swap(BasePtr, Offset);
9271
9272   // Now check for #3 and #4.
9273   bool RealUse = false;
9274
9275   // Caches for hasPredecessorHelper
9276   SmallPtrSet<const SDNode *, 32> Visited;
9277   SmallVector<const SDNode *, 16> Worklist;
9278
9279   for (SDNode *Use : Ptr.getNode()->uses()) {
9280     if (Use == N)
9281       continue;
9282     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9283       return false;
9284
9285     // If Ptr may be folded in addressing mode of other use, then it's
9286     // not profitable to do this transformation.
9287     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9288       RealUse = true;
9289   }
9290
9291   if (!RealUse)
9292     return false;
9293
9294   SDValue Result;
9295   if (isLoad)
9296     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9297                                 BasePtr, Offset, AM);
9298   else
9299     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9300                                  BasePtr, Offset, AM);
9301   ++PreIndexedNodes;
9302   ++NodesCombined;
9303   DEBUG(dbgs() << "\nReplacing.4 ";
9304         N->dump(&DAG);
9305         dbgs() << "\nWith: ";
9306         Result.getNode()->dump(&DAG);
9307         dbgs() << '\n');
9308   WorklistRemover DeadNodes(*this);
9309   if (isLoad) {
9310     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9311     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9312   } else {
9313     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9314   }
9315
9316   // Finally, since the node is now dead, remove it from the graph.
9317   deleteAndRecombine(N);
9318
9319   if (Swapped)
9320     std::swap(BasePtr, Offset);
9321
9322   // Replace other uses of BasePtr that can be updated to use Ptr
9323   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9324     unsigned OffsetIdx = 1;
9325     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9326       OffsetIdx = 0;
9327     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9328            BasePtr.getNode() && "Expected BasePtr operand");
9329
9330     // We need to replace ptr0 in the following expression:
9331     //   x0 * offset0 + y0 * ptr0 = t0
9332     // knowing that
9333     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9334     //
9335     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9336     // indexed load/store and the expresion that needs to be re-written.
9337     //
9338     // Therefore, we have:
9339     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9340
9341     ConstantSDNode *CN =
9342       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9343     int X0, X1, Y0, Y1;
9344     APInt Offset0 = CN->getAPIntValue();
9345     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9346
9347     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9348     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9349     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9350     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9351
9352     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9353
9354     APInt CNV = Offset0;
9355     if (X0 < 0) CNV = -CNV;
9356     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9357     else CNV = CNV - Offset1;
9358
9359     SDLoc DL(OtherUses[i]);
9360
9361     // We can now generate the new expression.
9362     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9363     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9364
9365     SDValue NewUse = DAG.getNode(Opcode,
9366                                  DL,
9367                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9368     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9369     deleteAndRecombine(OtherUses[i]);
9370   }
9371
9372   // Replace the uses of Ptr with uses of the updated base value.
9373   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9374   deleteAndRecombine(Ptr.getNode());
9375
9376   return true;
9377 }
9378
9379 /// Try to combine a load/store with a add/sub of the base pointer node into a
9380 /// post-indexed load/store. The transformation folded the add/subtract into the
9381 /// new indexed load/store effectively and all of its uses are redirected to the
9382 /// new load/store.
9383 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9384   if (Level < AfterLegalizeDAG)
9385     return false;
9386
9387   bool isLoad = true;
9388   SDValue Ptr;
9389   EVT VT;
9390   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9391     if (LD->isIndexed())
9392       return false;
9393     VT = LD->getMemoryVT();
9394     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9395         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9396       return false;
9397     Ptr = LD->getBasePtr();
9398   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9399     if (ST->isIndexed())
9400       return false;
9401     VT = ST->getMemoryVT();
9402     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9403         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9404       return false;
9405     Ptr = ST->getBasePtr();
9406     isLoad = false;
9407   } else {
9408     return false;
9409   }
9410
9411   if (Ptr.getNode()->hasOneUse())
9412     return false;
9413
9414   for (SDNode *Op : Ptr.getNode()->uses()) {
9415     if (Op == N ||
9416         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9417       continue;
9418
9419     SDValue BasePtr;
9420     SDValue Offset;
9421     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9422     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9423       // Don't create a indexed load / store with zero offset.
9424       if (isNullConstant(Offset))
9425         continue;
9426
9427       // Try turning it into a post-indexed load / store except when
9428       // 1) All uses are load / store ops that use it as base ptr (and
9429       //    it may be folded as addressing mmode).
9430       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9431       //    nor a successor of N. Otherwise, if Op is folded that would
9432       //    create a cycle.
9433
9434       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9435         continue;
9436
9437       // Check for #1.
9438       bool TryNext = false;
9439       for (SDNode *Use : BasePtr.getNode()->uses()) {
9440         if (Use == Ptr.getNode())
9441           continue;
9442
9443         // If all the uses are load / store addresses, then don't do the
9444         // transformation.
9445         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9446           bool RealUse = false;
9447           for (SDNode *UseUse : Use->uses()) {
9448             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9449               RealUse = true;
9450           }
9451
9452           if (!RealUse) {
9453             TryNext = true;
9454             break;
9455           }
9456         }
9457       }
9458
9459       if (TryNext)
9460         continue;
9461
9462       // Check for #2
9463       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9464         SDValue Result = isLoad
9465           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9466                                BasePtr, Offset, AM)
9467           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9468                                 BasePtr, Offset, AM);
9469         ++PostIndexedNodes;
9470         ++NodesCombined;
9471         DEBUG(dbgs() << "\nReplacing.5 ";
9472               N->dump(&DAG);
9473               dbgs() << "\nWith: ";
9474               Result.getNode()->dump(&DAG);
9475               dbgs() << '\n');
9476         WorklistRemover DeadNodes(*this);
9477         if (isLoad) {
9478           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9479           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9480         } else {
9481           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9482         }
9483
9484         // Finally, since the node is now dead, remove it from the graph.
9485         deleteAndRecombine(N);
9486
9487         // Replace the uses of Use with uses of the updated base value.
9488         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9489                                       Result.getValue(isLoad ? 1 : 0));
9490         deleteAndRecombine(Op);
9491         return true;
9492       }
9493     }
9494   }
9495
9496   return false;
9497 }
9498
9499 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9500 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9501   ISD::MemIndexedMode AM = LD->getAddressingMode();
9502   assert(AM != ISD::UNINDEXED);
9503   SDValue BP = LD->getOperand(1);
9504   SDValue Inc = LD->getOperand(2);
9505
9506   // Some backends use TargetConstants for load offsets, but don't expect
9507   // TargetConstants in general ADD nodes. We can convert these constants into
9508   // regular Constants (if the constant is not opaque).
9509   assert((Inc.getOpcode() != ISD::TargetConstant ||
9510           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9511          "Cannot split out indexing using opaque target constants");
9512   if (Inc.getOpcode() == ISD::TargetConstant) {
9513     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9514     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9515                           ConstInc->getValueType(0));
9516   }
9517
9518   unsigned Opc =
9519       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9520   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9521 }
9522
9523 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9524   LoadSDNode *LD  = cast<LoadSDNode>(N);
9525   SDValue Chain = LD->getChain();
9526   SDValue Ptr   = LD->getBasePtr();
9527
9528   // If load is not volatile and there are no uses of the loaded value (and
9529   // the updated indexed value in case of indexed loads), change uses of the
9530   // chain value into uses of the chain input (i.e. delete the dead load).
9531   if (!LD->isVolatile()) {
9532     if (N->getValueType(1) == MVT::Other) {
9533       // Unindexed loads.
9534       if (!N->hasAnyUseOfValue(0)) {
9535         // It's not safe to use the two value CombineTo variant here. e.g.
9536         // v1, chain2 = load chain1, loc
9537         // v2, chain3 = load chain2, loc
9538         // v3         = add v2, c
9539         // Now we replace use of chain2 with chain1.  This makes the second load
9540         // isomorphic to the one we are deleting, and thus makes this load live.
9541         DEBUG(dbgs() << "\nReplacing.6 ";
9542               N->dump(&DAG);
9543               dbgs() << "\nWith chain: ";
9544               Chain.getNode()->dump(&DAG);
9545               dbgs() << "\n");
9546         WorklistRemover DeadNodes(*this);
9547         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9548
9549         if (N->use_empty())
9550           deleteAndRecombine(N);
9551
9552         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9553       }
9554     } else {
9555       // Indexed loads.
9556       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9557
9558       // If this load has an opaque TargetConstant offset, then we cannot split
9559       // the indexing into an add/sub directly (that TargetConstant may not be
9560       // valid for a different type of node, and we cannot convert an opaque
9561       // target constant into a regular constant).
9562       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9563                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9564
9565       if (!N->hasAnyUseOfValue(0) &&
9566           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9567         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9568         SDValue Index;
9569         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9570           Index = SplitIndexingFromLoad(LD);
9571           // Try to fold the base pointer arithmetic into subsequent loads and
9572           // stores.
9573           AddUsersToWorklist(N);
9574         } else
9575           Index = DAG.getUNDEF(N->getValueType(1));
9576         DEBUG(dbgs() << "\nReplacing.7 ";
9577               N->dump(&DAG);
9578               dbgs() << "\nWith: ";
9579               Undef.getNode()->dump(&DAG);
9580               dbgs() << " and 2 other values\n");
9581         WorklistRemover DeadNodes(*this);
9582         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9583         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9584         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9585         deleteAndRecombine(N);
9586         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9587       }
9588     }
9589   }
9590
9591   // If this load is directly stored, replace the load value with the stored
9592   // value.
9593   // TODO: Handle store large -> read small portion.
9594   // TODO: Handle TRUNCSTORE/LOADEXT
9595   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9596     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9597       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9598       if (PrevST->getBasePtr() == Ptr &&
9599           PrevST->getValue().getValueType() == N->getValueType(0))
9600       return CombineTo(N, Chain.getOperand(1), Chain);
9601     }
9602   }
9603
9604   // Try to infer better alignment information than the load already has.
9605   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9606     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9607       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9608         SDValue NewLoad =
9609                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9610                               LD->getValueType(0),
9611                               Chain, Ptr, LD->getPointerInfo(),
9612                               LD->getMemoryVT(),
9613                               LD->isVolatile(), LD->isNonTemporal(),
9614                               LD->isInvariant(), Align, LD->getAAInfo());
9615         if (NewLoad.getNode() != N)
9616           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9617       }
9618     }
9619   }
9620
9621   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9622                                                   : DAG.getSubtarget().useAA();
9623 #ifndef NDEBUG
9624   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9625       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9626     UseAA = false;
9627 #endif
9628   if (UseAA && LD->isUnindexed()) {
9629     // Walk up chain skipping non-aliasing memory nodes.
9630     SDValue BetterChain = FindBetterChain(N, Chain);
9631
9632     // If there is a better chain.
9633     if (Chain != BetterChain) {
9634       SDValue ReplLoad;
9635
9636       // Replace the chain to void dependency.
9637       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9638         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9639                                BetterChain, Ptr, LD->getMemOperand());
9640       } else {
9641         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9642                                   LD->getValueType(0),
9643                                   BetterChain, Ptr, LD->getMemoryVT(),
9644                                   LD->getMemOperand());
9645       }
9646
9647       // Create token factor to keep old chain connected.
9648       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9649                                   MVT::Other, Chain, ReplLoad.getValue(1));
9650
9651       // Make sure the new and old chains are cleaned up.
9652       AddToWorklist(Token.getNode());
9653
9654       // Replace uses with load result and token factor. Don't add users
9655       // to work list.
9656       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9657     }
9658   }
9659
9660   // Try transforming N to an indexed load.
9661   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9662     return SDValue(N, 0);
9663
9664   // Try to slice up N to more direct loads if the slices are mapped to
9665   // different register banks or pairing can take place.
9666   if (SliceUpLoad(N))
9667     return SDValue(N, 0);
9668
9669   return SDValue();
9670 }
9671
9672 namespace {
9673 /// \brief Helper structure used to slice a load in smaller loads.
9674 /// Basically a slice is obtained from the following sequence:
9675 /// Origin = load Ty1, Base
9676 /// Shift = srl Ty1 Origin, CstTy Amount
9677 /// Inst = trunc Shift to Ty2
9678 ///
9679 /// Then, it will be rewriten into:
9680 /// Slice = load SliceTy, Base + SliceOffset
9681 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9682 ///
9683 /// SliceTy is deduced from the number of bits that are actually used to
9684 /// build Inst.
9685 struct LoadedSlice {
9686   /// \brief Helper structure used to compute the cost of a slice.
9687   struct Cost {
9688     /// Are we optimizing for code size.
9689     bool ForCodeSize;
9690     /// Various cost.
9691     unsigned Loads;
9692     unsigned Truncates;
9693     unsigned CrossRegisterBanksCopies;
9694     unsigned ZExts;
9695     unsigned Shift;
9696
9697     Cost(bool ForCodeSize = false)
9698         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9699           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9700
9701     /// \brief Get the cost of one isolated slice.
9702     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9703         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9704           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9705       EVT TruncType = LS.Inst->getValueType(0);
9706       EVT LoadedType = LS.getLoadedType();
9707       if (TruncType != LoadedType &&
9708           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9709         ZExts = 1;
9710     }
9711
9712     /// \brief Account for slicing gain in the current cost.
9713     /// Slicing provide a few gains like removing a shift or a
9714     /// truncate. This method allows to grow the cost of the original
9715     /// load with the gain from this slice.
9716     void addSliceGain(const LoadedSlice &LS) {
9717       // Each slice saves a truncate.
9718       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9719       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9720                               LS.Inst->getOperand(0).getValueType()))
9721         ++Truncates;
9722       // If there is a shift amount, this slice gets rid of it.
9723       if (LS.Shift)
9724         ++Shift;
9725       // If this slice can merge a cross register bank copy, account for it.
9726       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9727         ++CrossRegisterBanksCopies;
9728     }
9729
9730     Cost &operator+=(const Cost &RHS) {
9731       Loads += RHS.Loads;
9732       Truncates += RHS.Truncates;
9733       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9734       ZExts += RHS.ZExts;
9735       Shift += RHS.Shift;
9736       return *this;
9737     }
9738
9739     bool operator==(const Cost &RHS) const {
9740       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9741              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9742              ZExts == RHS.ZExts && Shift == RHS.Shift;
9743     }
9744
9745     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9746
9747     bool operator<(const Cost &RHS) const {
9748       // Assume cross register banks copies are as expensive as loads.
9749       // FIXME: Do we want some more target hooks?
9750       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9751       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9752       // Unless we are optimizing for code size, consider the
9753       // expensive operation first.
9754       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9755         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9756       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9757              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9758     }
9759
9760     bool operator>(const Cost &RHS) const { return RHS < *this; }
9761
9762     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9763
9764     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9765   };
9766   // The last instruction that represent the slice. This should be a
9767   // truncate instruction.
9768   SDNode *Inst;
9769   // The original load instruction.
9770   LoadSDNode *Origin;
9771   // The right shift amount in bits from the original load.
9772   unsigned Shift;
9773   // The DAG from which Origin came from.
9774   // This is used to get some contextual information about legal types, etc.
9775   SelectionDAG *DAG;
9776
9777   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9778               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9779       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9780
9781   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9782   /// \return Result is \p BitWidth and has used bits set to 1 and
9783   ///         not used bits set to 0.
9784   APInt getUsedBits() const {
9785     // Reproduce the trunc(lshr) sequence:
9786     // - Start from the truncated value.
9787     // - Zero extend to the desired bit width.
9788     // - Shift left.
9789     assert(Origin && "No original load to compare against.");
9790     unsigned BitWidth = Origin->getValueSizeInBits(0);
9791     assert(Inst && "This slice is not bound to an instruction");
9792     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9793            "Extracted slice is bigger than the whole type!");
9794     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9795     UsedBits.setAllBits();
9796     UsedBits = UsedBits.zext(BitWidth);
9797     UsedBits <<= Shift;
9798     return UsedBits;
9799   }
9800
9801   /// \brief Get the size of the slice to be loaded in bytes.
9802   unsigned getLoadedSize() const {
9803     unsigned SliceSize = getUsedBits().countPopulation();
9804     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9805     return SliceSize / 8;
9806   }
9807
9808   /// \brief Get the type that will be loaded for this slice.
9809   /// Note: This may not be the final type for the slice.
9810   EVT getLoadedType() const {
9811     assert(DAG && "Missing context");
9812     LLVMContext &Ctxt = *DAG->getContext();
9813     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9814   }
9815
9816   /// \brief Get the alignment of the load used for this slice.
9817   unsigned getAlignment() const {
9818     unsigned Alignment = Origin->getAlignment();
9819     unsigned Offset = getOffsetFromBase();
9820     if (Offset != 0)
9821       Alignment = MinAlign(Alignment, Alignment + Offset);
9822     return Alignment;
9823   }
9824
9825   /// \brief Check if this slice can be rewritten with legal operations.
9826   bool isLegal() const {
9827     // An invalid slice is not legal.
9828     if (!Origin || !Inst || !DAG)
9829       return false;
9830
9831     // Offsets are for indexed load only, we do not handle that.
9832     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9833       return false;
9834
9835     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9836
9837     // Check that the type is legal.
9838     EVT SliceType = getLoadedType();
9839     if (!TLI.isTypeLegal(SliceType))
9840       return false;
9841
9842     // Check that the load is legal for this type.
9843     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9844       return false;
9845
9846     // Check that the offset can be computed.
9847     // 1. Check its type.
9848     EVT PtrType = Origin->getBasePtr().getValueType();
9849     if (PtrType == MVT::Untyped || PtrType.isExtended())
9850       return false;
9851
9852     // 2. Check that it fits in the immediate.
9853     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9854       return false;
9855
9856     // 3. Check that the computation is legal.
9857     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9858       return false;
9859
9860     // Check that the zext is legal if it needs one.
9861     EVT TruncateType = Inst->getValueType(0);
9862     if (TruncateType != SliceType &&
9863         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9864       return false;
9865
9866     return true;
9867   }
9868
9869   /// \brief Get the offset in bytes of this slice in the original chunk of
9870   /// bits.
9871   /// \pre DAG != nullptr.
9872   uint64_t getOffsetFromBase() const {
9873     assert(DAG && "Missing context.");
9874     bool IsBigEndian =
9875         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9876     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9877     uint64_t Offset = Shift / 8;
9878     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9879     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9880            "The size of the original loaded type is not a multiple of a"
9881            " byte.");
9882     // If Offset is bigger than TySizeInBytes, it means we are loading all
9883     // zeros. This should have been optimized before in the process.
9884     assert(TySizeInBytes > Offset &&
9885            "Invalid shift amount for given loaded size");
9886     if (IsBigEndian)
9887       Offset = TySizeInBytes - Offset - getLoadedSize();
9888     return Offset;
9889   }
9890
9891   /// \brief Generate the sequence of instructions to load the slice
9892   /// represented by this object and redirect the uses of this slice to
9893   /// this new sequence of instructions.
9894   /// \pre this->Inst && this->Origin are valid Instructions and this
9895   /// object passed the legal check: LoadedSlice::isLegal returned true.
9896   /// \return The last instruction of the sequence used to load the slice.
9897   SDValue loadSlice() const {
9898     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9899     const SDValue &OldBaseAddr = Origin->getBasePtr();
9900     SDValue BaseAddr = OldBaseAddr;
9901     // Get the offset in that chunk of bytes w.r.t. the endianess.
9902     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9903     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9904     if (Offset) {
9905       // BaseAddr = BaseAddr + Offset.
9906       EVT ArithType = BaseAddr.getValueType();
9907       SDLoc DL(Origin);
9908       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9909                               DAG->getConstant(Offset, DL, ArithType));
9910     }
9911
9912     // Create the type of the loaded slice according to its size.
9913     EVT SliceType = getLoadedType();
9914
9915     // Create the load for the slice.
9916     SDValue LastInst = DAG->getLoad(
9917         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9918         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9919         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9920     // If the final type is not the same as the loaded type, this means that
9921     // we have to pad with zero. Create a zero extend for that.
9922     EVT FinalType = Inst->getValueType(0);
9923     if (SliceType != FinalType)
9924       LastInst =
9925           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9926     return LastInst;
9927   }
9928
9929   /// \brief Check if this slice can be merged with an expensive cross register
9930   /// bank copy. E.g.,
9931   /// i = load i32
9932   /// f = bitcast i32 i to float
9933   bool canMergeExpensiveCrossRegisterBankCopy() const {
9934     if (!Inst || !Inst->hasOneUse())
9935       return false;
9936     SDNode *Use = *Inst->use_begin();
9937     if (Use->getOpcode() != ISD::BITCAST)
9938       return false;
9939     assert(DAG && "Missing context");
9940     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9941     EVT ResVT = Use->getValueType(0);
9942     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9943     const TargetRegisterClass *ArgRC =
9944         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9945     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9946       return false;
9947
9948     // At this point, we know that we perform a cross-register-bank copy.
9949     // Check if it is expensive.
9950     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9951     // Assume bitcasts are cheap, unless both register classes do not
9952     // explicitly share a common sub class.
9953     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9954       return false;
9955
9956     // Check if it will be merged with the load.
9957     // 1. Check the alignment constraint.
9958     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9959         ResVT.getTypeForEVT(*DAG->getContext()));
9960
9961     if (RequiredAlignment > getAlignment())
9962       return false;
9963
9964     // 2. Check that the load is a legal operation for that type.
9965     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9966       return false;
9967
9968     // 3. Check that we do not have a zext in the way.
9969     if (Inst->getValueType(0) != getLoadedType())
9970       return false;
9971
9972     return true;
9973   }
9974 };
9975 }
9976
9977 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9978 /// \p UsedBits looks like 0..0 1..1 0..0.
9979 static bool areUsedBitsDense(const APInt &UsedBits) {
9980   // If all the bits are one, this is dense!
9981   if (UsedBits.isAllOnesValue())
9982     return true;
9983
9984   // Get rid of the unused bits on the right.
9985   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9986   // Get rid of the unused bits on the left.
9987   if (NarrowedUsedBits.countLeadingZeros())
9988     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9989   // Check that the chunk of bits is completely used.
9990   return NarrowedUsedBits.isAllOnesValue();
9991 }
9992
9993 /// \brief Check whether or not \p First and \p Second are next to each other
9994 /// in memory. This means that there is no hole between the bits loaded
9995 /// by \p First and the bits loaded by \p Second.
9996 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9997                                      const LoadedSlice &Second) {
9998   assert(First.Origin == Second.Origin && First.Origin &&
9999          "Unable to match different memory origins.");
10000   APInt UsedBits = First.getUsedBits();
10001   assert((UsedBits & Second.getUsedBits()) == 0 &&
10002          "Slices are not supposed to overlap.");
10003   UsedBits |= Second.getUsedBits();
10004   return areUsedBitsDense(UsedBits);
10005 }
10006
10007 /// \brief Adjust the \p GlobalLSCost according to the target
10008 /// paring capabilities and the layout of the slices.
10009 /// \pre \p GlobalLSCost should account for at least as many loads as
10010 /// there is in the slices in \p LoadedSlices.
10011 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10012                                  LoadedSlice::Cost &GlobalLSCost) {
10013   unsigned NumberOfSlices = LoadedSlices.size();
10014   // If there is less than 2 elements, no pairing is possible.
10015   if (NumberOfSlices < 2)
10016     return;
10017
10018   // Sort the slices so that elements that are likely to be next to each
10019   // other in memory are next to each other in the list.
10020   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10021             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10022     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10023     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10024   });
10025   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10026   // First (resp. Second) is the first (resp. Second) potentially candidate
10027   // to be placed in a paired load.
10028   const LoadedSlice *First = nullptr;
10029   const LoadedSlice *Second = nullptr;
10030   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10031                 // Set the beginning of the pair.
10032                                                            First = Second) {
10033
10034     Second = &LoadedSlices[CurrSlice];
10035
10036     // If First is NULL, it means we start a new pair.
10037     // Get to the next slice.
10038     if (!First)
10039       continue;
10040
10041     EVT LoadedType = First->getLoadedType();
10042
10043     // If the types of the slices are different, we cannot pair them.
10044     if (LoadedType != Second->getLoadedType())
10045       continue;
10046
10047     // Check if the target supplies paired loads for this type.
10048     unsigned RequiredAlignment = 0;
10049     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10050       // move to the next pair, this type is hopeless.
10051       Second = nullptr;
10052       continue;
10053     }
10054     // Check if we meet the alignment requirement.
10055     if (RequiredAlignment > First->getAlignment())
10056       continue;
10057
10058     // Check that both loads are next to each other in memory.
10059     if (!areSlicesNextToEachOther(*First, *Second))
10060       continue;
10061
10062     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10063     --GlobalLSCost.Loads;
10064     // Move to the next pair.
10065     Second = nullptr;
10066   }
10067 }
10068
10069 /// \brief Check the profitability of all involved LoadedSlice.
10070 /// Currently, it is considered profitable if there is exactly two
10071 /// involved slices (1) which are (2) next to each other in memory, and
10072 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10073 ///
10074 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10075 /// the elements themselves.
10076 ///
10077 /// FIXME: When the cost model will be mature enough, we can relax
10078 /// constraints (1) and (2).
10079 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10080                                 const APInt &UsedBits, bool ForCodeSize) {
10081   unsigned NumberOfSlices = LoadedSlices.size();
10082   if (StressLoadSlicing)
10083     return NumberOfSlices > 1;
10084
10085   // Check (1).
10086   if (NumberOfSlices != 2)
10087     return false;
10088
10089   // Check (2).
10090   if (!areUsedBitsDense(UsedBits))
10091     return false;
10092
10093   // Check (3).
10094   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10095   // The original code has one big load.
10096   OrigCost.Loads = 1;
10097   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10098     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10099     // Accumulate the cost of all the slices.
10100     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10101     GlobalSlicingCost += SliceCost;
10102
10103     // Account as cost in the original configuration the gain obtained
10104     // with the current slices.
10105     OrigCost.addSliceGain(LS);
10106   }
10107
10108   // If the target supports paired load, adjust the cost accordingly.
10109   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10110   return OrigCost > GlobalSlicingCost;
10111 }
10112
10113 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10114 /// operations, split it in the various pieces being extracted.
10115 ///
10116 /// This sort of thing is introduced by SROA.
10117 /// This slicing takes care not to insert overlapping loads.
10118 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10119 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10120   if (Level < AfterLegalizeDAG)
10121     return false;
10122
10123   LoadSDNode *LD = cast<LoadSDNode>(N);
10124   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10125       !LD->getValueType(0).isInteger())
10126     return false;
10127
10128   // Keep track of already used bits to detect overlapping values.
10129   // In that case, we will just abort the transformation.
10130   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10131
10132   SmallVector<LoadedSlice, 4> LoadedSlices;
10133
10134   // Check if this load is used as several smaller chunks of bits.
10135   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10136   // of computation for each trunc.
10137   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10138        UI != UIEnd; ++UI) {
10139     // Skip the uses of the chain.
10140     if (UI.getUse().getResNo() != 0)
10141       continue;
10142
10143     SDNode *User = *UI;
10144     unsigned Shift = 0;
10145
10146     // Check if this is a trunc(lshr).
10147     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10148         isa<ConstantSDNode>(User->getOperand(1))) {
10149       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10150       User = *User->use_begin();
10151     }
10152
10153     // At this point, User is a Truncate, iff we encountered, trunc or
10154     // trunc(lshr).
10155     if (User->getOpcode() != ISD::TRUNCATE)
10156       return false;
10157
10158     // The width of the type must be a power of 2 and greater than 8-bits.
10159     // Otherwise the load cannot be represented in LLVM IR.
10160     // Moreover, if we shifted with a non-8-bits multiple, the slice
10161     // will be across several bytes. We do not support that.
10162     unsigned Width = User->getValueSizeInBits(0);
10163     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10164       return 0;
10165
10166     // Build the slice for this chain of computations.
10167     LoadedSlice LS(User, LD, Shift, &DAG);
10168     APInt CurrentUsedBits = LS.getUsedBits();
10169
10170     // Check if this slice overlaps with another.
10171     if ((CurrentUsedBits & UsedBits) != 0)
10172       return false;
10173     // Update the bits used globally.
10174     UsedBits |= CurrentUsedBits;
10175
10176     // Check if the new slice would be legal.
10177     if (!LS.isLegal())
10178       return false;
10179
10180     // Record the slice.
10181     LoadedSlices.push_back(LS);
10182   }
10183
10184   // Abort slicing if it does not seem to be profitable.
10185   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10186     return false;
10187
10188   ++SlicedLoads;
10189
10190   // Rewrite each chain to use an independent load.
10191   // By construction, each chain can be represented by a unique load.
10192
10193   // Prepare the argument for the new token factor for all the slices.
10194   SmallVector<SDValue, 8> ArgChains;
10195   for (SmallVectorImpl<LoadedSlice>::const_iterator
10196            LSIt = LoadedSlices.begin(),
10197            LSItEnd = LoadedSlices.end();
10198        LSIt != LSItEnd; ++LSIt) {
10199     SDValue SliceInst = LSIt->loadSlice();
10200     CombineTo(LSIt->Inst, SliceInst, true);
10201     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10202       SliceInst = SliceInst.getOperand(0);
10203     assert(SliceInst->getOpcode() == ISD::LOAD &&
10204            "It takes more than a zext to get to the loaded slice!!");
10205     ArgChains.push_back(SliceInst.getValue(1));
10206   }
10207
10208   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10209                               ArgChains);
10210   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10211   return true;
10212 }
10213
10214 /// Check to see if V is (and load (ptr), imm), where the load is having
10215 /// specific bytes cleared out.  If so, return the byte size being masked out
10216 /// and the shift amount.
10217 static std::pair<unsigned, unsigned>
10218 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10219   std::pair<unsigned, unsigned> Result(0, 0);
10220
10221   // Check for the structure we're looking for.
10222   if (V->getOpcode() != ISD::AND ||
10223       !isa<ConstantSDNode>(V->getOperand(1)) ||
10224       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10225     return Result;
10226
10227   // Check the chain and pointer.
10228   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10229   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10230
10231   // The store should be chained directly to the load or be an operand of a
10232   // tokenfactor.
10233   if (LD == Chain.getNode())
10234     ; // ok.
10235   else if (Chain->getOpcode() != ISD::TokenFactor)
10236     return Result; // Fail.
10237   else {
10238     bool isOk = false;
10239     for (const SDValue &ChainOp : Chain->op_values())
10240       if (ChainOp.getNode() == LD) {
10241         isOk = true;
10242         break;
10243       }
10244     if (!isOk) return Result;
10245   }
10246
10247   // This only handles simple types.
10248   if (V.getValueType() != MVT::i16 &&
10249       V.getValueType() != MVT::i32 &&
10250       V.getValueType() != MVT::i64)
10251     return Result;
10252
10253   // Check the constant mask.  Invert it so that the bits being masked out are
10254   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10255   // follow the sign bit for uniformity.
10256   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10257   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10258   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10259   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10260   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10261   if (NotMaskLZ == 64) return Result;  // All zero mask.
10262
10263   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10264   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10265     return Result;
10266
10267   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10268   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10269     NotMaskLZ -= 64-V.getValueSizeInBits();
10270
10271   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10272   switch (MaskedBytes) {
10273   case 1:
10274   case 2:
10275   case 4: break;
10276   default: return Result; // All one mask, or 5-byte mask.
10277   }
10278
10279   // Verify that the first bit starts at a multiple of mask so that the access
10280   // is aligned the same as the access width.
10281   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10282
10283   Result.first = MaskedBytes;
10284   Result.second = NotMaskTZ/8;
10285   return Result;
10286 }
10287
10288
10289 /// Check to see if IVal is something that provides a value as specified by
10290 /// MaskInfo. If so, replace the specified store with a narrower store of
10291 /// truncated IVal.
10292 static SDNode *
10293 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10294                                 SDValue IVal, StoreSDNode *St,
10295                                 DAGCombiner *DC) {
10296   unsigned NumBytes = MaskInfo.first;
10297   unsigned ByteShift = MaskInfo.second;
10298   SelectionDAG &DAG = DC->getDAG();
10299
10300   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10301   // that uses this.  If not, this is not a replacement.
10302   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10303                                   ByteShift*8, (ByteShift+NumBytes)*8);
10304   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10305
10306   // Check that it is legal on the target to do this.  It is legal if the new
10307   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10308   // legalization.
10309   MVT VT = MVT::getIntegerVT(NumBytes*8);
10310   if (!DC->isTypeLegal(VT))
10311     return nullptr;
10312
10313   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10314   // shifted by ByteShift and truncated down to NumBytes.
10315   if (ByteShift) {
10316     SDLoc DL(IVal);
10317     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10318                        DAG.getConstant(ByteShift*8, DL,
10319                                     DC->getShiftAmountTy(IVal.getValueType())));
10320   }
10321
10322   // Figure out the offset for the store and the alignment of the access.
10323   unsigned StOffset;
10324   unsigned NewAlign = St->getAlignment();
10325
10326   if (DAG.getTargetLoweringInfo().isLittleEndian())
10327     StOffset = ByteShift;
10328   else
10329     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10330
10331   SDValue Ptr = St->getBasePtr();
10332   if (StOffset) {
10333     SDLoc DL(IVal);
10334     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10335                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10336     NewAlign = MinAlign(NewAlign, StOffset);
10337   }
10338
10339   // Truncate down to the new size.
10340   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10341
10342   ++OpsNarrowed;
10343   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10344                       St->getPointerInfo().getWithOffset(StOffset),
10345                       false, false, NewAlign).getNode();
10346 }
10347
10348
10349 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10350 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10351 /// narrowing the load and store if it would end up being a win for performance
10352 /// or code size.
10353 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10354   StoreSDNode *ST  = cast<StoreSDNode>(N);
10355   if (ST->isVolatile())
10356     return SDValue();
10357
10358   SDValue Chain = ST->getChain();
10359   SDValue Value = ST->getValue();
10360   SDValue Ptr   = ST->getBasePtr();
10361   EVT VT = Value.getValueType();
10362
10363   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10364     return SDValue();
10365
10366   unsigned Opc = Value.getOpcode();
10367
10368   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10369   // is a byte mask indicating a consecutive number of bytes, check to see if
10370   // Y is known to provide just those bytes.  If so, we try to replace the
10371   // load + replace + store sequence with a single (narrower) store, which makes
10372   // the load dead.
10373   if (Opc == ISD::OR) {
10374     std::pair<unsigned, unsigned> MaskedLoad;
10375     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10376     if (MaskedLoad.first)
10377       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10378                                                   Value.getOperand(1), ST,this))
10379         return SDValue(NewST, 0);
10380
10381     // Or is commutative, so try swapping X and Y.
10382     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10383     if (MaskedLoad.first)
10384       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10385                                                   Value.getOperand(0), ST,this))
10386         return SDValue(NewST, 0);
10387   }
10388
10389   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10390       Value.getOperand(1).getOpcode() != ISD::Constant)
10391     return SDValue();
10392
10393   SDValue N0 = Value.getOperand(0);
10394   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10395       Chain == SDValue(N0.getNode(), 1)) {
10396     LoadSDNode *LD = cast<LoadSDNode>(N0);
10397     if (LD->getBasePtr() != Ptr ||
10398         LD->getPointerInfo().getAddrSpace() !=
10399         ST->getPointerInfo().getAddrSpace())
10400       return SDValue();
10401
10402     // Find the type to narrow it the load / op / store to.
10403     SDValue N1 = Value.getOperand(1);
10404     unsigned BitWidth = N1.getValueSizeInBits();
10405     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10406     if (Opc == ISD::AND)
10407       Imm ^= APInt::getAllOnesValue(BitWidth);
10408     if (Imm == 0 || Imm.isAllOnesValue())
10409       return SDValue();
10410     unsigned ShAmt = Imm.countTrailingZeros();
10411     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10412     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10413     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10414     // The narrowing should be profitable, the load/store operation should be
10415     // legal (or custom) and the store size should be equal to the NewVT width.
10416     while (NewBW < BitWidth &&
10417            (NewVT.getStoreSizeInBits() != NewBW ||
10418             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10419             !TLI.isNarrowingProfitable(VT, NewVT))) {
10420       NewBW = NextPowerOf2(NewBW);
10421       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10422     }
10423     if (NewBW >= BitWidth)
10424       return SDValue();
10425
10426     // If the lsb changed does not start at the type bitwidth boundary,
10427     // start at the previous one.
10428     if (ShAmt % NewBW)
10429       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10430     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10431                                    std::min(BitWidth, ShAmt + NewBW));
10432     if ((Imm & Mask) == Imm) {
10433       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10434       if (Opc == ISD::AND)
10435         NewImm ^= APInt::getAllOnesValue(NewBW);
10436       uint64_t PtrOff = ShAmt / 8;
10437       // For big endian targets, we need to adjust the offset to the pointer to
10438       // load the correct bytes.
10439       if (TLI.isBigEndian())
10440         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10441
10442       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10443       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10444       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10445         return SDValue();
10446
10447       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10448                                    Ptr.getValueType(), Ptr,
10449                                    DAG.getConstant(PtrOff, SDLoc(LD),
10450                                                    Ptr.getValueType()));
10451       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10452                                   LD->getChain(), NewPtr,
10453                                   LD->getPointerInfo().getWithOffset(PtrOff),
10454                                   LD->isVolatile(), LD->isNonTemporal(),
10455                                   LD->isInvariant(), NewAlign,
10456                                   LD->getAAInfo());
10457       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10458                                    DAG.getConstant(NewImm, SDLoc(Value),
10459                                                    NewVT));
10460       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10461                                    NewVal, NewPtr,
10462                                    ST->getPointerInfo().getWithOffset(PtrOff),
10463                                    false, false, NewAlign);
10464
10465       AddToWorklist(NewPtr.getNode());
10466       AddToWorklist(NewLD.getNode());
10467       AddToWorklist(NewVal.getNode());
10468       WorklistRemover DeadNodes(*this);
10469       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10470       ++OpsNarrowed;
10471       return NewST;
10472     }
10473   }
10474
10475   return SDValue();
10476 }
10477
10478 /// For a given floating point load / store pair, if the load value isn't used
10479 /// by any other operations, then consider transforming the pair to integer
10480 /// load / store operations if the target deems the transformation profitable.
10481 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10482   StoreSDNode *ST  = cast<StoreSDNode>(N);
10483   SDValue Chain = ST->getChain();
10484   SDValue Value = ST->getValue();
10485   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10486       Value.hasOneUse() &&
10487       Chain == SDValue(Value.getNode(), 1)) {
10488     LoadSDNode *LD = cast<LoadSDNode>(Value);
10489     EVT VT = LD->getMemoryVT();
10490     if (!VT.isFloatingPoint() ||
10491         VT != ST->getMemoryVT() ||
10492         LD->isNonTemporal() ||
10493         ST->isNonTemporal() ||
10494         LD->getPointerInfo().getAddrSpace() != 0 ||
10495         ST->getPointerInfo().getAddrSpace() != 0)
10496       return SDValue();
10497
10498     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10499     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10500         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10501         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10502         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10503       return SDValue();
10504
10505     unsigned LDAlign = LD->getAlignment();
10506     unsigned STAlign = ST->getAlignment();
10507     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10508     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10509     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10510       return SDValue();
10511
10512     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10513                                 LD->getChain(), LD->getBasePtr(),
10514                                 LD->getPointerInfo(),
10515                                 false, false, false, LDAlign);
10516
10517     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10518                                  NewLD, ST->getBasePtr(),
10519                                  ST->getPointerInfo(),
10520                                  false, false, STAlign);
10521
10522     AddToWorklist(NewLD.getNode());
10523     AddToWorklist(NewST.getNode());
10524     WorklistRemover DeadNodes(*this);
10525     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10526     ++LdStFP2Int;
10527     return NewST;
10528   }
10529
10530   return SDValue();
10531 }
10532
10533 namespace {
10534 /// Helper struct to parse and store a memory address as base + index + offset.
10535 /// We ignore sign extensions when it is safe to do so.
10536 /// The following two expressions are not equivalent. To differentiate we need
10537 /// to store whether there was a sign extension involved in the index
10538 /// computation.
10539 ///  (load (i64 add (i64 copyfromreg %c)
10540 ///                 (i64 signextend (add (i8 load %index)
10541 ///                                      (i8 1))))
10542 /// vs
10543 ///
10544 /// (load (i64 add (i64 copyfromreg %c)
10545 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10546 ///                                         (i32 1)))))
10547 struct BaseIndexOffset {
10548   SDValue Base;
10549   SDValue Index;
10550   int64_t Offset;
10551   bool IsIndexSignExt;
10552
10553   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10554
10555   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10556                   bool IsIndexSignExt) :
10557     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10558
10559   bool equalBaseIndex(const BaseIndexOffset &Other) {
10560     return Other.Base == Base && Other.Index == Index &&
10561       Other.IsIndexSignExt == IsIndexSignExt;
10562   }
10563
10564   /// Parses tree in Ptr for base, index, offset addresses.
10565   static BaseIndexOffset match(SDValue Ptr) {
10566     bool IsIndexSignExt = false;
10567
10568     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10569     // instruction, then it could be just the BASE or everything else we don't
10570     // know how to handle. Just use Ptr as BASE and give up.
10571     if (Ptr->getOpcode() != ISD::ADD)
10572       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10573
10574     // We know that we have at least an ADD instruction. Try to pattern match
10575     // the simple case of BASE + OFFSET.
10576     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10577       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10578       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10579                               IsIndexSignExt);
10580     }
10581
10582     // Inside a loop the current BASE pointer is calculated using an ADD and a
10583     // MUL instruction. In this case Ptr is the actual BASE pointer.
10584     // (i64 add (i64 %array_ptr)
10585     //          (i64 mul (i64 %induction_var)
10586     //                   (i64 %element_size)))
10587     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10588       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10589
10590     // Look at Base + Index + Offset cases.
10591     SDValue Base = Ptr->getOperand(0);
10592     SDValue IndexOffset = Ptr->getOperand(1);
10593
10594     // Skip signextends.
10595     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10596       IndexOffset = IndexOffset->getOperand(0);
10597       IsIndexSignExt = true;
10598     }
10599
10600     // Either the case of Base + Index (no offset) or something else.
10601     if (IndexOffset->getOpcode() != ISD::ADD)
10602       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10603
10604     // Now we have the case of Base + Index + offset.
10605     SDValue Index = IndexOffset->getOperand(0);
10606     SDValue Offset = IndexOffset->getOperand(1);
10607
10608     if (!isa<ConstantSDNode>(Offset))
10609       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10610
10611     // Ignore signextends.
10612     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10613       Index = Index->getOperand(0);
10614       IsIndexSignExt = true;
10615     } else IsIndexSignExt = false;
10616
10617     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10618     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10619   }
10620 };
10621 } // namespace
10622
10623 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10624                                                   SDLoc SL,
10625                                                   ArrayRef<MemOpLink> Stores,
10626                                                   EVT Ty) const {
10627   SmallVector<SDValue, 8> BuildVector;
10628
10629   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10630     BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10631
10632   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10633 }
10634
10635 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10636                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10637                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10638   // Make sure we have something to merge.
10639   if (NumElem < 2)
10640     return false;
10641
10642   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10643   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10644   unsigned LatestNodeUsed = 0;
10645
10646   for (unsigned i=0; i < NumElem; ++i) {
10647     // Find a chain for the new wide-store operand. Notice that some
10648     // of the store nodes that we found may not be selected for inclusion
10649     // in the wide store. The chain we use needs to be the chain of the
10650     // latest store node which is *used* and replaced by the wide store.
10651     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10652       LatestNodeUsed = i;
10653   }
10654
10655   // The latest Node in the DAG.
10656   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10657   SDLoc DL(StoreNodes[0].MemNode);
10658
10659   SDValue StoredVal;
10660   if (UseVector) {
10661     // Find a legal type for the vector store.
10662     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10663     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10664     if (IsConstantSrc) {
10665       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10666     } else {
10667       SmallVector<SDValue, 8> Ops;
10668       for (unsigned i = 0; i < NumElem ; ++i) {
10669         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10670         SDValue Val = St->getValue();
10671         // All of the operands of a BUILD_VECTOR must have the same type.
10672         if (Val.getValueType() != MemVT)
10673           return false;
10674         Ops.push_back(Val);
10675       }
10676
10677       // Build the extracted vector elements back into a vector.
10678       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10679     }
10680   } else {
10681     // We should always use a vector store when merging extracted vector
10682     // elements, so this path implies a store of constants.
10683     assert(IsConstantSrc && "Merged vector elements should use vector store");
10684
10685     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
10686     APInt StoreInt(SizeInBits, 0);
10687
10688     // Construct a single integer constant which is made of the smaller
10689     // constant inputs.
10690     bool IsLE = TLI.isLittleEndian();
10691     for (unsigned i = 0; i < NumElem ; ++i) {
10692       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10693       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10694       SDValue Val = St->getValue();
10695       StoreInt <<= ElementSizeBytes * 8;
10696       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10697         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10698       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10699         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10700       } else {
10701         llvm_unreachable("Invalid constant element type");
10702       }
10703     }
10704
10705     // Create the new Load and Store operations.
10706     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10707     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10708   }
10709
10710   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10711                                   FirstInChain->getBasePtr(),
10712                                   FirstInChain->getPointerInfo(),
10713                                   false, false,
10714                                   FirstInChain->getAlignment());
10715
10716   // Replace the last store with the new store
10717   CombineTo(LatestOp, NewStore);
10718   // Erase all other stores.
10719   for (unsigned i = 0; i < NumElem ; ++i) {
10720     if (StoreNodes[i].MemNode == LatestOp)
10721       continue;
10722     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10723     // ReplaceAllUsesWith will replace all uses that existed when it was
10724     // called, but graph optimizations may cause new ones to appear. For
10725     // example, the case in pr14333 looks like
10726     //
10727     //  St's chain -> St -> another store -> X
10728     //
10729     // And the only difference from St to the other store is the chain.
10730     // When we change it's chain to be St's chain they become identical,
10731     // get CSEed and the net result is that X is now a use of St.
10732     // Since we know that St is redundant, just iterate.
10733     while (!St->use_empty())
10734       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10735     deleteAndRecombine(St);
10736   }
10737
10738   return true;
10739 }
10740
10741 static bool allowableAlignment(const SelectionDAG &DAG,
10742                                const TargetLowering &TLI, EVT EVTTy,
10743                                unsigned AS, unsigned Align) {
10744   if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10745     return true;
10746
10747   Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10748   unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10749   return (Align >= ABIAlignment);
10750 }
10751
10752 void DAGCombiner::getStoreMergeAndAliasCandidates(
10753     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10754     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10755   // This holds the base pointer, index, and the offset in bytes from the base
10756   // pointer.
10757   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10758
10759   // We must have a base and an offset.
10760   if (!BasePtr.Base.getNode())
10761     return;
10762
10763   // Do not handle stores to undef base pointers.
10764   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10765     return;
10766
10767   // Walk up the chain and look for nodes with offsets from the same
10768   // base pointer. Stop when reaching an instruction with a different kind
10769   // or instruction which has a different base pointer.
10770   EVT MemVT = St->getMemoryVT();
10771   unsigned Seq = 0;
10772   StoreSDNode *Index = St;
10773   while (Index) {
10774     // If the chain has more than one use, then we can't reorder the mem ops.
10775     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10776       break;
10777
10778     // Find the base pointer and offset for this memory node.
10779     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10780
10781     // Check that the base pointer is the same as the original one.
10782     if (!Ptr.equalBaseIndex(BasePtr))
10783       break;
10784
10785     // The memory operands must not be volatile.
10786     if (Index->isVolatile() || Index->isIndexed())
10787       break;
10788
10789     // No truncation.
10790     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10791       if (St->isTruncatingStore())
10792         break;
10793
10794     // The stored memory type must be the same.
10795     if (Index->getMemoryVT() != MemVT)
10796       break;
10797
10798     // We found a potential memory operand to merge.
10799     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10800
10801     // Find the next memory operand in the chain. If the next operand in the
10802     // chain is a store then move up and continue the scan with the next
10803     // memory operand. If the next operand is a load save it and use alias
10804     // information to check if it interferes with anything.
10805     SDNode *NextInChain = Index->getChain().getNode();
10806     while (1) {
10807       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10808         // We found a store node. Use it for the next iteration.
10809         Index = STn;
10810         break;
10811       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10812         if (Ldn->isVolatile()) {
10813           Index = nullptr;
10814           break;
10815         }
10816
10817         // Save the load node for later. Continue the scan.
10818         AliasLoadNodes.push_back(Ldn);
10819         NextInChain = Ldn->getChain().getNode();
10820         continue;
10821       } else {
10822         Index = nullptr;
10823         break;
10824       }
10825     }
10826   }
10827 }
10828
10829 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10830   if (OptLevel == CodeGenOpt::None)
10831     return false;
10832
10833   EVT MemVT = St->getMemoryVT();
10834   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10835   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10836       Attribute::NoImplicitFloat);
10837
10838   // This function cannot currently deal with non-byte-sized memory sizes.
10839   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10840     return false;
10841
10842   // Don't merge vectors into wider inputs.
10843   if (MemVT.isVector() || !MemVT.isSimple())
10844     return false;
10845
10846   // Perform an early exit check. Do not bother looking at stored values that
10847   // are not constants, loads, or extracted vector elements.
10848   SDValue StoredVal = St->getValue();
10849   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10850   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10851                        isa<ConstantFPSDNode>(StoredVal);
10852   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10853
10854   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10855     return false;
10856
10857   // Only look at ends of store sequences.
10858   SDValue Chain = SDValue(St, 0);
10859   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10860     return false;
10861
10862   // Save the LoadSDNodes that we find in the chain.
10863   // We need to make sure that these nodes do not interfere with
10864   // any of the store nodes.
10865   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10866   
10867   // Save the StoreSDNodes that we find in the chain.
10868   SmallVector<MemOpLink, 8> StoreNodes;
10869
10870   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10871   
10872   // Check if there is anything to merge.
10873   if (StoreNodes.size() < 2)
10874     return false;
10875
10876   // Sort the memory operands according to their distance from the base pointer.
10877   std::sort(StoreNodes.begin(), StoreNodes.end(),
10878             [](MemOpLink LHS, MemOpLink RHS) {
10879     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10880            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10881             LHS.SequenceNum > RHS.SequenceNum);
10882   });
10883
10884   // Scan the memory operations on the chain and find the first non-consecutive
10885   // store memory address.
10886   unsigned LastConsecutiveStore = 0;
10887   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10888   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10889
10890     // Check that the addresses are consecutive starting from the second
10891     // element in the list of stores.
10892     if (i > 0) {
10893       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10894       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10895         break;
10896     }
10897
10898     bool Alias = false;
10899     // Check if this store interferes with any of the loads that we found.
10900     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10901       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10902         Alias = true;
10903         break;
10904       }
10905     // We found a load that alias with this store. Stop the sequence.
10906     if (Alias)
10907       break;
10908
10909     // Mark this node as useful.
10910     LastConsecutiveStore = i;
10911   }
10912
10913   // The node with the lowest store address.
10914   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10915   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10916   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10917
10918   // Store the constants into memory as one consecutive store.
10919   if (IsConstantSrc) {
10920     unsigned LastLegalType = 0;
10921     unsigned LastLegalVectorType = 0;
10922     bool NonZero = false;
10923     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10924       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10925       SDValue StoredVal = St->getValue();
10926
10927       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10928         NonZero |= !C->isNullValue();
10929       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10930         NonZero |= !C->getConstantFPValue()->isNullValue();
10931       } else {
10932         // Non-constant.
10933         break;
10934       }
10935
10936       // Find a legal type for the constant store.
10937       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
10938       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10939       if (TLI.isTypeLegal(StoreTy) &&
10940           allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10941                              FirstStoreAlign)) {
10942         LastLegalType = i+1;
10943       // Or check whether a truncstore is legal.
10944       } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10945                  TargetLowering::TypePromoteInteger) {
10946         EVT LegalizedStoredValueTy =
10947           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10948         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10949             allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10950                                FirstStoreAlign)) {
10951           LastLegalType = i + 1;
10952         }
10953       }
10954
10955       // Find a legal type for the vector store.
10956       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10957       if (TLI.isTypeLegal(Ty) &&
10958           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10959         LastLegalVectorType = i + 1;
10960       }
10961     }
10962
10963
10964     // We only use vectors if the constant is known to be zero or the target
10965     // allows it and the function is not marked with the noimplicitfloat
10966     // attribute.
10967     if (NoVectors) {
10968       LastLegalVectorType = 0;
10969     } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10970                                                             LastLegalVectorType,
10971                                                             FirstStoreAS)) {
10972       LastLegalVectorType = 0;
10973     }
10974
10975     // Check if we found a legal integer type to store.
10976     if (LastLegalType == 0 && LastLegalVectorType == 0)
10977       return false;
10978
10979     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10980     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10981
10982     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10983                                            true, UseVector);
10984   }
10985
10986   // When extracting multiple vector elements, try to store them
10987   // in one vector store rather than a sequence of scalar stores.
10988   if (IsExtractVecEltSrc) {
10989     unsigned NumElem = 0;
10990     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10991       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10992       SDValue StoredVal = St->getValue();
10993       // This restriction could be loosened.
10994       // Bail out if any stored values are not elements extracted from a vector.
10995       // It should be possible to handle mixed sources, but load sources need
10996       // more careful handling (see the block of code below that handles
10997       // consecutive loads).
10998       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10999         return false;
11000
11001       // Find a legal type for the vector store.
11002       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11003       if (TLI.isTypeLegal(Ty) &&
11004           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
11005         NumElem = i + 1;
11006     }
11007
11008     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11009                                            false, true);
11010   }
11011
11012   // Below we handle the case of multiple consecutive stores that
11013   // come from multiple consecutive loads. We merge them into a single
11014   // wide load and a single wide store.
11015
11016   // Look for load nodes which are used by the stored values.
11017   SmallVector<MemOpLink, 8> LoadNodes;
11018
11019   // Find acceptable loads. Loads need to have the same chain (token factor),
11020   // must not be zext, volatile, indexed, and they must be consecutive.
11021   BaseIndexOffset LdBasePtr;
11022   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11023     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11024     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11025     if (!Ld) break;
11026
11027     // Loads must only have one use.
11028     if (!Ld->hasNUsesOfValue(1, 0))
11029       break;
11030
11031     // The memory operands must not be volatile.
11032     if (Ld->isVolatile() || Ld->isIndexed())
11033       break;
11034
11035     // We do not accept ext loads.
11036     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11037       break;
11038
11039     // The stored memory type must be the same.
11040     if (Ld->getMemoryVT() != MemVT)
11041       break;
11042
11043     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11044     // If this is not the first ptr that we check.
11045     if (LdBasePtr.Base.getNode()) {
11046       // The base ptr must be the same.
11047       if (!LdPtr.equalBaseIndex(LdBasePtr))
11048         break;
11049     } else {
11050       // Check that all other base pointers are the same as this one.
11051       LdBasePtr = LdPtr;
11052     }
11053
11054     // We found a potential memory operand to merge.
11055     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11056   }
11057
11058   if (LoadNodes.size() < 2)
11059     return false;
11060
11061   // If we have load/store pair instructions and we only have two values,
11062   // don't bother.
11063   unsigned RequiredAlignment;
11064   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11065       St->getAlignment() >= RequiredAlignment)
11066     return false;
11067
11068   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11069   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11070   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11071
11072   // Scan the memory operations on the chain and find the first non-consecutive
11073   // load memory address. These variables hold the index in the store node
11074   // array.
11075   unsigned LastConsecutiveLoad = 0;
11076   // This variable refers to the size and not index in the array.
11077   unsigned LastLegalVectorType = 0;
11078   unsigned LastLegalIntegerType = 0;
11079   StartAddress = LoadNodes[0].OffsetFromBase;
11080   SDValue FirstChain = FirstLoad->getChain();
11081   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11082     // All loads much share the same chain.
11083     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11084       break;
11085
11086     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11087     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11088       break;
11089     LastConsecutiveLoad = i;
11090
11091     // Find a legal type for the vector store.
11092     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11093     if (TLI.isTypeLegal(StoreTy) &&
11094         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11095         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11096       LastLegalVectorType = i + 1;
11097     }
11098
11099     // Find a legal type for the integer store.
11100     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11101     StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11102     if (TLI.isTypeLegal(StoreTy) &&
11103         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11104         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11105       LastLegalIntegerType = i + 1;
11106     // Or check whether a truncstore and extload is legal.
11107     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11108              TargetLowering::TypePromoteInteger) {
11109       EVT LegalizedStoredValueTy =
11110         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11111       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11112           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11113           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11114           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11115           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11116                              FirstStoreAlign) &&
11117           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11118                              FirstLoadAlign))
11119         LastLegalIntegerType = i+1;
11120     }
11121   }
11122
11123   // Only use vector types if the vector type is larger than the integer type.
11124   // If they are the same, use integers.
11125   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11126   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11127
11128   // We add +1 here because the LastXXX variables refer to location while
11129   // the NumElem refers to array/index size.
11130   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11131   NumElem = std::min(LastLegalType, NumElem);
11132
11133   if (NumElem < 2)
11134     return false;
11135
11136   // The latest Node in the DAG.
11137   unsigned LatestNodeUsed = 0;
11138   for (unsigned i=1; i<NumElem; ++i) {
11139     // Find a chain for the new wide-store operand. Notice that some
11140     // of the store nodes that we found may not be selected for inclusion
11141     // in the wide store. The chain we use needs to be the chain of the
11142     // latest store node which is *used* and replaced by the wide store.
11143     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11144       LatestNodeUsed = i;
11145   }
11146
11147   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11148
11149   // Find if it is better to use vectors or integers to load and store
11150   // to memory.
11151   EVT JointMemOpVT;
11152   if (UseVectorTy) {
11153     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11154   } else {
11155     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11156     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11157   }
11158
11159   SDLoc LoadDL(LoadNodes[0].MemNode);
11160   SDLoc StoreDL(StoreNodes[0].MemNode);
11161
11162   SDValue NewLoad = DAG.getLoad(
11163       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11164       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11165
11166   SDValue NewStore = DAG.getStore(
11167       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11168       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11169
11170   // Replace one of the loads with the new load.
11171   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11172   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11173                                 SDValue(NewLoad.getNode(), 1));
11174
11175   // Remove the rest of the load chains.
11176   for (unsigned i = 1; i < NumElem ; ++i) {
11177     // Replace all chain users of the old load nodes with the chain of the new
11178     // load node.
11179     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11180     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11181   }
11182
11183   // Replace the last store with the new store.
11184   CombineTo(LatestOp, NewStore);
11185   // Erase all other stores.
11186   for (unsigned i = 0; i < NumElem ; ++i) {
11187     // Remove all Store nodes.
11188     if (StoreNodes[i].MemNode == LatestOp)
11189       continue;
11190     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11191     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11192     deleteAndRecombine(St);
11193   }
11194
11195   return true;
11196 }
11197
11198 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11199   StoreSDNode *ST  = cast<StoreSDNode>(N);
11200   SDValue Chain = ST->getChain();
11201   SDValue Value = ST->getValue();
11202   SDValue Ptr   = ST->getBasePtr();
11203
11204   // If this is a store of a bit convert, store the input value if the
11205   // resultant store does not need a higher alignment than the original.
11206   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11207       ST->isUnindexed()) {
11208     unsigned OrigAlign = ST->getAlignment();
11209     EVT SVT = Value.getOperand(0).getValueType();
11210     unsigned Align = TLI.getDataLayout()->
11211       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11212     if (Align <= OrigAlign &&
11213         ((!LegalOperations && !ST->isVolatile()) ||
11214          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11215       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11216                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11217                           ST->isNonTemporal(), OrigAlign,
11218                           ST->getAAInfo());
11219   }
11220
11221   // Turn 'store undef, Ptr' -> nothing.
11222   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11223     return Chain;
11224
11225   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11226   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11227     // NOTE: If the original store is volatile, this transform must not increase
11228     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11229     // processor operation but an i64 (which is not legal) requires two.  So the
11230     // transform should not be done in this case.
11231     if (Value.getOpcode() != ISD::TargetConstantFP) {
11232       SDValue Tmp;
11233       switch (CFP->getSimpleValueType(0).SimpleTy) {
11234       default: llvm_unreachable("Unknown FP type");
11235       case MVT::f16:    // We don't do this for these yet.
11236       case MVT::f80:
11237       case MVT::f128:
11238       case MVT::ppcf128:
11239         break;
11240       case MVT::f32:
11241         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11242             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11243           ;
11244           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11245                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11246                               MVT::i32);
11247           return DAG.getStore(Chain, SDLoc(N), Tmp,
11248                               Ptr, ST->getMemOperand());
11249         }
11250         break;
11251       case MVT::f64:
11252         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11253              !ST->isVolatile()) ||
11254             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11255           ;
11256           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11257                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11258           return DAG.getStore(Chain, SDLoc(N), Tmp,
11259                               Ptr, ST->getMemOperand());
11260         }
11261
11262         if (!ST->isVolatile() &&
11263             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11264           // Many FP stores are not made apparent until after legalize, e.g. for
11265           // argument passing.  Since this is so common, custom legalize the
11266           // 64-bit integer store into two 32-bit stores.
11267           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11268           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11269           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11270           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11271
11272           unsigned Alignment = ST->getAlignment();
11273           bool isVolatile = ST->isVolatile();
11274           bool isNonTemporal = ST->isNonTemporal();
11275           AAMDNodes AAInfo = ST->getAAInfo();
11276
11277           SDLoc DL(N);
11278
11279           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11280                                      Ptr, ST->getPointerInfo(),
11281                                      isVolatile, isNonTemporal,
11282                                      ST->getAlignment(), AAInfo);
11283           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11284                             DAG.getConstant(4, DL, Ptr.getValueType()));
11285           Alignment = MinAlign(Alignment, 4U);
11286           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11287                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11288                                      isVolatile, isNonTemporal,
11289                                      Alignment, AAInfo);
11290           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11291                              St0, St1);
11292         }
11293
11294         break;
11295       }
11296     }
11297   }
11298
11299   // Try to infer better alignment information than the store already has.
11300   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11301     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11302       if (Align > ST->getAlignment()) {
11303         SDValue NewStore =
11304                DAG.getTruncStore(Chain, SDLoc(N), Value,
11305                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11306                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11307                                  ST->getAAInfo());
11308         if (NewStore.getNode() != N)
11309           return CombineTo(ST, NewStore, true);
11310       }
11311     }
11312   }
11313
11314   // Try transforming a pair floating point load / store ops to integer
11315   // load / store ops.
11316   SDValue NewST = TransformFPLoadStorePair(N);
11317   if (NewST.getNode())
11318     return NewST;
11319
11320   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11321                                                   : DAG.getSubtarget().useAA();
11322 #ifndef NDEBUG
11323   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11324       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11325     UseAA = false;
11326 #endif
11327   if (UseAA && ST->isUnindexed()) {
11328     // Walk up chain skipping non-aliasing memory nodes.
11329     SDValue BetterChain = FindBetterChain(N, Chain);
11330
11331     // If there is a better chain.
11332     if (Chain != BetterChain) {
11333       SDValue ReplStore;
11334
11335       // Replace the chain to avoid dependency.
11336       if (ST->isTruncatingStore()) {
11337         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11338                                       ST->getMemoryVT(), ST->getMemOperand());
11339       } else {
11340         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11341                                  ST->getMemOperand());
11342       }
11343
11344       // Create token to keep both nodes around.
11345       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11346                                   MVT::Other, Chain, ReplStore);
11347
11348       // Make sure the new and old chains are cleaned up.
11349       AddToWorklist(Token.getNode());
11350
11351       // Don't add users to work list.
11352       return CombineTo(N, Token, false);
11353     }
11354   }
11355
11356   // Try transforming N to an indexed store.
11357   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11358     return SDValue(N, 0);
11359
11360   // FIXME: is there such a thing as a truncating indexed store?
11361   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11362       Value.getValueType().isInteger()) {
11363     // See if we can simplify the input to this truncstore with knowledge that
11364     // only the low bits are being used.  For example:
11365     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11366     SDValue Shorter =
11367       GetDemandedBits(Value,
11368                       APInt::getLowBitsSet(
11369                         Value.getValueType().getScalarType().getSizeInBits(),
11370                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11371     AddToWorklist(Value.getNode());
11372     if (Shorter.getNode())
11373       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11374                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11375
11376     // Otherwise, see if we can simplify the operation with
11377     // SimplifyDemandedBits, which only works if the value has a single use.
11378     if (SimplifyDemandedBits(Value,
11379                         APInt::getLowBitsSet(
11380                           Value.getValueType().getScalarType().getSizeInBits(),
11381                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11382       return SDValue(N, 0);
11383   }
11384
11385   // If this is a load followed by a store to the same location, then the store
11386   // is dead/noop.
11387   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11388     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11389         ST->isUnindexed() && !ST->isVolatile() &&
11390         // There can't be any side effects between the load and store, such as
11391         // a call or store.
11392         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11393       // The store is dead, remove it.
11394       return Chain;
11395     }
11396   }
11397
11398   // If this is a store followed by a store with the same value to the same
11399   // location, then the store is dead/noop.
11400   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11401     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11402         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11403         ST1->isUnindexed() && !ST1->isVolatile()) {
11404       // The store is dead, remove it.
11405       return Chain;
11406     }
11407   }
11408
11409   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11410   // truncating store.  We can do this even if this is already a truncstore.
11411   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11412       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11413       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11414                             ST->getMemoryVT())) {
11415     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11416                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11417   }
11418
11419   // Only perform this optimization before the types are legal, because we
11420   // don't want to perform this optimization on every DAGCombine invocation.
11421   if (!LegalTypes) {
11422     bool EverChanged = false;
11423
11424     do {
11425       // There can be multiple store sequences on the same chain.
11426       // Keep trying to merge store sequences until we are unable to do so
11427       // or until we merge the last store on the chain.
11428       bool Changed = MergeConsecutiveStores(ST);
11429       EverChanged |= Changed;
11430       if (!Changed) break;
11431     } while (ST->getOpcode() != ISD::DELETED_NODE);
11432
11433     if (EverChanged)
11434       return SDValue(N, 0);
11435   }
11436
11437   return ReduceLoadOpStoreWidth(N);
11438 }
11439
11440 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11441   SDValue InVec = N->getOperand(0);
11442   SDValue InVal = N->getOperand(1);
11443   SDValue EltNo = N->getOperand(2);
11444   SDLoc dl(N);
11445
11446   // If the inserted element is an UNDEF, just use the input vector.
11447   if (InVal.getOpcode() == ISD::UNDEF)
11448     return InVec;
11449
11450   EVT VT = InVec.getValueType();
11451
11452   // If we can't generate a legal BUILD_VECTOR, exit
11453   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11454     return SDValue();
11455
11456   // Check that we know which element is being inserted
11457   if (!isa<ConstantSDNode>(EltNo))
11458     return SDValue();
11459   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11460
11461   // Canonicalize insert_vector_elt dag nodes.
11462   // Example:
11463   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11464   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11465   //
11466   // Do this only if the child insert_vector node has one use; also
11467   // do this only if indices are both constants and Idx1 < Idx0.
11468   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11469       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11470     unsigned OtherElt =
11471       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11472     if (Elt < OtherElt) {
11473       // Swap nodes.
11474       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11475                                   InVec.getOperand(0), InVal, EltNo);
11476       AddToWorklist(NewOp.getNode());
11477       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11478                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11479     }
11480   }
11481
11482   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11483   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11484   // vector elements.
11485   SmallVector<SDValue, 8> Ops;
11486   // Do not combine these two vectors if the output vector will not replace
11487   // the input vector.
11488   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11489     Ops.append(InVec.getNode()->op_begin(),
11490                InVec.getNode()->op_end());
11491   } else if (InVec.getOpcode() == ISD::UNDEF) {
11492     unsigned NElts = VT.getVectorNumElements();
11493     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11494   } else {
11495     return SDValue();
11496   }
11497
11498   // Insert the element
11499   if (Elt < Ops.size()) {
11500     // All the operands of BUILD_VECTOR must have the same type;
11501     // we enforce that here.
11502     EVT OpVT = Ops[0].getValueType();
11503     if (InVal.getValueType() != OpVT)
11504       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11505                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11506                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11507     Ops[Elt] = InVal;
11508   }
11509
11510   // Return the new vector
11511   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11512 }
11513
11514 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11515     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11516   EVT ResultVT = EVE->getValueType(0);
11517   EVT VecEltVT = InVecVT.getVectorElementType();
11518   unsigned Align = OriginalLoad->getAlignment();
11519   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11520       VecEltVT.getTypeForEVT(*DAG.getContext()));
11521
11522   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11523     return SDValue();
11524
11525   Align = NewAlign;
11526
11527   SDValue NewPtr = OriginalLoad->getBasePtr();
11528   SDValue Offset;
11529   EVT PtrType = NewPtr.getValueType();
11530   MachinePointerInfo MPI;
11531   SDLoc DL(EVE);
11532   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11533     int Elt = ConstEltNo->getZExtValue();
11534     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11535     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11536     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11537   } else {
11538     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11539     Offset = DAG.getNode(
11540         ISD::MUL, DL, PtrType, Offset,
11541         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11542     MPI = OriginalLoad->getPointerInfo();
11543   }
11544   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11545
11546   // The replacement we need to do here is a little tricky: we need to
11547   // replace an extractelement of a load with a load.
11548   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11549   // Note that this replacement assumes that the extractvalue is the only
11550   // use of the load; that's okay because we don't want to perform this
11551   // transformation in other cases anyway.
11552   SDValue Load;
11553   SDValue Chain;
11554   if (ResultVT.bitsGT(VecEltVT)) {
11555     // If the result type of vextract is wider than the load, then issue an
11556     // extending load instead.
11557     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11558                                                   VecEltVT)
11559                                    ? ISD::ZEXTLOAD
11560                                    : ISD::EXTLOAD;
11561     Load = DAG.getExtLoad(
11562         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11563         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11564         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11565     Chain = Load.getValue(1);
11566   } else {
11567     Load = DAG.getLoad(
11568         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11569         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11570         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11571     Chain = Load.getValue(1);
11572     if (ResultVT.bitsLT(VecEltVT))
11573       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11574     else
11575       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11576   }
11577   WorklistRemover DeadNodes(*this);
11578   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11579   SDValue To[] = { Load, Chain };
11580   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11581   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11582   // worklist explicitly as well.
11583   AddToWorklist(Load.getNode());
11584   AddUsersToWorklist(Load.getNode()); // Add users too
11585   // Make sure to revisit this node to clean it up; it will usually be dead.
11586   AddToWorklist(EVE);
11587   ++OpsNarrowed;
11588   return SDValue(EVE, 0);
11589 }
11590
11591 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11592   // (vextract (scalar_to_vector val, 0) -> val
11593   SDValue InVec = N->getOperand(0);
11594   EVT VT = InVec.getValueType();
11595   EVT NVT = N->getValueType(0);
11596
11597   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11598     // Check if the result type doesn't match the inserted element type. A
11599     // SCALAR_TO_VECTOR may truncate the inserted element and the
11600     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11601     SDValue InOp = InVec.getOperand(0);
11602     if (InOp.getValueType() != NVT) {
11603       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11604       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11605     }
11606     return InOp;
11607   }
11608
11609   SDValue EltNo = N->getOperand(1);
11610   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11611
11612   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11613   // We only perform this optimization before the op legalization phase because
11614   // we may introduce new vector instructions which are not backed by TD
11615   // patterns. For example on AVX, extracting elements from a wide vector
11616   // without using extract_subvector. However, if we can find an underlying
11617   // scalar value, then we can always use that.
11618   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11619       && ConstEltNo) {
11620     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11621     int NumElem = VT.getVectorNumElements();
11622     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11623     // Find the new index to extract from.
11624     int OrigElt = SVOp->getMaskElt(Elt);
11625
11626     // Extracting an undef index is undef.
11627     if (OrigElt == -1)
11628       return DAG.getUNDEF(NVT);
11629
11630     // Select the right vector half to extract from.
11631     SDValue SVInVec;
11632     if (OrigElt < NumElem) {
11633       SVInVec = InVec->getOperand(0);
11634     } else {
11635       SVInVec = InVec->getOperand(1);
11636       OrigElt -= NumElem;
11637     }
11638
11639     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11640       SDValue InOp = SVInVec.getOperand(OrigElt);
11641       if (InOp.getValueType() != NVT) {
11642         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11643         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11644       }
11645
11646       return InOp;
11647     }
11648
11649     // FIXME: We should handle recursing on other vector shuffles and
11650     // scalar_to_vector here as well.
11651
11652     if (!LegalOperations) {
11653       EVT IndexTy = TLI.getVectorIdxTy();
11654       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11655                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11656     }
11657   }
11658
11659   bool BCNumEltsChanged = false;
11660   EVT ExtVT = VT.getVectorElementType();
11661   EVT LVT = ExtVT;
11662
11663   // If the result of load has to be truncated, then it's not necessarily
11664   // profitable.
11665   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11666     return SDValue();
11667
11668   if (InVec.getOpcode() == ISD::BITCAST) {
11669     // Don't duplicate a load with other uses.
11670     if (!InVec.hasOneUse())
11671       return SDValue();
11672
11673     EVT BCVT = InVec.getOperand(0).getValueType();
11674     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11675       return SDValue();
11676     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11677       BCNumEltsChanged = true;
11678     InVec = InVec.getOperand(0);
11679     ExtVT = BCVT.getVectorElementType();
11680   }
11681
11682   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11683   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11684       ISD::isNormalLoad(InVec.getNode()) &&
11685       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11686     SDValue Index = N->getOperand(1);
11687     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11688       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11689                                                            OrigLoad);
11690   }
11691
11692   // Perform only after legalization to ensure build_vector / vector_shuffle
11693   // optimizations have already been done.
11694   if (!LegalOperations) return SDValue();
11695
11696   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11697   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11698   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11699
11700   if (ConstEltNo) {
11701     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11702
11703     LoadSDNode *LN0 = nullptr;
11704     const ShuffleVectorSDNode *SVN = nullptr;
11705     if (ISD::isNormalLoad(InVec.getNode())) {
11706       LN0 = cast<LoadSDNode>(InVec);
11707     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11708                InVec.getOperand(0).getValueType() == ExtVT &&
11709                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11710       // Don't duplicate a load with other uses.
11711       if (!InVec.hasOneUse())
11712         return SDValue();
11713
11714       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11715     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11716       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11717       // =>
11718       // (load $addr+1*size)
11719
11720       // Don't duplicate a load with other uses.
11721       if (!InVec.hasOneUse())
11722         return SDValue();
11723
11724       // If the bit convert changed the number of elements, it is unsafe
11725       // to examine the mask.
11726       if (BCNumEltsChanged)
11727         return SDValue();
11728
11729       // Select the input vector, guarding against out of range extract vector.
11730       unsigned NumElems = VT.getVectorNumElements();
11731       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11732       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11733
11734       if (InVec.getOpcode() == ISD::BITCAST) {
11735         // Don't duplicate a load with other uses.
11736         if (!InVec.hasOneUse())
11737           return SDValue();
11738
11739         InVec = InVec.getOperand(0);
11740       }
11741       if (ISD::isNormalLoad(InVec.getNode())) {
11742         LN0 = cast<LoadSDNode>(InVec);
11743         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11744         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11745       }
11746     }
11747
11748     // Make sure we found a non-volatile load and the extractelement is
11749     // the only use.
11750     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11751       return SDValue();
11752
11753     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11754     if (Elt == -1)
11755       return DAG.getUNDEF(LVT);
11756
11757     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11758   }
11759
11760   return SDValue();
11761 }
11762
11763 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11764 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11765   // We perform this optimization post type-legalization because
11766   // the type-legalizer often scalarizes integer-promoted vectors.
11767   // Performing this optimization before may create bit-casts which
11768   // will be type-legalized to complex code sequences.
11769   // We perform this optimization only before the operation legalizer because we
11770   // may introduce illegal operations.
11771   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11772     return SDValue();
11773
11774   unsigned NumInScalars = N->getNumOperands();
11775   SDLoc dl(N);
11776   EVT VT = N->getValueType(0);
11777
11778   // Check to see if this is a BUILD_VECTOR of a bunch of values
11779   // which come from any_extend or zero_extend nodes. If so, we can create
11780   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11781   // optimizations. We do not handle sign-extend because we can't fill the sign
11782   // using shuffles.
11783   EVT SourceType = MVT::Other;
11784   bool AllAnyExt = true;
11785
11786   for (unsigned i = 0; i != NumInScalars; ++i) {
11787     SDValue In = N->getOperand(i);
11788     // Ignore undef inputs.
11789     if (In.getOpcode() == ISD::UNDEF) continue;
11790
11791     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11792     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11793
11794     // Abort if the element is not an extension.
11795     if (!ZeroExt && !AnyExt) {
11796       SourceType = MVT::Other;
11797       break;
11798     }
11799
11800     // The input is a ZeroExt or AnyExt. Check the original type.
11801     EVT InTy = In.getOperand(0).getValueType();
11802
11803     // Check that all of the widened source types are the same.
11804     if (SourceType == MVT::Other)
11805       // First time.
11806       SourceType = InTy;
11807     else if (InTy != SourceType) {
11808       // Multiple income types. Abort.
11809       SourceType = MVT::Other;
11810       break;
11811     }
11812
11813     // Check if all of the extends are ANY_EXTENDs.
11814     AllAnyExt &= AnyExt;
11815   }
11816
11817   // In order to have valid types, all of the inputs must be extended from the
11818   // same source type and all of the inputs must be any or zero extend.
11819   // Scalar sizes must be a power of two.
11820   EVT OutScalarTy = VT.getScalarType();
11821   bool ValidTypes = SourceType != MVT::Other &&
11822                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11823                  isPowerOf2_32(SourceType.getSizeInBits());
11824
11825   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11826   // turn into a single shuffle instruction.
11827   if (!ValidTypes)
11828     return SDValue();
11829
11830   bool isLE = TLI.isLittleEndian();
11831   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11832   assert(ElemRatio > 1 && "Invalid element size ratio");
11833   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11834                                DAG.getConstant(0, SDLoc(N), SourceType);
11835
11836   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11837   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11838
11839   // Populate the new build_vector
11840   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11841     SDValue Cast = N->getOperand(i);
11842     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11843             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11844             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11845     SDValue In;
11846     if (Cast.getOpcode() == ISD::UNDEF)
11847       In = DAG.getUNDEF(SourceType);
11848     else
11849       In = Cast->getOperand(0);
11850     unsigned Index = isLE ? (i * ElemRatio) :
11851                             (i * ElemRatio + (ElemRatio - 1));
11852
11853     assert(Index < Ops.size() && "Invalid index");
11854     Ops[Index] = In;
11855   }
11856
11857   // The type of the new BUILD_VECTOR node.
11858   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11859   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11860          "Invalid vector size");
11861   // Check if the new vector type is legal.
11862   if (!isTypeLegal(VecVT)) return SDValue();
11863
11864   // Make the new BUILD_VECTOR.
11865   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11866
11867   // The new BUILD_VECTOR node has the potential to be further optimized.
11868   AddToWorklist(BV.getNode());
11869   // Bitcast to the desired type.
11870   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11871 }
11872
11873 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11874   EVT VT = N->getValueType(0);
11875
11876   unsigned NumInScalars = N->getNumOperands();
11877   SDLoc dl(N);
11878
11879   EVT SrcVT = MVT::Other;
11880   unsigned Opcode = ISD::DELETED_NODE;
11881   unsigned NumDefs = 0;
11882
11883   for (unsigned i = 0; i != NumInScalars; ++i) {
11884     SDValue In = N->getOperand(i);
11885     unsigned Opc = In.getOpcode();
11886
11887     if (Opc == ISD::UNDEF)
11888       continue;
11889
11890     // If all scalar values are floats and converted from integers.
11891     if (Opcode == ISD::DELETED_NODE &&
11892         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11893       Opcode = Opc;
11894     }
11895
11896     if (Opc != Opcode)
11897       return SDValue();
11898
11899     EVT InVT = In.getOperand(0).getValueType();
11900
11901     // If all scalar values are typed differently, bail out. It's chosen to
11902     // simplify BUILD_VECTOR of integer types.
11903     if (SrcVT == MVT::Other)
11904       SrcVT = InVT;
11905     if (SrcVT != InVT)
11906       return SDValue();
11907     NumDefs++;
11908   }
11909
11910   // If the vector has just one element defined, it's not worth to fold it into
11911   // a vectorized one.
11912   if (NumDefs < 2)
11913     return SDValue();
11914
11915   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11916          && "Should only handle conversion from integer to float.");
11917   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11918
11919   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11920
11921   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11922     return SDValue();
11923
11924   // Just because the floating-point vector type is legal does not necessarily
11925   // mean that the corresponding integer vector type is.
11926   if (!isTypeLegal(NVT))
11927     return SDValue();
11928
11929   SmallVector<SDValue, 8> Opnds;
11930   for (unsigned i = 0; i != NumInScalars; ++i) {
11931     SDValue In = N->getOperand(i);
11932
11933     if (In.getOpcode() == ISD::UNDEF)
11934       Opnds.push_back(DAG.getUNDEF(SrcVT));
11935     else
11936       Opnds.push_back(In.getOperand(0));
11937   }
11938   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11939   AddToWorklist(BV.getNode());
11940
11941   return DAG.getNode(Opcode, dl, VT, BV);
11942 }
11943
11944 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11945   unsigned NumInScalars = N->getNumOperands();
11946   SDLoc dl(N);
11947   EVT VT = N->getValueType(0);
11948
11949   // A vector built entirely of undefs is undef.
11950   if (ISD::allOperandsUndef(N))
11951     return DAG.getUNDEF(VT);
11952
11953   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11954     return V;
11955
11956   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11957     return V;
11958
11959   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11960   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11961   // at most two distinct vectors, turn this into a shuffle node.
11962
11963   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11964   if (!isTypeLegal(VT))
11965     return SDValue();
11966
11967   // May only combine to shuffle after legalize if shuffle is legal.
11968   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11969     return SDValue();
11970
11971   SDValue VecIn1, VecIn2;
11972   bool UsesZeroVector = false;
11973   for (unsigned i = 0; i != NumInScalars; ++i) {
11974     SDValue Op = N->getOperand(i);
11975     // Ignore undef inputs.
11976     if (Op.getOpcode() == ISD::UNDEF) continue;
11977
11978     // See if we can combine this build_vector into a blend with a zero vector.
11979     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
11980       UsesZeroVector = true;
11981       continue;
11982     }
11983
11984     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11985     // constant index, bail out.
11986     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11987         !isa<ConstantSDNode>(Op.getOperand(1))) {
11988       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11989       break;
11990     }
11991
11992     // We allow up to two distinct input vectors.
11993     SDValue ExtractedFromVec = Op.getOperand(0);
11994     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11995       continue;
11996
11997     if (!VecIn1.getNode()) {
11998       VecIn1 = ExtractedFromVec;
11999     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12000       VecIn2 = ExtractedFromVec;
12001     } else {
12002       // Too many inputs.
12003       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12004       break;
12005     }
12006   }
12007
12008   // If everything is good, we can make a shuffle operation.
12009   if (VecIn1.getNode()) {
12010     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12011     SmallVector<int, 8> Mask;
12012     for (unsigned i = 0; i != NumInScalars; ++i) {
12013       unsigned Opcode = N->getOperand(i).getOpcode();
12014       if (Opcode == ISD::UNDEF) {
12015         Mask.push_back(-1);
12016         continue;
12017       }
12018
12019       // Operands can also be zero.
12020       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12021         assert(UsesZeroVector &&
12022                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12023                "Unexpected node found!");
12024         Mask.push_back(NumInScalars+i);
12025         continue;
12026       }
12027
12028       // If extracting from the first vector, just use the index directly.
12029       SDValue Extract = N->getOperand(i);
12030       SDValue ExtVal = Extract.getOperand(1);
12031       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12032       if (Extract.getOperand(0) == VecIn1) {
12033         Mask.push_back(ExtIndex);
12034         continue;
12035       }
12036
12037       // Otherwise, use InIdx + InputVecSize
12038       Mask.push_back(InNumElements + ExtIndex);
12039     }
12040
12041     // Avoid introducing illegal shuffles with zero.
12042     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12043       return SDValue();
12044
12045     // We can't generate a shuffle node with mismatched input and output types.
12046     // Attempt to transform a single input vector to the correct type.
12047     if ((VT != VecIn1.getValueType())) {
12048       // If the input vector type has a different base type to the output
12049       // vector type, bail out.
12050       EVT VTElemType = VT.getVectorElementType();
12051       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12052           (VecIn2.getNode() &&
12053            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12054         return SDValue();
12055
12056       // If the input vector is too small, widen it.
12057       // We only support widening of vectors which are half the size of the
12058       // output registers. For example XMM->YMM widening on X86 with AVX.
12059       EVT VecInT = VecIn1.getValueType();
12060       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12061         // If we only have one small input, widen it by adding undef values.
12062         if (!VecIn2.getNode())
12063           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12064                                DAG.getUNDEF(VecIn1.getValueType()));
12065         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12066           // If we have two small inputs of the same type, try to concat them.
12067           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12068           VecIn2 = SDValue(nullptr, 0);
12069         } else
12070           return SDValue();
12071       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12072         // If the input vector is too large, try to split it.
12073         // We don't support having two input vectors that are too large.
12074         // If the zero vector was used, we can not split the vector,
12075         // since we'd need 3 inputs.
12076         if (UsesZeroVector || VecIn2.getNode())
12077           return SDValue();
12078
12079         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12080           return SDValue();
12081
12082         // Try to replace VecIn1 with two extract_subvectors
12083         // No need to update the masks, they should still be correct.
12084         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12085           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
12086         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12087           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
12088       } else
12089         return SDValue();
12090     }
12091
12092     if (UsesZeroVector)
12093       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12094                                 DAG.getConstantFP(0.0, dl, VT);
12095     else
12096       // If VecIn2 is unused then change it to undef.
12097       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12098
12099     // Check that we were able to transform all incoming values to the same
12100     // type.
12101     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12102         VecIn1.getValueType() != VT)
12103           return SDValue();
12104
12105     // Return the new VECTOR_SHUFFLE node.
12106     SDValue Ops[2];
12107     Ops[0] = VecIn1;
12108     Ops[1] = VecIn2;
12109     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12110   }
12111
12112   return SDValue();
12113 }
12114
12115 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12116   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12117   EVT OpVT = N->getOperand(0).getValueType();
12118
12119   // If the operands are legal vectors, leave them alone.
12120   if (TLI.isTypeLegal(OpVT))
12121     return SDValue();
12122
12123   SDLoc DL(N);
12124   EVT VT = N->getValueType(0);
12125   SmallVector<SDValue, 8> Ops;
12126
12127   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12128   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12129
12130   // Keep track of what we encounter.
12131   bool AnyInteger = false;
12132   bool AnyFP = false;
12133   for (const SDValue &Op : N->ops()) {
12134     if (ISD::BITCAST == Op.getOpcode() &&
12135         !Op.getOperand(0).getValueType().isVector())
12136       Ops.push_back(Op.getOperand(0));
12137     else if (ISD::UNDEF == Op.getOpcode())
12138       Ops.push_back(ScalarUndef);
12139     else
12140       return SDValue();
12141
12142     // Note whether we encounter an integer or floating point scalar.
12143     // If it's neither, bail out, it could be something weird like x86mmx.
12144     EVT LastOpVT = Ops.back().getValueType();
12145     if (LastOpVT.isFloatingPoint())
12146       AnyFP = true;
12147     else if (LastOpVT.isInteger())
12148       AnyInteger = true;
12149     else
12150       return SDValue();
12151   }
12152
12153   // If any of the operands is a floating point scalar bitcast to a vector,
12154   // use floating point types throughout, and bitcast everything.
12155   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12156   if (AnyFP) {
12157     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12158     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12159     if (AnyInteger) {
12160       for (SDValue &Op : Ops) {
12161         if (Op.getValueType() == SVT)
12162           continue;
12163         if (Op.getOpcode() == ISD::UNDEF)
12164           Op = ScalarUndef;
12165         else
12166           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12167       }
12168     }
12169   }
12170
12171   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12172                                VT.getSizeInBits() / SVT.getSizeInBits());
12173   return DAG.getNode(ISD::BITCAST, DL, VT,
12174                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12175 }
12176
12177 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12178   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12179   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12180   // inputs come from at most two distinct vectors, turn this into a shuffle
12181   // node.
12182
12183   // If we only have one input vector, we don't need to do any concatenation.
12184   if (N->getNumOperands() == 1)
12185     return N->getOperand(0);
12186
12187   // Check if all of the operands are undefs.
12188   EVT VT = N->getValueType(0);
12189   if (ISD::allOperandsUndef(N))
12190     return DAG.getUNDEF(VT);
12191
12192   // Optimize concat_vectors where all but the first of the vectors are undef.
12193   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12194         return Op.getOpcode() == ISD::UNDEF;
12195       })) {
12196     SDValue In = N->getOperand(0);
12197     assert(In.getValueType().isVector() && "Must concat vectors");
12198
12199     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12200     if (In->getOpcode() == ISD::BITCAST &&
12201         !In->getOperand(0)->getValueType(0).isVector()) {
12202       SDValue Scalar = In->getOperand(0);
12203
12204       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12205       // look through the trunc so we can still do the transform:
12206       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12207       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12208           !TLI.isTypeLegal(Scalar.getValueType()) &&
12209           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12210         Scalar = Scalar->getOperand(0);
12211
12212       EVT SclTy = Scalar->getValueType(0);
12213
12214       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12215         return SDValue();
12216
12217       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12218                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12219       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12220         return SDValue();
12221
12222       SDLoc dl = SDLoc(N);
12223       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12224       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12225     }
12226   }
12227
12228   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12229   // We have already tested above for an UNDEF only concatenation.
12230   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12231   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12232   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12233     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12234   };
12235   bool AllBuildVectorsOrUndefs =
12236       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12237   if (AllBuildVectorsOrUndefs) {
12238     SmallVector<SDValue, 8> Opnds;
12239     EVT SVT = VT.getScalarType();
12240
12241     EVT MinVT = SVT;
12242     if (!SVT.isFloatingPoint()) {
12243       // If BUILD_VECTOR are from built from integer, they may have different
12244       // operand types. Get the smallest type and truncate all operands to it.
12245       bool FoundMinVT = false;
12246       for (const SDValue &Op : N->ops())
12247         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12248           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12249           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12250           FoundMinVT = true;
12251         }
12252       assert(FoundMinVT && "Concat vector type mismatch");
12253     }
12254
12255     for (const SDValue &Op : N->ops()) {
12256       EVT OpVT = Op.getValueType();
12257       unsigned NumElts = OpVT.getVectorNumElements();
12258
12259       if (ISD::UNDEF == Op.getOpcode())
12260         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12261
12262       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12263         if (SVT.isFloatingPoint()) {
12264           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12265           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12266         } else {
12267           for (unsigned i = 0; i != NumElts; ++i)
12268             Opnds.push_back(
12269                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12270         }
12271       }
12272     }
12273
12274     assert(VT.getVectorNumElements() == Opnds.size() &&
12275            "Concat vector type mismatch");
12276     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12277   }
12278
12279   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12280   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12281     return V;
12282
12283   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12284   // nodes often generate nop CONCAT_VECTOR nodes.
12285   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12286   // place the incoming vectors at the exact same location.
12287   SDValue SingleSource = SDValue();
12288   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12289
12290   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12291     SDValue Op = N->getOperand(i);
12292
12293     if (Op.getOpcode() == ISD::UNDEF)
12294       continue;
12295
12296     // Check if this is the identity extract:
12297     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12298       return SDValue();
12299
12300     // Find the single incoming vector for the extract_subvector.
12301     if (SingleSource.getNode()) {
12302       if (Op.getOperand(0) != SingleSource)
12303         return SDValue();
12304     } else {
12305       SingleSource = Op.getOperand(0);
12306
12307       // Check the source type is the same as the type of the result.
12308       // If not, this concat may extend the vector, so we can not
12309       // optimize it away.
12310       if (SingleSource.getValueType() != N->getValueType(0))
12311         return SDValue();
12312     }
12313
12314     unsigned IdentityIndex = i * PartNumElem;
12315     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12316     // The extract index must be constant.
12317     if (!CS)
12318       return SDValue();
12319
12320     // Check that we are reading from the identity index.
12321     if (CS->getZExtValue() != IdentityIndex)
12322       return SDValue();
12323   }
12324
12325   if (SingleSource.getNode())
12326     return SingleSource;
12327
12328   return SDValue();
12329 }
12330
12331 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12332   EVT NVT = N->getValueType(0);
12333   SDValue V = N->getOperand(0);
12334
12335   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12336     // Combine:
12337     //    (extract_subvec (concat V1, V2, ...), i)
12338     // Into:
12339     //    Vi if possible
12340     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12341     // type.
12342     if (V->getOperand(0).getValueType() != NVT)
12343       return SDValue();
12344     unsigned Idx = N->getConstantOperandVal(1);
12345     unsigned NumElems = NVT.getVectorNumElements();
12346     assert((Idx % NumElems) == 0 &&
12347            "IDX in concat is not a multiple of the result vector length.");
12348     return V->getOperand(Idx / NumElems);
12349   }
12350
12351   // Skip bitcasting
12352   if (V->getOpcode() == ISD::BITCAST)
12353     V = V.getOperand(0);
12354
12355   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12356     SDLoc dl(N);
12357     // Handle only simple case where vector being inserted and vector
12358     // being extracted are of same type, and are half size of larger vectors.
12359     EVT BigVT = V->getOperand(0).getValueType();
12360     EVT SmallVT = V->getOperand(1).getValueType();
12361     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12362       return SDValue();
12363
12364     // Only handle cases where both indexes are constants with the same type.
12365     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12366     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12367
12368     if (InsIdx && ExtIdx &&
12369         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12370         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12371       // Combine:
12372       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12373       // Into:
12374       //    indices are equal or bit offsets are equal => V1
12375       //    otherwise => (extract_subvec V1, ExtIdx)
12376       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12377           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12378         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12379       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12380                          DAG.getNode(ISD::BITCAST, dl,
12381                                      N->getOperand(0).getValueType(),
12382                                      V->getOperand(0)), N->getOperand(1));
12383     }
12384   }
12385
12386   return SDValue();
12387 }
12388
12389 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12390                                                  SDValue V, SelectionDAG &DAG) {
12391   SDLoc DL(V);
12392   EVT VT = V.getValueType();
12393
12394   switch (V.getOpcode()) {
12395   default:
12396     return V;
12397
12398   case ISD::CONCAT_VECTORS: {
12399     EVT OpVT = V->getOperand(0).getValueType();
12400     int OpSize = OpVT.getVectorNumElements();
12401     SmallBitVector OpUsedElements(OpSize, false);
12402     bool FoundSimplification = false;
12403     SmallVector<SDValue, 4> NewOps;
12404     NewOps.reserve(V->getNumOperands());
12405     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12406       SDValue Op = V->getOperand(i);
12407       bool OpUsed = false;
12408       for (int j = 0; j < OpSize; ++j)
12409         if (UsedElements[i * OpSize + j]) {
12410           OpUsedElements[j] = true;
12411           OpUsed = true;
12412         }
12413       NewOps.push_back(
12414           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12415                  : DAG.getUNDEF(OpVT));
12416       FoundSimplification |= Op == NewOps.back();
12417       OpUsedElements.reset();
12418     }
12419     if (FoundSimplification)
12420       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12421     return V;
12422   }
12423
12424   case ISD::INSERT_SUBVECTOR: {
12425     SDValue BaseV = V->getOperand(0);
12426     SDValue SubV = V->getOperand(1);
12427     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12428     if (!IdxN)
12429       return V;
12430
12431     int SubSize = SubV.getValueType().getVectorNumElements();
12432     int Idx = IdxN->getZExtValue();
12433     bool SubVectorUsed = false;
12434     SmallBitVector SubUsedElements(SubSize, false);
12435     for (int i = 0; i < SubSize; ++i)
12436       if (UsedElements[i + Idx]) {
12437         SubVectorUsed = true;
12438         SubUsedElements[i] = true;
12439         UsedElements[i + Idx] = false;
12440       }
12441
12442     // Now recurse on both the base and sub vectors.
12443     SDValue SimplifiedSubV =
12444         SubVectorUsed
12445             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12446             : DAG.getUNDEF(SubV.getValueType());
12447     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12448     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12449       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12450                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12451     return V;
12452   }
12453   }
12454 }
12455
12456 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12457                                        SDValue N1, SelectionDAG &DAG) {
12458   EVT VT = SVN->getValueType(0);
12459   int NumElts = VT.getVectorNumElements();
12460   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12461   for (int M : SVN->getMask())
12462     if (M >= 0 && M < NumElts)
12463       N0UsedElements[M] = true;
12464     else if (M >= NumElts)
12465       N1UsedElements[M - NumElts] = true;
12466
12467   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12468   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12469   if (S0 == N0 && S1 == N1)
12470     return SDValue();
12471
12472   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12473 }
12474
12475 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12476 // or turn a shuffle of a single concat into simpler shuffle then concat.
12477 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12478   EVT VT = N->getValueType(0);
12479   unsigned NumElts = VT.getVectorNumElements();
12480
12481   SDValue N0 = N->getOperand(0);
12482   SDValue N1 = N->getOperand(1);
12483   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12484
12485   SmallVector<SDValue, 4> Ops;
12486   EVT ConcatVT = N0.getOperand(0).getValueType();
12487   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12488   unsigned NumConcats = NumElts / NumElemsPerConcat;
12489
12490   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12491   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12492   // half vector elements.
12493   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12494       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12495                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12496     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12497                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12498     N1 = DAG.getUNDEF(ConcatVT);
12499     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12500   }
12501
12502   // Look at every vector that's inserted. We're looking for exact
12503   // subvector-sized copies from a concatenated vector
12504   for (unsigned I = 0; I != NumConcats; ++I) {
12505     // Make sure we're dealing with a copy.
12506     unsigned Begin = I * NumElemsPerConcat;
12507     bool AllUndef = true, NoUndef = true;
12508     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12509       if (SVN->getMaskElt(J) >= 0)
12510         AllUndef = false;
12511       else
12512         NoUndef = false;
12513     }
12514
12515     if (NoUndef) {
12516       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12517         return SDValue();
12518
12519       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12520         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12521           return SDValue();
12522
12523       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12524       if (FirstElt < N0.getNumOperands())
12525         Ops.push_back(N0.getOperand(FirstElt));
12526       else
12527         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12528
12529     } else if (AllUndef) {
12530       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12531     } else { // Mixed with general masks and undefs, can't do optimization.
12532       return SDValue();
12533     }
12534   }
12535
12536   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12537 }
12538
12539 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12540   EVT VT = N->getValueType(0);
12541   unsigned NumElts = VT.getVectorNumElements();
12542
12543   SDValue N0 = N->getOperand(0);
12544   SDValue N1 = N->getOperand(1);
12545
12546   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12547
12548   // Canonicalize shuffle undef, undef -> undef
12549   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12550     return DAG.getUNDEF(VT);
12551
12552   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12553
12554   // Canonicalize shuffle v, v -> v, undef
12555   if (N0 == N1) {
12556     SmallVector<int, 8> NewMask;
12557     for (unsigned i = 0; i != NumElts; ++i) {
12558       int Idx = SVN->getMaskElt(i);
12559       if (Idx >= (int)NumElts) Idx -= NumElts;
12560       NewMask.push_back(Idx);
12561     }
12562     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12563                                 &NewMask[0]);
12564   }
12565
12566   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12567   if (N0.getOpcode() == ISD::UNDEF) {
12568     SmallVector<int, 8> NewMask;
12569     for (unsigned i = 0; i != NumElts; ++i) {
12570       int Idx = SVN->getMaskElt(i);
12571       if (Idx >= 0) {
12572         if (Idx >= (int)NumElts)
12573           Idx -= NumElts;
12574         else
12575           Idx = -1; // remove reference to lhs
12576       }
12577       NewMask.push_back(Idx);
12578     }
12579     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12580                                 &NewMask[0]);
12581   }
12582
12583   // Remove references to rhs if it is undef
12584   if (N1.getOpcode() == ISD::UNDEF) {
12585     bool Changed = false;
12586     SmallVector<int, 8> NewMask;
12587     for (unsigned i = 0; i != NumElts; ++i) {
12588       int Idx = SVN->getMaskElt(i);
12589       if (Idx >= (int)NumElts) {
12590         Idx = -1;
12591         Changed = true;
12592       }
12593       NewMask.push_back(Idx);
12594     }
12595     if (Changed)
12596       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12597   }
12598
12599   // If it is a splat, check if the argument vector is another splat or a
12600   // build_vector.
12601   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12602     SDNode *V = N0.getNode();
12603
12604     // If this is a bit convert that changes the element type of the vector but
12605     // not the number of vector elements, look through it.  Be careful not to
12606     // look though conversions that change things like v4f32 to v2f64.
12607     if (V->getOpcode() == ISD::BITCAST) {
12608       SDValue ConvInput = V->getOperand(0);
12609       if (ConvInput.getValueType().isVector() &&
12610           ConvInput.getValueType().getVectorNumElements() == NumElts)
12611         V = ConvInput.getNode();
12612     }
12613
12614     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12615       assert(V->getNumOperands() == NumElts &&
12616              "BUILD_VECTOR has wrong number of operands");
12617       SDValue Base;
12618       bool AllSame = true;
12619       for (unsigned i = 0; i != NumElts; ++i) {
12620         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12621           Base = V->getOperand(i);
12622           break;
12623         }
12624       }
12625       // Splat of <u, u, u, u>, return <u, u, u, u>
12626       if (!Base.getNode())
12627         return N0;
12628       for (unsigned i = 0; i != NumElts; ++i) {
12629         if (V->getOperand(i) != Base) {
12630           AllSame = false;
12631           break;
12632         }
12633       }
12634       // Splat of <x, x, x, x>, return <x, x, x, x>
12635       if (AllSame)
12636         return N0;
12637
12638       // Canonicalize any other splat as a build_vector.
12639       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12640       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12641       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12642                                   V->getValueType(0), Ops);
12643
12644       // We may have jumped through bitcasts, so the type of the
12645       // BUILD_VECTOR may not match the type of the shuffle.
12646       if (V->getValueType(0) != VT)
12647         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12648       return NewBV;
12649     }
12650   }
12651
12652   // There are various patterns used to build up a vector from smaller vectors,
12653   // subvectors, or elements. Scan chains of these and replace unused insertions
12654   // or components with undef.
12655   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12656     return S;
12657
12658   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12659       Level < AfterLegalizeVectorOps &&
12660       (N1.getOpcode() == ISD::UNDEF ||
12661       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12662        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12663     SDValue V = partitionShuffleOfConcats(N, DAG);
12664
12665     if (V.getNode())
12666       return V;
12667   }
12668
12669   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12670   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12671   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12672     SmallVector<SDValue, 8> Ops;
12673     for (int M : SVN->getMask()) {
12674       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12675       if (M >= 0) {
12676         int Idx = M % NumElts;
12677         SDValue &S = (M < (int)NumElts ? N0 : N1);
12678         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12679           Op = S.getOperand(Idx);
12680         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12681           if (Idx == 0)
12682             Op = S.getOperand(0);
12683         } else {
12684           // Operand can't be combined - bail out.
12685           break;
12686         }
12687       }
12688       Ops.push_back(Op);
12689     }
12690     if (Ops.size() == VT.getVectorNumElements()) {
12691       // BUILD_VECTOR requires all inputs to be of the same type, find the
12692       // maximum type and extend them all.
12693       EVT SVT = VT.getScalarType();
12694       if (SVT.isInteger())
12695         for (SDValue &Op : Ops)
12696           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12697       if (SVT != VT.getScalarType())
12698         for (SDValue &Op : Ops)
12699           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12700                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12701                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12702       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12703     }
12704   }
12705
12706   // If this shuffle only has a single input that is a bitcasted shuffle,
12707   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12708   // back to their original types.
12709   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12710       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12711       TLI.isTypeLegal(VT)) {
12712
12713     // Peek through the bitcast only if there is one user.
12714     SDValue BC0 = N0;
12715     while (BC0.getOpcode() == ISD::BITCAST) {
12716       if (!BC0.hasOneUse())
12717         break;
12718       BC0 = BC0.getOperand(0);
12719     }
12720
12721     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12722       if (Scale == 1)
12723         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12724
12725       SmallVector<int, 8> NewMask;
12726       for (int M : Mask)
12727         for (int s = 0; s != Scale; ++s)
12728           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12729       return NewMask;
12730     };
12731
12732     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12733       EVT SVT = VT.getScalarType();
12734       EVT InnerVT = BC0->getValueType(0);
12735       EVT InnerSVT = InnerVT.getScalarType();
12736
12737       // Determine which shuffle works with the smaller scalar type.
12738       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12739       EVT ScaleSVT = ScaleVT.getScalarType();
12740
12741       if (TLI.isTypeLegal(ScaleVT) &&
12742           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12743           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12744
12745         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12746         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12747
12748         // Scale the shuffle masks to the smaller scalar type.
12749         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12750         SmallVector<int, 8> InnerMask =
12751             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12752         SmallVector<int, 8> OuterMask =
12753             ScaleShuffleMask(SVN->getMask(), OuterScale);
12754
12755         // Merge the shuffle masks.
12756         SmallVector<int, 8> NewMask;
12757         for (int M : OuterMask)
12758           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12759
12760         // Test for shuffle mask legality over both commutations.
12761         SDValue SV0 = BC0->getOperand(0);
12762         SDValue SV1 = BC0->getOperand(1);
12763         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12764         if (!LegalMask) {
12765           std::swap(SV0, SV1);
12766           ShuffleVectorSDNode::commuteMask(NewMask);
12767           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12768         }
12769
12770         if (LegalMask) {
12771           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12772           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12773           return DAG.getNode(
12774               ISD::BITCAST, SDLoc(N), VT,
12775               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12776         }
12777       }
12778     }
12779   }
12780
12781   // Canonicalize shuffles according to rules:
12782   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12783   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12784   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12785   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12786       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12787       TLI.isTypeLegal(VT)) {
12788     // The incoming shuffle must be of the same type as the result of the
12789     // current shuffle.
12790     assert(N1->getOperand(0).getValueType() == VT &&
12791            "Shuffle types don't match");
12792
12793     SDValue SV0 = N1->getOperand(0);
12794     SDValue SV1 = N1->getOperand(1);
12795     bool HasSameOp0 = N0 == SV0;
12796     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12797     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12798       // Commute the operands of this shuffle so that next rule
12799       // will trigger.
12800       return DAG.getCommutedVectorShuffle(*SVN);
12801   }
12802
12803   // Try to fold according to rules:
12804   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12805   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12806   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12807   // Don't try to fold shuffles with illegal type.
12808   // Only fold if this shuffle is the only user of the other shuffle.
12809   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12810       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12811     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12812
12813     // The incoming shuffle must be of the same type as the result of the
12814     // current shuffle.
12815     assert(OtherSV->getOperand(0).getValueType() == VT &&
12816            "Shuffle types don't match");
12817
12818     SDValue SV0, SV1;
12819     SmallVector<int, 4> Mask;
12820     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12821     // operand, and SV1 as the second operand.
12822     for (unsigned i = 0; i != NumElts; ++i) {
12823       int Idx = SVN->getMaskElt(i);
12824       if (Idx < 0) {
12825         // Propagate Undef.
12826         Mask.push_back(Idx);
12827         continue;
12828       }
12829
12830       SDValue CurrentVec;
12831       if (Idx < (int)NumElts) {
12832         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12833         // shuffle mask to identify which vector is actually referenced.
12834         Idx = OtherSV->getMaskElt(Idx);
12835         if (Idx < 0) {
12836           // Propagate Undef.
12837           Mask.push_back(Idx);
12838           continue;
12839         }
12840
12841         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12842                                            : OtherSV->getOperand(1);
12843       } else {
12844         // This shuffle index references an element within N1.
12845         CurrentVec = N1;
12846       }
12847
12848       // Simple case where 'CurrentVec' is UNDEF.
12849       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12850         Mask.push_back(-1);
12851         continue;
12852       }
12853
12854       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12855       // will be the first or second operand of the combined shuffle.
12856       Idx = Idx % NumElts;
12857       if (!SV0.getNode() || SV0 == CurrentVec) {
12858         // Ok. CurrentVec is the left hand side.
12859         // Update the mask accordingly.
12860         SV0 = CurrentVec;
12861         Mask.push_back(Idx);
12862         continue;
12863       }
12864
12865       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12866       if (SV1.getNode() && SV1 != CurrentVec)
12867         return SDValue();
12868
12869       // Ok. CurrentVec is the right hand side.
12870       // Update the mask accordingly.
12871       SV1 = CurrentVec;
12872       Mask.push_back(Idx + NumElts);
12873     }
12874
12875     // Check if all indices in Mask are Undef. In case, propagate Undef.
12876     bool isUndefMask = true;
12877     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12878       isUndefMask &= Mask[i] < 0;
12879
12880     if (isUndefMask)
12881       return DAG.getUNDEF(VT);
12882
12883     if (!SV0.getNode())
12884       SV0 = DAG.getUNDEF(VT);
12885     if (!SV1.getNode())
12886       SV1 = DAG.getUNDEF(VT);
12887
12888     // Avoid introducing shuffles with illegal mask.
12889     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12890       ShuffleVectorSDNode::commuteMask(Mask);
12891
12892       if (!TLI.isShuffleMaskLegal(Mask, VT))
12893         return SDValue();
12894
12895       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12896       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12897       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12898       std::swap(SV0, SV1);
12899     }
12900
12901     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12902     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12903     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12904     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12905   }
12906
12907   return SDValue();
12908 }
12909
12910 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12911   SDValue InVal = N->getOperand(0);
12912   EVT VT = N->getValueType(0);
12913
12914   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12915   // with a VECTOR_SHUFFLE.
12916   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12917     SDValue InVec = InVal->getOperand(0);
12918     SDValue EltNo = InVal->getOperand(1);
12919
12920     // FIXME: We could support implicit truncation if the shuffle can be
12921     // scaled to a smaller vector scalar type.
12922     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12923     if (C0 && VT == InVec.getValueType() &&
12924         VT.getScalarType() == InVal.getValueType()) {
12925       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12926       int Elt = C0->getZExtValue();
12927       NewMask[0] = Elt;
12928
12929       if (TLI.isShuffleMaskLegal(NewMask, VT))
12930         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12931                                     NewMask);
12932     }
12933   }
12934
12935   return SDValue();
12936 }
12937
12938 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12939   SDValue N0 = N->getOperand(0);
12940   SDValue N2 = N->getOperand(2);
12941
12942   // If the input vector is a concatenation, and the insert replaces
12943   // one of the halves, we can optimize into a single concat_vectors.
12944   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12945       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12946     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12947     EVT VT = N->getValueType(0);
12948
12949     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12950     // (concat_vectors Z, Y)
12951     if (InsIdx == 0)
12952       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12953                          N->getOperand(1), N0.getOperand(1));
12954
12955     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12956     // (concat_vectors X, Z)
12957     if (InsIdx == VT.getVectorNumElements()/2)
12958       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12959                          N0.getOperand(0), N->getOperand(1));
12960   }
12961
12962   return SDValue();
12963 }
12964
12965 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12966   SDValue N0 = N->getOperand(0);
12967
12968   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12969   if (N0->getOpcode() == ISD::FP16_TO_FP)
12970     return N0->getOperand(0);
12971
12972   return SDValue();
12973 }
12974
12975 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12976 /// with the destination vector and a zero vector.
12977 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12978 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12979 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12980   EVT VT = N->getValueType(0);
12981   SDValue LHS = N->getOperand(0);
12982   SDValue RHS = N->getOperand(1);
12983   SDLoc dl(N);
12984
12985   // Make sure we're not running after operation legalization where it
12986   // may have custom lowered the vector shuffles.
12987   if (LegalOperations)
12988     return SDValue();
12989
12990   if (N->getOpcode() != ISD::AND)
12991     return SDValue();
12992
12993   if (RHS.getOpcode() == ISD::BITCAST)
12994     RHS = RHS.getOperand(0);
12995
12996   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12997     SmallVector<int, 8> Indices;
12998     unsigned NumElts = RHS.getNumOperands();
12999
13000     for (unsigned i = 0; i != NumElts; ++i) {
13001       SDValue Elt = RHS.getOperand(i);
13002       if (isAllOnesConstant(Elt))
13003         Indices.push_back(i);
13004       else if (isNullConstant(Elt))
13005         Indices.push_back(NumElts+i);
13006       else
13007         return SDValue();
13008     }
13009
13010     // Let's see if the target supports this vector_shuffle.
13011     EVT RVT = RHS.getValueType();
13012     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
13013       return SDValue();
13014
13015     // Return the new VECTOR_SHUFFLE node.
13016     EVT EltVT = RVT.getVectorElementType();
13017     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
13018                                    DAG.getConstant(0, dl, EltVT));
13019     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
13020     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
13021     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
13022     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
13023   }
13024
13025   return SDValue();
13026 }
13027
13028 /// Visit a binary vector operation, like ADD.
13029 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13030   assert(N->getValueType(0).isVector() &&
13031          "SimplifyVBinOp only works on vectors!");
13032
13033   SDValue LHS = N->getOperand(0);
13034   SDValue RHS = N->getOperand(1);
13035
13036   if (SDValue Shuffle = XformToShuffleWithZero(N))
13037     return Shuffle;
13038
13039   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13040   // this operation.
13041   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13042       RHS.getOpcode() == ISD::BUILD_VECTOR) {
13043     // Check if both vectors are constants. If not bail out.
13044     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13045           cast<BuildVectorSDNode>(RHS)->isConstant()))
13046       return SDValue();
13047
13048     SmallVector<SDValue, 8> Ops;
13049     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13050       SDValue LHSOp = LHS.getOperand(i);
13051       SDValue RHSOp = RHS.getOperand(i);
13052
13053       // Can't fold divide by zero.
13054       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13055           N->getOpcode() == ISD::FDIV) {
13056         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13057              cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13058           break;
13059       }
13060
13061       EVT VT = LHSOp.getValueType();
13062       EVT RVT = RHSOp.getValueType();
13063       if (RVT != VT) {
13064         // Integer BUILD_VECTOR operands may have types larger than the element
13065         // size (e.g., when the element type is not legal).  Prior to type
13066         // legalization, the types may not match between the two BUILD_VECTORS.
13067         // Truncate one of the operands to make them match.
13068         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13069           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13070         } else {
13071           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13072           VT = RVT;
13073         }
13074       }
13075       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13076                                    LHSOp, RHSOp);
13077       if (FoldOp.getOpcode() != ISD::UNDEF &&
13078           FoldOp.getOpcode() != ISD::Constant &&
13079           FoldOp.getOpcode() != ISD::ConstantFP)
13080         break;
13081       Ops.push_back(FoldOp);
13082       AddToWorklist(FoldOp.getNode());
13083     }
13084
13085     if (Ops.size() == LHS.getNumOperands())
13086       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13087   }
13088
13089   // Type legalization might introduce new shuffles in the DAG.
13090   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13091   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13092   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13093       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13094       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13095       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13096     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13097     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13098
13099     if (SVN0->getMask().equals(SVN1->getMask())) {
13100       EVT VT = N->getValueType(0);
13101       SDValue UndefVector = LHS.getOperand(1);
13102       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13103                                      LHS.getOperand(0), RHS.getOperand(0));
13104       AddUsersToWorklist(N);
13105       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13106                                   &SVN0->getMask()[0]);
13107     }
13108   }
13109
13110   return SDValue();
13111 }
13112
13113 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13114                                     SDValue N1, SDValue N2){
13115   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13116
13117   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13118                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13119
13120   // If we got a simplified select_cc node back from SimplifySelectCC, then
13121   // break it down into a new SETCC node, and a new SELECT node, and then return
13122   // the SELECT node, since we were called with a SELECT node.
13123   if (SCC.getNode()) {
13124     // Check to see if we got a select_cc back (to turn into setcc/select).
13125     // Otherwise, just return whatever node we got back, like fabs.
13126     if (SCC.getOpcode() == ISD::SELECT_CC) {
13127       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13128                                   N0.getValueType(),
13129                                   SCC.getOperand(0), SCC.getOperand(1),
13130                                   SCC.getOperand(4));
13131       AddToWorklist(SETCC.getNode());
13132       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13133                            SCC.getOperand(2), SCC.getOperand(3));
13134     }
13135
13136     return SCC;
13137   }
13138   return SDValue();
13139 }
13140
13141 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13142 /// being selected between, see if we can simplify the select.  Callers of this
13143 /// should assume that TheSelect is deleted if this returns true.  As such, they
13144 /// should return the appropriate thing (e.g. the node) back to the top-level of
13145 /// the DAG combiner loop to avoid it being looked at.
13146 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13147                                     SDValue RHS) {
13148
13149   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13150   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13151   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13152     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13153       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13154       SDValue Sqrt = RHS;
13155       ISD::CondCode CC;
13156       SDValue CmpLHS;
13157       const ConstantFPSDNode *NegZero = nullptr;
13158
13159       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13160         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13161         CmpLHS = TheSelect->getOperand(0);
13162         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13163       } else {
13164         // SELECT or VSELECT
13165         SDValue Cmp = TheSelect->getOperand(0);
13166         if (Cmp.getOpcode() == ISD::SETCC) {
13167           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13168           CmpLHS = Cmp.getOperand(0);
13169           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13170         }
13171       }
13172       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13173           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13174           CC == ISD::SETULT || CC == ISD::SETLT)) {
13175         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13176         CombineTo(TheSelect, Sqrt);
13177         return true;
13178       }
13179     }
13180   }
13181   // Cannot simplify select with vector condition
13182   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13183
13184   // If this is a select from two identical things, try to pull the operation
13185   // through the select.
13186   if (LHS.getOpcode() != RHS.getOpcode() ||
13187       !LHS.hasOneUse() || !RHS.hasOneUse())
13188     return false;
13189
13190   // If this is a load and the token chain is identical, replace the select
13191   // of two loads with a load through a select of the address to load from.
13192   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13193   // constants have been dropped into the constant pool.
13194   if (LHS.getOpcode() == ISD::LOAD) {
13195     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13196     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13197
13198     // Token chains must be identical.
13199     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13200         // Do not let this transformation reduce the number of volatile loads.
13201         LLD->isVolatile() || RLD->isVolatile() ||
13202         // FIXME: If either is a pre/post inc/dec load,
13203         // we'd need to split out the address adjustment.
13204         LLD->isIndexed() || RLD->isIndexed() ||
13205         // If this is an EXTLOAD, the VT's must match.
13206         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13207         // If this is an EXTLOAD, the kind of extension must match.
13208         (LLD->getExtensionType() != RLD->getExtensionType() &&
13209          // The only exception is if one of the extensions is anyext.
13210          LLD->getExtensionType() != ISD::EXTLOAD &&
13211          RLD->getExtensionType() != ISD::EXTLOAD) ||
13212         // FIXME: this discards src value information.  This is
13213         // over-conservative. It would be beneficial to be able to remember
13214         // both potential memory locations.  Since we are discarding
13215         // src value info, don't do the transformation if the memory
13216         // locations are not in the default address space.
13217         LLD->getPointerInfo().getAddrSpace() != 0 ||
13218         RLD->getPointerInfo().getAddrSpace() != 0 ||
13219         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13220                                       LLD->getBasePtr().getValueType()))
13221       return false;
13222
13223     // Check that the select condition doesn't reach either load.  If so,
13224     // folding this will induce a cycle into the DAG.  If not, this is safe to
13225     // xform, so create a select of the addresses.
13226     SDValue Addr;
13227     if (TheSelect->getOpcode() == ISD::SELECT) {
13228       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13229       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13230           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13231         return false;
13232       // The loads must not depend on one another.
13233       if (LLD->isPredecessorOf(RLD) ||
13234           RLD->isPredecessorOf(LLD))
13235         return false;
13236       Addr = DAG.getSelect(SDLoc(TheSelect),
13237                            LLD->getBasePtr().getValueType(),
13238                            TheSelect->getOperand(0), LLD->getBasePtr(),
13239                            RLD->getBasePtr());
13240     } else {  // Otherwise SELECT_CC
13241       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13242       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13243
13244       if ((LLD->hasAnyUseOfValue(1) &&
13245            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13246           (RLD->hasAnyUseOfValue(1) &&
13247            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13248         return false;
13249
13250       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13251                          LLD->getBasePtr().getValueType(),
13252                          TheSelect->getOperand(0),
13253                          TheSelect->getOperand(1),
13254                          LLD->getBasePtr(), RLD->getBasePtr(),
13255                          TheSelect->getOperand(4));
13256     }
13257
13258     SDValue Load;
13259     // It is safe to replace the two loads if they have different alignments,
13260     // but the new load must be the minimum (most restrictive) alignment of the
13261     // inputs.
13262     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13263     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13264     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13265       Load = DAG.getLoad(TheSelect->getValueType(0),
13266                          SDLoc(TheSelect),
13267                          // FIXME: Discards pointer and AA info.
13268                          LLD->getChain(), Addr, MachinePointerInfo(),
13269                          LLD->isVolatile(), LLD->isNonTemporal(),
13270                          isInvariant, Alignment);
13271     } else {
13272       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13273                             RLD->getExtensionType() : LLD->getExtensionType(),
13274                             SDLoc(TheSelect),
13275                             TheSelect->getValueType(0),
13276                             // FIXME: Discards pointer and AA info.
13277                             LLD->getChain(), Addr, MachinePointerInfo(),
13278                             LLD->getMemoryVT(), LLD->isVolatile(),
13279                             LLD->isNonTemporal(), isInvariant, Alignment);
13280     }
13281
13282     // Users of the select now use the result of the load.
13283     CombineTo(TheSelect, Load);
13284
13285     // Users of the old loads now use the new load's chain.  We know the
13286     // old-load value is dead now.
13287     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13288     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13289     return true;
13290   }
13291
13292   return false;
13293 }
13294
13295 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13296 /// where 'cond' is the comparison specified by CC.
13297 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13298                                       SDValue N2, SDValue N3,
13299                                       ISD::CondCode CC, bool NotExtCompare) {
13300   // (x ? y : y) -> y.
13301   if (N2 == N3) return N2;
13302
13303   EVT VT = N2.getValueType();
13304   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13305   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13306
13307   // Determine if the condition we're dealing with is constant
13308   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13309                               N0, N1, CC, DL, false);
13310   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13311
13312   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13313     // fold select_cc true, x, y -> x
13314     // fold select_cc false, x, y -> y
13315     return !SCCC->isNullValue() ? N2 : N3;
13316   }
13317
13318   // Check to see if we can simplify the select into an fabs node
13319   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13320     // Allow either -0.0 or 0.0
13321     if (CFP->isZero()) {
13322       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13323       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13324           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13325           N2 == N3.getOperand(0))
13326         return DAG.getNode(ISD::FABS, DL, VT, N0);
13327
13328       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13329       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13330           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13331           N2.getOperand(0) == N3)
13332         return DAG.getNode(ISD::FABS, DL, VT, N3);
13333     }
13334   }
13335
13336   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13337   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13338   // in it.  This is a win when the constant is not otherwise available because
13339   // it replaces two constant pool loads with one.  We only do this if the FP
13340   // type is known to be legal, because if it isn't, then we are before legalize
13341   // types an we want the other legalization to happen first (e.g. to avoid
13342   // messing with soft float) and if the ConstantFP is not legal, because if
13343   // it is legal, we may not need to store the FP constant in a constant pool.
13344   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13345     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13346       if (TLI.isTypeLegal(N2.getValueType()) &&
13347           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13348                TargetLowering::Legal &&
13349            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13350            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13351           // If both constants have multiple uses, then we won't need to do an
13352           // extra load, they are likely around in registers for other users.
13353           (TV->hasOneUse() || FV->hasOneUse())) {
13354         Constant *Elts[] = {
13355           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13356           const_cast<ConstantFP*>(TV->getConstantFPValue())
13357         };
13358         Type *FPTy = Elts[0]->getType();
13359         const DataLayout &TD = *TLI.getDataLayout();
13360
13361         // Create a ConstantArray of the two constants.
13362         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13363         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13364                                             TD.getPrefTypeAlignment(FPTy));
13365         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13366
13367         // Get the offsets to the 0 and 1 element of the array so that we can
13368         // select between them.
13369         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13370         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13371         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13372
13373         SDValue Cond = DAG.getSetCC(DL,
13374                                     getSetCCResultType(N0.getValueType()),
13375                                     N0, N1, CC);
13376         AddToWorklist(Cond.getNode());
13377         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13378                                           Cond, One, Zero);
13379         AddToWorklist(CstOffset.getNode());
13380         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13381                             CstOffset);
13382         AddToWorklist(CPIdx.getNode());
13383         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13384                            MachinePointerInfo::getConstantPool(), false,
13385                            false, false, Alignment);
13386       }
13387     }
13388
13389   // Check to see if we can perform the "gzip trick", transforming
13390   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13391   if (isNullConstant(N3) && CC == ISD::SETLT &&
13392       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13393        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13394     EVT XType = N0.getValueType();
13395     EVT AType = N2.getValueType();
13396     if (XType.bitsGE(AType)) {
13397       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13398       // single-bit constant.
13399       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13400         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13401         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13402         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13403                                        getShiftAmountTy(N0.getValueType()));
13404         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13405                                     XType, N0, ShCt);
13406         AddToWorklist(Shift.getNode());
13407
13408         if (XType.bitsGT(AType)) {
13409           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13410           AddToWorklist(Shift.getNode());
13411         }
13412
13413         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13414       }
13415
13416       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13417                                   XType, N0,
13418                                   DAG.getConstant(XType.getSizeInBits() - 1,
13419                                                   SDLoc(N0),
13420                                          getShiftAmountTy(N0.getValueType())));
13421       AddToWorklist(Shift.getNode());
13422
13423       if (XType.bitsGT(AType)) {
13424         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13425         AddToWorklist(Shift.getNode());
13426       }
13427
13428       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13429     }
13430   }
13431
13432   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13433   // where y is has a single bit set.
13434   // A plaintext description would be, we can turn the SELECT_CC into an AND
13435   // when the condition can be materialized as an all-ones register.  Any
13436   // single bit-test can be materialized as an all-ones register with
13437   // shift-left and shift-right-arith.
13438   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13439       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13440     SDValue AndLHS = N0->getOperand(0);
13441     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13442     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13443       // Shift the tested bit over the sign bit.
13444       APInt AndMask = ConstAndRHS->getAPIntValue();
13445       SDValue ShlAmt =
13446         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13447                         getShiftAmountTy(AndLHS.getValueType()));
13448       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13449
13450       // Now arithmetic right shift it all the way over, so the result is either
13451       // all-ones, or zero.
13452       SDValue ShrAmt =
13453         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13454                         getShiftAmountTy(Shl.getValueType()));
13455       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13456
13457       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13458     }
13459   }
13460
13461   // fold select C, 16, 0 -> shl C, 4
13462   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13463       TLI.getBooleanContents(N0.getValueType()) ==
13464           TargetLowering::ZeroOrOneBooleanContent) {
13465
13466     // If the caller doesn't want us to simplify this into a zext of a compare,
13467     // don't do it.
13468     if (NotExtCompare && N2C->isOne())
13469       return SDValue();
13470
13471     // Get a SetCC of the condition
13472     // NOTE: Don't create a SETCC if it's not legal on this target.
13473     if (!LegalOperations ||
13474         TLI.isOperationLegal(ISD::SETCC,
13475           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13476       SDValue Temp, SCC;
13477       // cast from setcc result type to select result type
13478       if (LegalTypes) {
13479         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13480                             N0, N1, CC);
13481         if (N2.getValueType().bitsLT(SCC.getValueType()))
13482           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13483                                         N2.getValueType());
13484         else
13485           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13486                              N2.getValueType(), SCC);
13487       } else {
13488         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13489         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13490                            N2.getValueType(), SCC);
13491       }
13492
13493       AddToWorklist(SCC.getNode());
13494       AddToWorklist(Temp.getNode());
13495
13496       if (N2C->isOne())
13497         return Temp;
13498
13499       // shl setcc result by log2 n2c
13500       return DAG.getNode(
13501           ISD::SHL, DL, N2.getValueType(), Temp,
13502           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13503                           getShiftAmountTy(Temp.getValueType())));
13504     }
13505   }
13506
13507   // Check to see if this is the equivalent of setcc
13508   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13509   // otherwise, go ahead with the folds.
13510   if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13511     EVT XType = N0.getValueType();
13512     if (!LegalOperations ||
13513         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13514       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13515       if (Res.getValueType() != VT)
13516         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13517       return Res;
13518     }
13519
13520     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13521     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13522         (!LegalOperations ||
13523          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13524       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13525       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13526                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13527                                          SDLoc(Ctlz),
13528                                        getShiftAmountTy(Ctlz.getValueType())));
13529     }
13530     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13531     if (isNullConstant(N1) && CC == ISD::SETGT) {
13532       SDLoc DL(N0);
13533       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13534                                   XType, DAG.getConstant(0, DL, XType), N0);
13535       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13536       return DAG.getNode(ISD::SRL, DL, XType,
13537                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13538                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13539                                          getShiftAmountTy(XType)));
13540     }
13541     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13542     if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13543       SDLoc DL(N0);
13544       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13545                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13546                                          getShiftAmountTy(N0.getValueType())));
13547       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13548                                                                     XType));
13549     }
13550   }
13551
13552   // Check to see if this is an integer abs.
13553   // select_cc setg[te] X,  0,  X, -X ->
13554   // select_cc setgt    X, -1,  X, -X ->
13555   // select_cc setl[te] X,  0, -X,  X ->
13556   // select_cc setlt    X,  1, -X,  X ->
13557   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13558   if (N1C) {
13559     ConstantSDNode *SubC = nullptr;
13560     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13561          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13562         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13563       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13564     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13565               (N1C->isOne() && CC == ISD::SETLT)) &&
13566              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13567       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13568
13569     EVT XType = N0.getValueType();
13570     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13571       SDLoc DL(N0);
13572       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13573                                   N0,
13574                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13575                                          getShiftAmountTy(N0.getValueType())));
13576       SDValue Add = DAG.getNode(ISD::ADD, DL,
13577                                 XType, N0, Shift);
13578       AddToWorklist(Shift.getNode());
13579       AddToWorklist(Add.getNode());
13580       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13581     }
13582   }
13583
13584   return SDValue();
13585 }
13586
13587 /// This is a stub for TargetLowering::SimplifySetCC.
13588 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13589                                    SDValue N1, ISD::CondCode Cond,
13590                                    SDLoc DL, bool foldBooleans) {
13591   TargetLowering::DAGCombinerInfo
13592     DagCombineInfo(DAG, Level, false, this);
13593   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13594 }
13595
13596 /// Given an ISD::SDIV node expressing a divide by constant, return
13597 /// a DAG expression to select that will generate the same value by multiplying
13598 /// by a magic number.
13599 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13600 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13601   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13602   if (!C)
13603     return SDValue();
13604
13605   // Avoid division by zero.
13606   if (C->isNullValue())
13607     return SDValue();
13608
13609   std::vector<SDNode*> Built;
13610   SDValue S =
13611       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13612
13613   for (SDNode *N : Built)
13614     AddToWorklist(N);
13615   return S;
13616 }
13617
13618 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13619 /// DAG expression that will generate the same value by right shifting.
13620 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13621   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13622   if (!C)
13623     return SDValue();
13624
13625   // Avoid division by zero.
13626   if (C->isNullValue())
13627     return SDValue();
13628
13629   std::vector<SDNode *> Built;
13630   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13631
13632   for (SDNode *N : Built)
13633     AddToWorklist(N);
13634   return S;
13635 }
13636
13637 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13638 /// expression that will generate the same value by multiplying by a magic
13639 /// number.
13640 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13641 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13642   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13643   if (!C)
13644     return SDValue();
13645
13646   // Avoid division by zero.
13647   if (C->isNullValue())
13648     return SDValue();
13649
13650   std::vector<SDNode*> Built;
13651   SDValue S =
13652       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13653
13654   for (SDNode *N : Built)
13655     AddToWorklist(N);
13656   return S;
13657 }
13658
13659 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13660   if (Level >= AfterLegalizeDAG)
13661     return SDValue();
13662
13663   // Expose the DAG combiner to the target combiner implementations.
13664   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13665
13666   unsigned Iterations = 0;
13667   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13668     if (Iterations) {
13669       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13670       // For the reciprocal, we need to find the zero of the function:
13671       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13672       //     =>
13673       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13674       //     does not require additional intermediate precision]
13675       EVT VT = Op.getValueType();
13676       SDLoc DL(Op);
13677       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13678
13679       AddToWorklist(Est.getNode());
13680
13681       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13682       for (unsigned i = 0; i < Iterations; ++i) {
13683         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13684         AddToWorklist(NewEst.getNode());
13685
13686         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13687         AddToWorklist(NewEst.getNode());
13688
13689         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13690         AddToWorklist(NewEst.getNode());
13691
13692         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13693         AddToWorklist(Est.getNode());
13694       }
13695     }
13696     return Est;
13697   }
13698
13699   return SDValue();
13700 }
13701
13702 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13703 /// For the reciprocal sqrt, we need to find the zero of the function:
13704 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13705 ///     =>
13706 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13707 /// As a result, we precompute A/2 prior to the iteration loop.
13708 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13709                                           unsigned Iterations) {
13710   EVT VT = Arg.getValueType();
13711   SDLoc DL(Arg);
13712   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13713
13714   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13715   // this entire sequence requires only one FP constant.
13716   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13717   AddToWorklist(HalfArg.getNode());
13718
13719   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13720   AddToWorklist(HalfArg.getNode());
13721
13722   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13723   for (unsigned i = 0; i < Iterations; ++i) {
13724     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13725     AddToWorklist(NewEst.getNode());
13726
13727     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13728     AddToWorklist(NewEst.getNode());
13729
13730     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13731     AddToWorklist(NewEst.getNode());
13732
13733     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13734     AddToWorklist(Est.getNode());
13735   }
13736   return Est;
13737 }
13738
13739 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13740 /// For the reciprocal sqrt, we need to find the zero of the function:
13741 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13742 ///     =>
13743 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13744 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13745                                           unsigned Iterations) {
13746   EVT VT = Arg.getValueType();
13747   SDLoc DL(Arg);
13748   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13749   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13750
13751   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13752   for (unsigned i = 0; i < Iterations; ++i) {
13753     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13754     AddToWorklist(HalfEst.getNode());
13755
13756     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13757     AddToWorklist(Est.getNode());
13758
13759     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13760     AddToWorklist(Est.getNode());
13761
13762     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13763     AddToWorklist(Est.getNode());
13764
13765     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13766     AddToWorklist(Est.getNode());
13767   }
13768   return Est;
13769 }
13770
13771 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13772   if (Level >= AfterLegalizeDAG)
13773     return SDValue();
13774
13775   // Expose the DAG combiner to the target combiner implementations.
13776   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13777   unsigned Iterations = 0;
13778   bool UseOneConstNR = false;
13779   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13780     AddToWorklist(Est.getNode());
13781     if (Iterations) {
13782       Est = UseOneConstNR ?
13783         BuildRsqrtNROneConst(Op, Est, Iterations) :
13784         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13785     }
13786     return Est;
13787   }
13788
13789   return SDValue();
13790 }
13791
13792 /// Return true if base is a frame index, which is known not to alias with
13793 /// anything but itself.  Provides base object and offset as results.
13794 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13795                            const GlobalValue *&GV, const void *&CV) {
13796   // Assume it is a primitive operation.
13797   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13798
13799   // If it's an adding a simple constant then integrate the offset.
13800   if (Base.getOpcode() == ISD::ADD) {
13801     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13802       Base = Base.getOperand(0);
13803       Offset += C->getZExtValue();
13804     }
13805   }
13806
13807   // Return the underlying GlobalValue, and update the Offset.  Return false
13808   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13809   // by multiple nodes with different offsets.
13810   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13811     GV = G->getGlobal();
13812     Offset += G->getOffset();
13813     return false;
13814   }
13815
13816   // Return the underlying Constant value, and update the Offset.  Return false
13817   // for ConstantSDNodes since the same constant pool entry may be represented
13818   // by multiple nodes with different offsets.
13819   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13820     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13821                                          : (const void *)C->getConstVal();
13822     Offset += C->getOffset();
13823     return false;
13824   }
13825   // If it's any of the following then it can't alias with anything but itself.
13826   return isa<FrameIndexSDNode>(Base);
13827 }
13828
13829 /// Return true if there is any possibility that the two addresses overlap.
13830 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13831   // If they are the same then they must be aliases.
13832   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13833
13834   // If they are both volatile then they cannot be reordered.
13835   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13836
13837   // Gather base node and offset information.
13838   SDValue Base1, Base2;
13839   int64_t Offset1, Offset2;
13840   const GlobalValue *GV1, *GV2;
13841   const void *CV1, *CV2;
13842   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13843                                       Base1, Offset1, GV1, CV1);
13844   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13845                                       Base2, Offset2, GV2, CV2);
13846
13847   // If they have a same base address then check to see if they overlap.
13848   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13849     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13850              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13851
13852   // It is possible for different frame indices to alias each other, mostly
13853   // when tail call optimization reuses return address slots for arguments.
13854   // To catch this case, look up the actual index of frame indices to compute
13855   // the real alias relationship.
13856   if (isFrameIndex1 && isFrameIndex2) {
13857     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13858     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13859     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13860     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13861              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13862   }
13863
13864   // Otherwise, if we know what the bases are, and they aren't identical, then
13865   // we know they cannot alias.
13866   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13867     return false;
13868
13869   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13870   // compared to the size and offset of the access, we may be able to prove they
13871   // do not alias.  This check is conservative for now to catch cases created by
13872   // splitting vector types.
13873   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13874       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13875       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13876        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13877       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13878     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13879     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13880
13881     // There is no overlap between these relatively aligned accesses of similar
13882     // size, return no alias.
13883     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13884         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13885       return false;
13886   }
13887
13888   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13889                    ? CombinerGlobalAA
13890                    : DAG.getSubtarget().useAA();
13891 #ifndef NDEBUG
13892   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13893       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13894     UseAA = false;
13895 #endif
13896   if (UseAA &&
13897       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13898     // Use alias analysis information.
13899     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13900                                  Op1->getSrcValueOffset());
13901     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13902         Op0->getSrcValueOffset() - MinOffset;
13903     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13904         Op1->getSrcValueOffset() - MinOffset;
13905     AliasResult AAResult =
13906         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
13907                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13908                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
13909                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13910     if (AAResult == NoAlias)
13911       return false;
13912   }
13913
13914   // Otherwise we have to assume they alias.
13915   return true;
13916 }
13917
13918 /// Walk up chain skipping non-aliasing memory nodes,
13919 /// looking for aliasing nodes and adding them to the Aliases vector.
13920 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13921                                    SmallVectorImpl<SDValue> &Aliases) {
13922   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13923   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13924
13925   // Get alias information for node.
13926   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13927
13928   // Starting off.
13929   Chains.push_back(OriginalChain);
13930   unsigned Depth = 0;
13931
13932   // Look at each chain and determine if it is an alias.  If so, add it to the
13933   // aliases list.  If not, then continue up the chain looking for the next
13934   // candidate.
13935   while (!Chains.empty()) {
13936     SDValue Chain = Chains.pop_back_val();
13937
13938     // For TokenFactor nodes, look at each operand and only continue up the
13939     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13940     // find more and revert to original chain since the xform is unlikely to be
13941     // profitable.
13942     //
13943     // FIXME: The depth check could be made to return the last non-aliasing
13944     // chain we found before we hit a tokenfactor rather than the original
13945     // chain.
13946     if (Depth > 6 || Aliases.size() == 2) {
13947       Aliases.clear();
13948       Aliases.push_back(OriginalChain);
13949       return;
13950     }
13951
13952     // Don't bother if we've been before.
13953     if (!Visited.insert(Chain.getNode()).second)
13954       continue;
13955
13956     switch (Chain.getOpcode()) {
13957     case ISD::EntryToken:
13958       // Entry token is ideal chain operand, but handled in FindBetterChain.
13959       break;
13960
13961     case ISD::LOAD:
13962     case ISD::STORE: {
13963       // Get alias information for Chain.
13964       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13965           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13966
13967       // If chain is alias then stop here.
13968       if (!(IsLoad && IsOpLoad) &&
13969           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13970         Aliases.push_back(Chain);
13971       } else {
13972         // Look further up the chain.
13973         Chains.push_back(Chain.getOperand(0));
13974         ++Depth;
13975       }
13976       break;
13977     }
13978
13979     case ISD::TokenFactor:
13980       // We have to check each of the operands of the token factor for "small"
13981       // token factors, so we queue them up.  Adding the operands to the queue
13982       // (stack) in reverse order maintains the original order and increases the
13983       // likelihood that getNode will find a matching token factor (CSE.)
13984       if (Chain.getNumOperands() > 16) {
13985         Aliases.push_back(Chain);
13986         break;
13987       }
13988       for (unsigned n = Chain.getNumOperands(); n;)
13989         Chains.push_back(Chain.getOperand(--n));
13990       ++Depth;
13991       break;
13992
13993     default:
13994       // For all other instructions we will just have to take what we can get.
13995       Aliases.push_back(Chain);
13996       break;
13997     }
13998   }
13999
14000   // We need to be careful here to also search for aliases through the
14001   // value operand of a store, etc. Consider the following situation:
14002   //   Token1 = ...
14003   //   L1 = load Token1, %52
14004   //   S1 = store Token1, L1, %51
14005   //   L2 = load Token1, %52+8
14006   //   S2 = store Token1, L2, %51+8
14007   //   Token2 = Token(S1, S2)
14008   //   L3 = load Token2, %53
14009   //   S3 = store Token2, L3, %52
14010   //   L4 = load Token2, %53+8
14011   //   S4 = store Token2, L4, %52+8
14012   // If we search for aliases of S3 (which loads address %52), and we look
14013   // only through the chain, then we'll miss the trivial dependence on L1
14014   // (which also loads from %52). We then might change all loads and
14015   // stores to use Token1 as their chain operand, which could result in
14016   // copying %53 into %52 before copying %52 into %51 (which should
14017   // happen first).
14018   //
14019   // The problem is, however, that searching for such data dependencies
14020   // can become expensive, and the cost is not directly related to the
14021   // chain depth. Instead, we'll rule out such configurations here by
14022   // insisting that we've visited all chain users (except for users
14023   // of the original chain, which is not necessary). When doing this,
14024   // we need to look through nodes we don't care about (otherwise, things
14025   // like register copies will interfere with trivial cases).
14026
14027   SmallVector<const SDNode *, 16> Worklist;
14028   for (const SDNode *N : Visited)
14029     if (N != OriginalChain.getNode())
14030       Worklist.push_back(N);
14031
14032   while (!Worklist.empty()) {
14033     const SDNode *M = Worklist.pop_back_val();
14034
14035     // We have already visited M, and want to make sure we've visited any uses
14036     // of M that we care about. For uses that we've not visisted, and don't
14037     // care about, queue them to the worklist.
14038
14039     for (SDNode::use_iterator UI = M->use_begin(),
14040          UIE = M->use_end(); UI != UIE; ++UI)
14041       if (UI.getUse().getValueType() == MVT::Other &&
14042           Visited.insert(*UI).second) {
14043         if (isa<MemSDNode>(*UI)) {
14044           // We've not visited this use, and we care about it (it could have an
14045           // ordering dependency with the original node).
14046           Aliases.clear();
14047           Aliases.push_back(OriginalChain);
14048           return;
14049         }
14050
14051         // We've not visited this use, but we don't care about it. Mark it as
14052         // visited and enqueue it to the worklist.
14053         Worklist.push_back(*UI);
14054       }
14055   }
14056 }
14057
14058 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14059 /// (aliasing node.)
14060 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14061   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14062
14063   // Accumulate all the aliases to this node.
14064   GatherAllAliases(N, OldChain, Aliases);
14065
14066   // If no operands then chain to entry token.
14067   if (Aliases.size() == 0)
14068     return DAG.getEntryNode();
14069
14070   // If a single operand then chain to it.  We don't need to revisit it.
14071   if (Aliases.size() == 1)
14072     return Aliases[0];
14073
14074   // Construct a custom tailored token factor.
14075   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14076 }
14077
14078 /// This is the entry point for the file.
14079 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14080                            CodeGenOpt::Level OptLevel) {
14081   /// This is the main entry point to this class.
14082   DAGCombiner(*this, AA, OptLevel).Run(Level);
14083 }