Merge DAGCombiner::visitSREM and DAGCombiner::visitUREM (NFC)
[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 visitREM(SDNode *N);
239     SDValue visitMULHU(SDNode *N);
240     SDValue visitMULHS(SDNode *N);
241     SDValue visitSMUL_LOHI(SDNode *N);
242     SDValue visitUMUL_LOHI(SDNode *N);
243     SDValue visitSMULO(SDNode *N);
244     SDValue visitUMULO(SDNode *N);
245     SDValue visitSDIVREM(SDNode *N);
246     SDValue visitUDIVREM(SDNode *N);
247     SDValue visitIMINMAX(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
302     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
303     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
304
305     SDValue visitSTORE(SDNode *N);
306     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
307     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
308     SDValue visitBUILD_VECTOR(SDNode *N);
309     SDValue visitCONCAT_VECTORS(SDNode *N);
310     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
311     SDValue visitVECTOR_SHUFFLE(SDNode *N);
312     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
313     SDValue visitINSERT_SUBVECTOR(SDNode *N);
314     SDValue visitMLOAD(SDNode *N);
315     SDValue visitMSTORE(SDNode *N);
316     SDValue visitMGATHER(SDNode *N);
317     SDValue visitMSCATTER(SDNode *N);
318     SDValue visitFP_TO_FP16(SDNode *N);
319     SDValue visitFP16_TO_FP(SDNode *N);
320
321     SDValue visitFADDForFMACombine(SDNode *N);
322     SDValue visitFSUBForFMACombine(SDNode *N);
323     SDValue visitFMULForFMACombine(SDNode *N);
324
325     SDValue XformToShuffleWithZero(SDNode *N);
326     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
327
328     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
329
330     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
331     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
332     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
333     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
334                              SDValue N3, ISD::CondCode CC,
335                              bool NotExtCompare = false);
336     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
337                           SDLoc DL, bool foldBooleans = true);
338
339     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
340                            SDValue &CC) const;
341     bool isOneUseSetCC(SDValue N) const;
342
343     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
344                                          unsigned HiOp);
345     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
346     SDValue CombineExtLoad(SDNode *N);
347     SDValue combineRepeatedFPDivisors(SDNode *N);
348     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
349     SDValue BuildSDIV(SDNode *N);
350     SDValue BuildSDIVPow2(SDNode *N);
351     SDValue BuildUDIV(SDNode *N);
352     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
353     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
354     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
355                                  SDNodeFlags *Flags);
356     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
357                                  SDNodeFlags *Flags);
358     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
359                                bool DemandHighBits = true);
360     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
361     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
362                               SDValue InnerPos, SDValue InnerNeg,
363                               unsigned PosOpcode, unsigned NegOpcode,
364                               SDLoc DL);
365     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
366     SDValue ReduceLoadWidth(SDNode *N);
367     SDValue ReduceLoadOpStoreWidth(SDNode *N);
368     SDValue TransformFPLoadStorePair(SDNode *N);
369     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
370     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
371
372     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
373
374     /// Walk up chain skipping non-aliasing memory nodes,
375     /// looking for aliasing nodes and adding them to the Aliases vector.
376     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
377                           SmallVectorImpl<SDValue> &Aliases);
378
379     /// Return true if there is any possibility that the two addresses overlap.
380     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
381
382     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
383     /// chain (aliasing node.)
384     SDValue FindBetterChain(SDNode *N, SDValue Chain);
385
386     /// Do FindBetterChain for a store and any possibly adjacent stores on
387     /// consecutive chains.
388     bool findBetterNeighborChains(StoreSDNode *St);
389
390     /// Holds a pointer to an LSBaseSDNode as well as information on where it
391     /// is located in a sequence of memory operations connected by a chain.
392     struct MemOpLink {
393       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
394       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
395       // Ptr to the mem node.
396       LSBaseSDNode *MemNode;
397       // Offset from the base ptr.
398       int64_t OffsetFromBase;
399       // What is the sequence number of this mem node.
400       // Lowest mem operand in the DAG starts at zero.
401       unsigned SequenceNum;
402     };
403
404     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
405     /// constant build_vector of the stored constant values in Stores.
406     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
407                                          SDLoc SL,
408                                          ArrayRef<MemOpLink> Stores,
409                                          SmallVectorImpl<SDValue> &Chains,
410                                          EVT Ty) const;
411
412     /// This is a helper function for MergeConsecutiveStores. When the source
413     /// elements of the consecutive stores are all constants or all extracted
414     /// vector elements, try to merge them into one larger store.
415     /// \return True if a merged store was created.
416     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
417                                          EVT MemVT, unsigned NumStores,
418                                          bool IsConstantSrc, bool UseVector);
419
420     /// This is a helper function for MergeConsecutiveStores.
421     /// Stores that may be merged are placed in StoreNodes.
422     /// Loads that may alias with those stores are placed in AliasLoadNodes.
423     void getStoreMergeAndAliasCandidates(
424         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
425         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
426
427     /// Merge consecutive store operations into a wide store.
428     /// This optimization uses wide integers or vectors when possible.
429     /// \return True if some memory operations were changed.
430     bool MergeConsecutiveStores(StoreSDNode *N);
431
432     /// \brief Try to transform a truncation where C is a constant:
433     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
434     ///
435     /// \p N needs to be a truncation and its first operand an AND. Other
436     /// requirements are checked by the function (e.g. that trunc is
437     /// single-use) and if missed an empty SDValue is returned.
438     SDValue distributeTruncateThroughAnd(SDNode *N);
439
440   public:
441     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
442         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
443           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
444       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
445     }
446
447     /// Runs the dag combiner on all nodes in the work list
448     void Run(CombineLevel AtLevel);
449
450     SelectionDAG &getDAG() const { return DAG; }
451
452     /// Returns a type large enough to hold any valid shift amount - before type
453     /// legalization these can be huge.
454     EVT getShiftAmountTy(EVT LHSTy) {
455       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
456       if (LHSTy.isVector())
457         return LHSTy;
458       auto &DL = DAG.getDataLayout();
459       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
460                         : TLI.getPointerTy(DL);
461     }
462
463     /// This method returns true if we are running before type legalization or
464     /// if the specified VT is legal.
465     bool isTypeLegal(const EVT &VT) {
466       if (!LegalTypes) return true;
467       return TLI.isTypeLegal(VT);
468     }
469
470     /// Convenience wrapper around TargetLowering::getSetCCResultType
471     EVT getSetCCResultType(EVT VT) const {
472       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
473     }
474   };
475 }
476
477
478 namespace {
479 /// This class is a DAGUpdateListener that removes any deleted
480 /// nodes from the worklist.
481 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
482   DAGCombiner &DC;
483 public:
484   explicit WorklistRemover(DAGCombiner &dc)
485     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
486
487   void NodeDeleted(SDNode *N, SDNode *E) override {
488     DC.removeFromWorklist(N);
489   }
490 };
491 }
492
493 //===----------------------------------------------------------------------===//
494 //  TargetLowering::DAGCombinerInfo implementation
495 //===----------------------------------------------------------------------===//
496
497 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
498   ((DAGCombiner*)DC)->AddToWorklist(N);
499 }
500
501 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
502   ((DAGCombiner*)DC)->removeFromWorklist(N);
503 }
504
505 SDValue TargetLowering::DAGCombinerInfo::
506 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
507   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
508 }
509
510 SDValue TargetLowering::DAGCombinerInfo::
511 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
512   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
513 }
514
515
516 SDValue TargetLowering::DAGCombinerInfo::
517 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
518   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
519 }
520
521 void TargetLowering::DAGCombinerInfo::
522 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
523   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
524 }
525
526 //===----------------------------------------------------------------------===//
527 // Helper Functions
528 //===----------------------------------------------------------------------===//
529
530 void DAGCombiner::deleteAndRecombine(SDNode *N) {
531   removeFromWorklist(N);
532
533   // If the operands of this node are only used by the node, they will now be
534   // dead. Make sure to re-visit them and recursively delete dead nodes.
535   for (const SDValue &Op : N->ops())
536     // For an operand generating multiple values, one of the values may
537     // become dead allowing further simplification (e.g. split index
538     // arithmetic from an indexed load).
539     if (Op->hasOneUse() || Op->getNumValues() > 1)
540       AddToWorklist(Op.getNode());
541
542   DAG.DeleteNode(N);
543 }
544
545 /// Return 1 if we can compute the negated form of the specified expression for
546 /// the same cost as the expression itself, or 2 if we can compute the negated
547 /// form more cheaply than the expression itself.
548 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
549                                const TargetLowering &TLI,
550                                const TargetOptions *Options,
551                                unsigned Depth = 0) {
552   // fneg is removable even if it has multiple uses.
553   if (Op.getOpcode() == ISD::FNEG) return 2;
554
555   // Don't allow anything with multiple uses.
556   if (!Op.hasOneUse()) return 0;
557
558   // Don't recurse exponentially.
559   if (Depth > 6) return 0;
560
561   switch (Op.getOpcode()) {
562   default: return false;
563   case ISD::ConstantFP:
564     // Don't invert constant FP values after legalize.  The negated constant
565     // isn't necessarily legal.
566     return LegalOperations ? 0 : 1;
567   case ISD::FADD:
568     // FIXME: determine better conditions for this xform.
569     if (!Options->UnsafeFPMath) return 0;
570
571     // After operation legalization, it might not be legal to create new FSUBs.
572     if (LegalOperations &&
573         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
574       return 0;
575
576     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
577     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
578                                     Options, Depth + 1))
579       return V;
580     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
581     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
582                               Depth + 1);
583   case ISD::FSUB:
584     // We can't turn -(A-B) into B-A when we honor signed zeros.
585     if (!Options->UnsafeFPMath) return 0;
586
587     // fold (fneg (fsub A, B)) -> (fsub B, A)
588     return 1;
589
590   case ISD::FMUL:
591   case ISD::FDIV:
592     if (Options->HonorSignDependentRoundingFPMath()) return 0;
593
594     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
595     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
596                                     Options, Depth + 1))
597       return V;
598
599     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
600                               Depth + 1);
601
602   case ISD::FP_EXTEND:
603   case ISD::FP_ROUND:
604   case ISD::FSIN:
605     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
606                               Depth + 1);
607   }
608 }
609
610 /// If isNegatibleForFree returns true, return the newly negated expression.
611 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
612                                     bool LegalOperations, unsigned Depth = 0) {
613   const TargetOptions &Options = DAG.getTarget().Options;
614   // fneg is removable even if it has multiple uses.
615   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
616
617   // Don't allow anything with multiple uses.
618   assert(Op.hasOneUse() && "Unknown reuse!");
619
620   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
621
622   const SDNodeFlags *Flags = Op.getNode()->getFlags();
623
624   switch (Op.getOpcode()) {
625   default: llvm_unreachable("Unknown code");
626   case ISD::ConstantFP: {
627     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
628     V.changeSign();
629     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
630   }
631   case ISD::FADD:
632     // FIXME: determine better conditions for this xform.
633     assert(Options.UnsafeFPMath);
634
635     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
636     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
637                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
638       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
639                          GetNegatedExpression(Op.getOperand(0), DAG,
640                                               LegalOperations, Depth+1),
641                          Op.getOperand(1), Flags);
642     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
643     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
644                        GetNegatedExpression(Op.getOperand(1), DAG,
645                                             LegalOperations, Depth+1),
646                        Op.getOperand(0), Flags);
647   case ISD::FSUB:
648     // We can't turn -(A-B) into B-A when we honor signed zeros.
649     assert(Options.UnsafeFPMath);
650
651     // fold (fneg (fsub 0, B)) -> B
652     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
653       if (N0CFP->isZero())
654         return Op.getOperand(1);
655
656     // fold (fneg (fsub A, B)) -> (fsub B, A)
657     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
658                        Op.getOperand(1), Op.getOperand(0), Flags);
659
660   case ISD::FMUL:
661   case ISD::FDIV:
662     assert(!Options.HonorSignDependentRoundingFPMath());
663
664     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
665     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
666                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
667       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
668                          GetNegatedExpression(Op.getOperand(0), DAG,
669                                               LegalOperations, Depth+1),
670                          Op.getOperand(1), Flags);
671
672     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
673     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
674                        Op.getOperand(0),
675                        GetNegatedExpression(Op.getOperand(1), DAG,
676                                             LegalOperations, Depth+1), Flags);
677
678   case ISD::FP_EXTEND:
679   case ISD::FSIN:
680     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
681                        GetNegatedExpression(Op.getOperand(0), DAG,
682                                             LegalOperations, Depth+1));
683   case ISD::FP_ROUND:
684       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
685                          GetNegatedExpression(Op.getOperand(0), DAG,
686                                               LegalOperations, Depth+1),
687                          Op.getOperand(1));
688   }
689 }
690
691 // Return true if this node is a setcc, or is a select_cc
692 // that selects between the target values used for true and false, making it
693 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
694 // the appropriate nodes based on the type of node we are checking. This
695 // simplifies life a bit for the callers.
696 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
697                                     SDValue &CC) const {
698   if (N.getOpcode() == ISD::SETCC) {
699     LHS = N.getOperand(0);
700     RHS = N.getOperand(1);
701     CC  = N.getOperand(2);
702     return true;
703   }
704
705   if (N.getOpcode() != ISD::SELECT_CC ||
706       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
707       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
708     return false;
709
710   if (TLI.getBooleanContents(N.getValueType()) ==
711       TargetLowering::UndefinedBooleanContent)
712     return false;
713
714   LHS = N.getOperand(0);
715   RHS = N.getOperand(1);
716   CC  = N.getOperand(4);
717   return true;
718 }
719
720 /// Return true if this is a SetCC-equivalent operation with only one use.
721 /// If this is true, it allows the users to invert the operation for free when
722 /// it is profitable to do so.
723 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
724   SDValue N0, N1, N2;
725   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
726     return true;
727   return false;
728 }
729
730 /// Returns true if N is a BUILD_VECTOR node whose
731 /// elements are all the same constant or undefined.
732 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
733   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
734   if (!C)
735     return false;
736
737   APInt SplatUndef;
738   unsigned SplatBitSize;
739   bool HasAnyUndefs;
740   EVT EltVT = N->getValueType(0).getVectorElementType();
741   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
742                              HasAnyUndefs) &&
743           EltVT.getSizeInBits() >= SplatBitSize);
744 }
745
746 // \brief Returns the SDNode if it is a constant integer BuildVector
747 // or constant integer.
748 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
749   if (isa<ConstantSDNode>(N))
750     return N.getNode();
751   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
752     return N.getNode();
753   return nullptr;
754 }
755
756 // \brief Returns the SDNode if it is a constant float BuildVector
757 // or constant float.
758 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
759   if (isa<ConstantFPSDNode>(N))
760     return N.getNode();
761   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
762     return N.getNode();
763   return nullptr;
764 }
765
766 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
767 // int.
768 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
769   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
770     return CN;
771
772   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
773     BitVector UndefElements;
774     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
775
776     // BuildVectors can truncate their operands. Ignore that case here.
777     // FIXME: We blindly ignore splats which include undef which is overly
778     // pessimistic.
779     if (CN && UndefElements.none() &&
780         CN->getValueType(0) == N.getValueType().getScalarType())
781       return CN;
782   }
783
784   return nullptr;
785 }
786
787 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
788 // float.
789 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
790   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
791     return CN;
792
793   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
794     BitVector UndefElements;
795     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
796
797     if (CN && UndefElements.none())
798       return CN;
799   }
800
801   return nullptr;
802 }
803
804 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
805                                     SDValue N0, SDValue N1) {
806   EVT VT = N0.getValueType();
807   if (N0.getOpcode() == Opc) {
808     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
809       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
810         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
811         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
812           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
813         return SDValue();
814       }
815       if (N0.hasOneUse()) {
816         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
817         // use
818         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
819         if (!OpNode.getNode())
820           return SDValue();
821         AddToWorklist(OpNode.getNode());
822         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
823       }
824     }
825   }
826
827   if (N1.getOpcode() == Opc) {
828     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
829       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
830         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
831         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
832           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
833         return SDValue();
834       }
835       if (N1.hasOneUse()) {
836         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
837         // use
838         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
839         if (!OpNode.getNode())
840           return SDValue();
841         AddToWorklist(OpNode.getNode());
842         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
843       }
844     }
845   }
846
847   return SDValue();
848 }
849
850 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
851                                bool AddTo) {
852   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
853   ++NodesCombined;
854   DEBUG(dbgs() << "\nReplacing.1 ";
855         N->dump(&DAG);
856         dbgs() << "\nWith: ";
857         To[0].getNode()->dump(&DAG);
858         dbgs() << " and " << NumTo-1 << " other values\n");
859   for (unsigned i = 0, e = NumTo; i != e; ++i)
860     assert((!To[i].getNode() ||
861             N->getValueType(i) == To[i].getValueType()) &&
862            "Cannot combine value to value of different type!");
863
864   WorklistRemover DeadNodes(*this);
865   DAG.ReplaceAllUsesWith(N, To);
866   if (AddTo) {
867     // Push the new nodes and any users onto the worklist
868     for (unsigned i = 0, e = NumTo; i != e; ++i) {
869       if (To[i].getNode()) {
870         AddToWorklist(To[i].getNode());
871         AddUsersToWorklist(To[i].getNode());
872       }
873     }
874   }
875
876   // Finally, if the node is now dead, remove it from the graph.  The node
877   // may not be dead if the replacement process recursively simplified to
878   // something else needing this node.
879   if (N->use_empty())
880     deleteAndRecombine(N);
881   return SDValue(N, 0);
882 }
883
884 void DAGCombiner::
885 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
886   // Replace all uses.  If any nodes become isomorphic to other nodes and
887   // are deleted, make sure to remove them from our worklist.
888   WorklistRemover DeadNodes(*this);
889   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
890
891   // Push the new node and any (possibly new) users onto the worklist.
892   AddToWorklist(TLO.New.getNode());
893   AddUsersToWorklist(TLO.New.getNode());
894
895   // Finally, if the node is now dead, remove it from the graph.  The node
896   // may not be dead if the replacement process recursively simplified to
897   // something else needing this node.
898   if (TLO.Old.getNode()->use_empty())
899     deleteAndRecombine(TLO.Old.getNode());
900 }
901
902 /// Check the specified integer node value to see if it can be simplified or if
903 /// things it uses can be simplified by bit propagation. If so, return true.
904 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
905   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
906   APInt KnownZero, KnownOne;
907   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
908     return false;
909
910   // Revisit the node.
911   AddToWorklist(Op.getNode());
912
913   // Replace the old value with the new one.
914   ++NodesCombined;
915   DEBUG(dbgs() << "\nReplacing.2 ";
916         TLO.Old.getNode()->dump(&DAG);
917         dbgs() << "\nWith: ";
918         TLO.New.getNode()->dump(&DAG);
919         dbgs() << '\n');
920
921   CommitTargetLoweringOpt(TLO);
922   return true;
923 }
924
925 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
926   SDLoc dl(Load);
927   EVT VT = Load->getValueType(0);
928   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
929
930   DEBUG(dbgs() << "\nReplacing.9 ";
931         Load->dump(&DAG);
932         dbgs() << "\nWith: ";
933         Trunc.getNode()->dump(&DAG);
934         dbgs() << '\n');
935   WorklistRemover DeadNodes(*this);
936   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
937   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
938   deleteAndRecombine(Load);
939   AddToWorklist(Trunc.getNode());
940 }
941
942 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
943   Replace = false;
944   SDLoc dl(Op);
945   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
946     EVT MemVT = LD->getMemoryVT();
947     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
948       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
949                                                        : ISD::EXTLOAD)
950       : LD->getExtensionType();
951     Replace = true;
952     return DAG.getExtLoad(ExtType, dl, PVT,
953                           LD->getChain(), LD->getBasePtr(),
954                           MemVT, LD->getMemOperand());
955   }
956
957   unsigned Opc = Op.getOpcode();
958   switch (Opc) {
959   default: break;
960   case ISD::AssertSext:
961     return DAG.getNode(ISD::AssertSext, dl, PVT,
962                        SExtPromoteOperand(Op.getOperand(0), PVT),
963                        Op.getOperand(1));
964   case ISD::AssertZext:
965     return DAG.getNode(ISD::AssertZext, dl, PVT,
966                        ZExtPromoteOperand(Op.getOperand(0), PVT),
967                        Op.getOperand(1));
968   case ISD::Constant: {
969     unsigned ExtOpc =
970       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
971     return DAG.getNode(ExtOpc, dl, PVT, Op);
972   }
973   }
974
975   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
976     return SDValue();
977   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
978 }
979
980 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
981   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
982     return SDValue();
983   EVT OldVT = Op.getValueType();
984   SDLoc dl(Op);
985   bool Replace = false;
986   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
987   if (!NewOp.getNode())
988     return SDValue();
989   AddToWorklist(NewOp.getNode());
990
991   if (Replace)
992     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
993   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
994                      DAG.getValueType(OldVT));
995 }
996
997 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
998   EVT OldVT = Op.getValueType();
999   SDLoc dl(Op);
1000   bool Replace = false;
1001   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1002   if (!NewOp.getNode())
1003     return SDValue();
1004   AddToWorklist(NewOp.getNode());
1005
1006   if (Replace)
1007     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1008   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1009 }
1010
1011 /// Promote the specified integer binary operation if the target indicates it is
1012 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1013 /// i32 since i16 instructions are longer.
1014 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1015   if (!LegalOperations)
1016     return SDValue();
1017
1018   EVT VT = Op.getValueType();
1019   if (VT.isVector() || !VT.isInteger())
1020     return SDValue();
1021
1022   // If operation type is 'undesirable', e.g. i16 on x86, consider
1023   // promoting it.
1024   unsigned Opc = Op.getOpcode();
1025   if (TLI.isTypeDesirableForOp(Opc, VT))
1026     return SDValue();
1027
1028   EVT PVT = VT;
1029   // Consult target whether it is a good idea to promote this operation and
1030   // what's the right type to promote it to.
1031   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1032     assert(PVT != VT && "Don't know what type to promote to!");
1033
1034     bool Replace0 = false;
1035     SDValue N0 = Op.getOperand(0);
1036     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1037     if (!NN0.getNode())
1038       return SDValue();
1039
1040     bool Replace1 = false;
1041     SDValue N1 = Op.getOperand(1);
1042     SDValue NN1;
1043     if (N0 == N1)
1044       NN1 = NN0;
1045     else {
1046       NN1 = PromoteOperand(N1, PVT, Replace1);
1047       if (!NN1.getNode())
1048         return SDValue();
1049     }
1050
1051     AddToWorklist(NN0.getNode());
1052     if (NN1.getNode())
1053       AddToWorklist(NN1.getNode());
1054
1055     if (Replace0)
1056       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1057     if (Replace1)
1058       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1059
1060     DEBUG(dbgs() << "\nPromoting ";
1061           Op.getNode()->dump(&DAG));
1062     SDLoc dl(Op);
1063     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1064                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1065   }
1066   return SDValue();
1067 }
1068
1069 /// Promote the specified integer shift operation if the target indicates it is
1070 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1071 /// i32 since i16 instructions are longer.
1072 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1073   if (!LegalOperations)
1074     return SDValue();
1075
1076   EVT VT = Op.getValueType();
1077   if (VT.isVector() || !VT.isInteger())
1078     return SDValue();
1079
1080   // If operation type is 'undesirable', e.g. i16 on x86, consider
1081   // promoting it.
1082   unsigned Opc = Op.getOpcode();
1083   if (TLI.isTypeDesirableForOp(Opc, VT))
1084     return SDValue();
1085
1086   EVT PVT = VT;
1087   // Consult target whether it is a good idea to promote this operation and
1088   // what's the right type to promote it to.
1089   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1090     assert(PVT != VT && "Don't know what type to promote to!");
1091
1092     bool Replace = false;
1093     SDValue N0 = Op.getOperand(0);
1094     if (Opc == ISD::SRA)
1095       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1096     else if (Opc == ISD::SRL)
1097       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1098     else
1099       N0 = PromoteOperand(N0, PVT, Replace);
1100     if (!N0.getNode())
1101       return SDValue();
1102
1103     AddToWorklist(N0.getNode());
1104     if (Replace)
1105       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1106
1107     DEBUG(dbgs() << "\nPromoting ";
1108           Op.getNode()->dump(&DAG));
1109     SDLoc dl(Op);
1110     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1111                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1112   }
1113   return SDValue();
1114 }
1115
1116 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1117   if (!LegalOperations)
1118     return SDValue();
1119
1120   EVT VT = Op.getValueType();
1121   if (VT.isVector() || !VT.isInteger())
1122     return SDValue();
1123
1124   // If operation type is 'undesirable', e.g. i16 on x86, consider
1125   // promoting it.
1126   unsigned Opc = Op.getOpcode();
1127   if (TLI.isTypeDesirableForOp(Opc, VT))
1128     return SDValue();
1129
1130   EVT PVT = VT;
1131   // Consult target whether it is a good idea to promote this operation and
1132   // what's the right type to promote it to.
1133   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1134     assert(PVT != VT && "Don't know what type to promote to!");
1135     // fold (aext (aext x)) -> (aext x)
1136     // fold (aext (zext x)) -> (zext x)
1137     // fold (aext (sext x)) -> (sext x)
1138     DEBUG(dbgs() << "\nPromoting ";
1139           Op.getNode()->dump(&DAG));
1140     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1141   }
1142   return SDValue();
1143 }
1144
1145 bool DAGCombiner::PromoteLoad(SDValue Op) {
1146   if (!LegalOperations)
1147     return false;
1148
1149   EVT VT = Op.getValueType();
1150   if (VT.isVector() || !VT.isInteger())
1151     return false;
1152
1153   // If operation type is 'undesirable', e.g. i16 on x86, consider
1154   // promoting it.
1155   unsigned Opc = Op.getOpcode();
1156   if (TLI.isTypeDesirableForOp(Opc, VT))
1157     return false;
1158
1159   EVT PVT = VT;
1160   // Consult target whether it is a good idea to promote this operation and
1161   // what's the right type to promote it to.
1162   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1163     assert(PVT != VT && "Don't know what type to promote to!");
1164
1165     SDLoc dl(Op);
1166     SDNode *N = Op.getNode();
1167     LoadSDNode *LD = cast<LoadSDNode>(N);
1168     EVT MemVT = LD->getMemoryVT();
1169     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1170       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1171                                                        : ISD::EXTLOAD)
1172       : LD->getExtensionType();
1173     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1174                                    LD->getChain(), LD->getBasePtr(),
1175                                    MemVT, LD->getMemOperand());
1176     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1177
1178     DEBUG(dbgs() << "\nPromoting ";
1179           N->dump(&DAG);
1180           dbgs() << "\nTo: ";
1181           Result.getNode()->dump(&DAG);
1182           dbgs() << '\n');
1183     WorklistRemover DeadNodes(*this);
1184     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1185     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1186     deleteAndRecombine(N);
1187     AddToWorklist(Result.getNode());
1188     return true;
1189   }
1190   return false;
1191 }
1192
1193 /// \brief Recursively delete a node which has no uses and any operands for
1194 /// which it is the only use.
1195 ///
1196 /// Note that this both deletes the nodes and removes them from the worklist.
1197 /// It also adds any nodes who have had a user deleted to the worklist as they
1198 /// may now have only one use and subject to other combines.
1199 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1200   if (!N->use_empty())
1201     return false;
1202
1203   SmallSetVector<SDNode *, 16> Nodes;
1204   Nodes.insert(N);
1205   do {
1206     N = Nodes.pop_back_val();
1207     if (!N)
1208       continue;
1209
1210     if (N->use_empty()) {
1211       for (const SDValue &ChildN : N->op_values())
1212         Nodes.insert(ChildN.getNode());
1213
1214       removeFromWorklist(N);
1215       DAG.DeleteNode(N);
1216     } else {
1217       AddToWorklist(N);
1218     }
1219   } while (!Nodes.empty());
1220   return true;
1221 }
1222
1223 //===----------------------------------------------------------------------===//
1224 //  Main DAG Combiner implementation
1225 //===----------------------------------------------------------------------===//
1226
1227 void DAGCombiner::Run(CombineLevel AtLevel) {
1228   // set the instance variables, so that the various visit routines may use it.
1229   Level = AtLevel;
1230   LegalOperations = Level >= AfterLegalizeVectorOps;
1231   LegalTypes = Level >= AfterLegalizeTypes;
1232
1233   // Add all the dag nodes to the worklist.
1234   for (SDNode &Node : DAG.allnodes())
1235     AddToWorklist(&Node);
1236
1237   // Create a dummy node (which is not added to allnodes), that adds a reference
1238   // to the root node, preventing it from being deleted, and tracking any
1239   // changes of the root.
1240   HandleSDNode Dummy(DAG.getRoot());
1241
1242   // while the worklist isn't empty, find a node and
1243   // try and combine it.
1244   while (!WorklistMap.empty()) {
1245     SDNode *N;
1246     // The Worklist holds the SDNodes in order, but it may contain null entries.
1247     do {
1248       N = Worklist.pop_back_val();
1249     } while (!N);
1250
1251     bool GoodWorklistEntry = WorklistMap.erase(N);
1252     (void)GoodWorklistEntry;
1253     assert(GoodWorklistEntry &&
1254            "Found a worklist entry without a corresponding map entry!");
1255
1256     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1257     // N is deleted from the DAG, since they too may now be dead or may have a
1258     // reduced number of uses, allowing other xforms.
1259     if (recursivelyDeleteUnusedNodes(N))
1260       continue;
1261
1262     WorklistRemover DeadNodes(*this);
1263
1264     // If this combine is running after legalizing the DAG, re-legalize any
1265     // nodes pulled off the worklist.
1266     if (Level == AfterLegalizeDAG) {
1267       SmallSetVector<SDNode *, 16> UpdatedNodes;
1268       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1269
1270       for (SDNode *LN : UpdatedNodes) {
1271         AddToWorklist(LN);
1272         AddUsersToWorklist(LN);
1273       }
1274       if (!NIsValid)
1275         continue;
1276     }
1277
1278     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1279
1280     // Add any operands of the new node which have not yet been combined to the
1281     // worklist as well. Because the worklist uniques things already, this
1282     // won't repeatedly process the same operand.
1283     CombinedNodes.insert(N);
1284     for (const SDValue &ChildN : N->op_values())
1285       if (!CombinedNodes.count(ChildN.getNode()))
1286         AddToWorklist(ChildN.getNode());
1287
1288     SDValue RV = combine(N);
1289
1290     if (!RV.getNode())
1291       continue;
1292
1293     ++NodesCombined;
1294
1295     // If we get back the same node we passed in, rather than a new node or
1296     // zero, we know that the node must have defined multiple values and
1297     // CombineTo was used.  Since CombineTo takes care of the worklist
1298     // mechanics for us, we have no work to do in this case.
1299     if (RV.getNode() == N)
1300       continue;
1301
1302     assert(N->getOpcode() != ISD::DELETED_NODE &&
1303            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1304            "Node was deleted but visit returned new node!");
1305
1306     DEBUG(dbgs() << " ... into: ";
1307           RV.getNode()->dump(&DAG));
1308
1309     // Transfer debug value.
1310     DAG.TransferDbgValues(SDValue(N, 0), RV);
1311     if (N->getNumValues() == RV.getNode()->getNumValues())
1312       DAG.ReplaceAllUsesWith(N, RV.getNode());
1313     else {
1314       assert(N->getValueType(0) == RV.getValueType() &&
1315              N->getNumValues() == 1 && "Type mismatch");
1316       SDValue OpV = RV;
1317       DAG.ReplaceAllUsesWith(N, &OpV);
1318     }
1319
1320     // Push the new node and any users onto the worklist
1321     AddToWorklist(RV.getNode());
1322     AddUsersToWorklist(RV.getNode());
1323
1324     // Finally, if the node is now dead, remove it from the graph.  The node
1325     // may not be dead if the replacement process recursively simplified to
1326     // something else needing this node. This will also take care of adding any
1327     // operands which have lost a user to the worklist.
1328     recursivelyDeleteUnusedNodes(N);
1329   }
1330
1331   // If the root changed (e.g. it was a dead load, update the root).
1332   DAG.setRoot(Dummy.getValue());
1333   DAG.RemoveDeadNodes();
1334 }
1335
1336 SDValue DAGCombiner::visit(SDNode *N) {
1337   switch (N->getOpcode()) {
1338   default: break;
1339   case ISD::TokenFactor:        return visitTokenFactor(N);
1340   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1341   case ISD::ADD:                return visitADD(N);
1342   case ISD::SUB:                return visitSUB(N);
1343   case ISD::ADDC:               return visitADDC(N);
1344   case ISD::SUBC:               return visitSUBC(N);
1345   case ISD::ADDE:               return visitADDE(N);
1346   case ISD::SUBE:               return visitSUBE(N);
1347   case ISD::MUL:                return visitMUL(N);
1348   case ISD::SDIV:               return visitSDIV(N);
1349   case ISD::UDIV:               return visitUDIV(N);
1350   case ISD::SREM:
1351   case ISD::UREM:               return visitREM(N);
1352   case ISD::MULHU:              return visitMULHU(N);
1353   case ISD::MULHS:              return visitMULHS(N);
1354   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1355   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1356   case ISD::SMULO:              return visitSMULO(N);
1357   case ISD::UMULO:              return visitUMULO(N);
1358   case ISD::SDIVREM:            return visitSDIVREM(N);
1359   case ISD::UDIVREM:            return visitUDIVREM(N);
1360   case ISD::SMIN:
1361   case ISD::SMAX:
1362   case ISD::UMIN:
1363   case ISD::UMAX:               return visitIMINMAX(N);
1364   case ISD::AND:                return visitAND(N);
1365   case ISD::OR:                 return visitOR(N);
1366   case ISD::XOR:                return visitXOR(N);
1367   case ISD::SHL:                return visitSHL(N);
1368   case ISD::SRA:                return visitSRA(N);
1369   case ISD::SRL:                return visitSRL(N);
1370   case ISD::ROTR:
1371   case ISD::ROTL:               return visitRotate(N);
1372   case ISD::BSWAP:              return visitBSWAP(N);
1373   case ISD::CTLZ:               return visitCTLZ(N);
1374   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1375   case ISD::CTTZ:               return visitCTTZ(N);
1376   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1377   case ISD::CTPOP:              return visitCTPOP(N);
1378   case ISD::SELECT:             return visitSELECT(N);
1379   case ISD::VSELECT:            return visitVSELECT(N);
1380   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1381   case ISD::SETCC:              return visitSETCC(N);
1382   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1383   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1384   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1385   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1386   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1387   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1388   case ISD::BITCAST:            return visitBITCAST(N);
1389   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1390   case ISD::FADD:               return visitFADD(N);
1391   case ISD::FSUB:               return visitFSUB(N);
1392   case ISD::FMUL:               return visitFMUL(N);
1393   case ISD::FMA:                return visitFMA(N);
1394   case ISD::FDIV:               return visitFDIV(N);
1395   case ISD::FREM:               return visitFREM(N);
1396   case ISD::FSQRT:              return visitFSQRT(N);
1397   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1398   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1399   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1400   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1401   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1402   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1403   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1404   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1405   case ISD::FNEG:               return visitFNEG(N);
1406   case ISD::FABS:               return visitFABS(N);
1407   case ISD::FFLOOR:             return visitFFLOOR(N);
1408   case ISD::FMINNUM:            return visitFMINNUM(N);
1409   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1410   case ISD::FCEIL:              return visitFCEIL(N);
1411   case ISD::FTRUNC:             return visitFTRUNC(N);
1412   case ISD::BRCOND:             return visitBRCOND(N);
1413   case ISD::BR_CC:              return visitBR_CC(N);
1414   case ISD::LOAD:               return visitLOAD(N);
1415   case ISD::STORE:              return visitSTORE(N);
1416   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1417   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1418   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1419   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1420   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1421   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1422   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1423   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1424   case ISD::MGATHER:            return visitMGATHER(N);
1425   case ISD::MLOAD:              return visitMLOAD(N);
1426   case ISD::MSCATTER:           return visitMSCATTER(N);
1427   case ISD::MSTORE:             return visitMSTORE(N);
1428   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1429   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1430   }
1431   return SDValue();
1432 }
1433
1434 SDValue DAGCombiner::combine(SDNode *N) {
1435   SDValue RV = visit(N);
1436
1437   // If nothing happened, try a target-specific DAG combine.
1438   if (!RV.getNode()) {
1439     assert(N->getOpcode() != ISD::DELETED_NODE &&
1440            "Node was deleted but visit returned NULL!");
1441
1442     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1443         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1444
1445       // Expose the DAG combiner to the target combiner impls.
1446       TargetLowering::DAGCombinerInfo
1447         DagCombineInfo(DAG, Level, false, this);
1448
1449       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1450     }
1451   }
1452
1453   // If nothing happened still, try promoting the operation.
1454   if (!RV.getNode()) {
1455     switch (N->getOpcode()) {
1456     default: break;
1457     case ISD::ADD:
1458     case ISD::SUB:
1459     case ISD::MUL:
1460     case ISD::AND:
1461     case ISD::OR:
1462     case ISD::XOR:
1463       RV = PromoteIntBinOp(SDValue(N, 0));
1464       break;
1465     case ISD::SHL:
1466     case ISD::SRA:
1467     case ISD::SRL:
1468       RV = PromoteIntShiftOp(SDValue(N, 0));
1469       break;
1470     case ISD::SIGN_EXTEND:
1471     case ISD::ZERO_EXTEND:
1472     case ISD::ANY_EXTEND:
1473       RV = PromoteExtend(SDValue(N, 0));
1474       break;
1475     case ISD::LOAD:
1476       if (PromoteLoad(SDValue(N, 0)))
1477         RV = SDValue(N, 0);
1478       break;
1479     }
1480   }
1481
1482   // If N is a commutative binary node, try commuting it to enable more
1483   // sdisel CSE.
1484   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1485       N->getNumValues() == 1) {
1486     SDValue N0 = N->getOperand(0);
1487     SDValue N1 = N->getOperand(1);
1488
1489     // Constant operands are canonicalized to RHS.
1490     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1491       SDValue Ops[] = {N1, N0};
1492       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1493                                             N->getFlags());
1494       if (CSENode)
1495         return SDValue(CSENode, 0);
1496     }
1497   }
1498
1499   return RV;
1500 }
1501
1502 /// Given a node, return its input chain if it has one, otherwise return a null
1503 /// sd operand.
1504 static SDValue getInputChainForNode(SDNode *N) {
1505   if (unsigned NumOps = N->getNumOperands()) {
1506     if (N->getOperand(0).getValueType() == MVT::Other)
1507       return N->getOperand(0);
1508     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1509       return N->getOperand(NumOps-1);
1510     for (unsigned i = 1; i < NumOps-1; ++i)
1511       if (N->getOperand(i).getValueType() == MVT::Other)
1512         return N->getOperand(i);
1513   }
1514   return SDValue();
1515 }
1516
1517 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1518   // If N has two operands, where one has an input chain equal to the other,
1519   // the 'other' chain is redundant.
1520   if (N->getNumOperands() == 2) {
1521     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1522       return N->getOperand(0);
1523     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1524       return N->getOperand(1);
1525   }
1526
1527   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1528   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1529   SmallPtrSet<SDNode*, 16> SeenOps;
1530   bool Changed = false;             // If we should replace this token factor.
1531
1532   // Start out with this token factor.
1533   TFs.push_back(N);
1534
1535   // Iterate through token factors.  The TFs grows when new token factors are
1536   // encountered.
1537   for (unsigned i = 0; i < TFs.size(); ++i) {
1538     SDNode *TF = TFs[i];
1539
1540     // Check each of the operands.
1541     for (const SDValue &Op : TF->op_values()) {
1542
1543       switch (Op.getOpcode()) {
1544       case ISD::EntryToken:
1545         // Entry tokens don't need to be added to the list. They are
1546         // redundant.
1547         Changed = true;
1548         break;
1549
1550       case ISD::TokenFactor:
1551         if (Op.hasOneUse() &&
1552             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1553           // Queue up for processing.
1554           TFs.push_back(Op.getNode());
1555           // Clean up in case the token factor is removed.
1556           AddToWorklist(Op.getNode());
1557           Changed = true;
1558           break;
1559         }
1560         // Fall thru
1561
1562       default:
1563         // Only add if it isn't already in the list.
1564         if (SeenOps.insert(Op.getNode()).second)
1565           Ops.push_back(Op);
1566         else
1567           Changed = true;
1568         break;
1569       }
1570     }
1571   }
1572
1573   SDValue Result;
1574
1575   // If we've changed things around then replace token factor.
1576   if (Changed) {
1577     if (Ops.empty()) {
1578       // The entry token is the only possible outcome.
1579       Result = DAG.getEntryNode();
1580     } else {
1581       // New and improved token factor.
1582       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1583     }
1584
1585     // Add users to worklist if AA is enabled, since it may introduce
1586     // a lot of new chained token factors while removing memory deps.
1587     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1588       : DAG.getSubtarget().useAA();
1589     return CombineTo(N, Result, UseAA /*add to worklist*/);
1590   }
1591
1592   return Result;
1593 }
1594
1595 /// MERGE_VALUES can always be eliminated.
1596 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1597   WorklistRemover DeadNodes(*this);
1598   // Replacing results may cause a different MERGE_VALUES to suddenly
1599   // be CSE'd with N, and carry its uses with it. Iterate until no
1600   // uses remain, to ensure that the node can be safely deleted.
1601   // First add the users of this node to the work list so that they
1602   // can be tried again once they have new operands.
1603   AddUsersToWorklist(N);
1604   do {
1605     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1606       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1607   } while (!N->use_empty());
1608   deleteAndRecombine(N);
1609   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1610 }
1611
1612 static bool isNullConstant(SDValue V) {
1613   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1614   return Const != nullptr && Const->isNullValue();
1615 }
1616
1617 static bool isNullFPConstant(SDValue V) {
1618   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1619   return Const != nullptr && Const->isZero() && !Const->isNegative();
1620 }
1621
1622 static bool isAllOnesConstant(SDValue V) {
1623   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1624   return Const != nullptr && Const->isAllOnesValue();
1625 }
1626
1627 static bool isOneConstant(SDValue V) {
1628   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1629   return Const != nullptr && Const->isOne();
1630 }
1631
1632 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1633 /// ContantSDNode pointer else nullptr.
1634 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1635   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1636   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1637 }
1638
1639 SDValue DAGCombiner::visitADD(SDNode *N) {
1640   SDValue N0 = N->getOperand(0);
1641   SDValue N1 = N->getOperand(1);
1642   EVT VT = N0.getValueType();
1643
1644   // fold vector ops
1645   if (VT.isVector()) {
1646     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1647       return FoldedVOp;
1648
1649     // fold (add x, 0) -> x, vector edition
1650     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1651       return N0;
1652     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1653       return N1;
1654   }
1655
1656   // fold (add x, undef) -> undef
1657   if (N0.getOpcode() == ISD::UNDEF)
1658     return N0;
1659   if (N1.getOpcode() == ISD::UNDEF)
1660     return N1;
1661   // fold (add c1, c2) -> c1+c2
1662   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1663   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1664   if (N0C && N1C)
1665     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1666   // canonicalize constant to RHS
1667   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1668      !isConstantIntBuildVectorOrConstantInt(N1))
1669     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1670   // fold (add x, 0) -> x
1671   if (isNullConstant(N1))
1672     return N0;
1673   // fold (add Sym, c) -> Sym+c
1674   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1675     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1676         GA->getOpcode() == ISD::GlobalAddress)
1677       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1678                                   GA->getOffset() +
1679                                     (uint64_t)N1C->getSExtValue());
1680   // fold ((c1-A)+c2) -> (c1+c2)-A
1681   if (N1C && N0.getOpcode() == ISD::SUB)
1682     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1683       SDLoc DL(N);
1684       return DAG.getNode(ISD::SUB, DL, VT,
1685                          DAG.getConstant(N1C->getAPIntValue()+
1686                                          N0C->getAPIntValue(), DL, VT),
1687                          N0.getOperand(1));
1688     }
1689   // reassociate add
1690   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1691     return RADD;
1692   // fold ((0-A) + B) -> B-A
1693   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1694     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1695   // fold (A + (0-B)) -> A-B
1696   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1697     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1698   // fold (A+(B-A)) -> B
1699   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1700     return N1.getOperand(0);
1701   // fold ((B-A)+A) -> B
1702   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1703     return N0.getOperand(0);
1704   // fold (A+(B-(A+C))) to (B-C)
1705   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1706       N0 == N1.getOperand(1).getOperand(0))
1707     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1708                        N1.getOperand(1).getOperand(1));
1709   // fold (A+(B-(C+A))) to (B-C)
1710   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1711       N0 == N1.getOperand(1).getOperand(1))
1712     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1713                        N1.getOperand(1).getOperand(0));
1714   // fold (A+((B-A)+or-C)) to (B+or-C)
1715   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1716       N1.getOperand(0).getOpcode() == ISD::SUB &&
1717       N0 == N1.getOperand(0).getOperand(1))
1718     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1719                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1720
1721   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1722   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1723     SDValue N00 = N0.getOperand(0);
1724     SDValue N01 = N0.getOperand(1);
1725     SDValue N10 = N1.getOperand(0);
1726     SDValue N11 = N1.getOperand(1);
1727
1728     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1729       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1730                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1731                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1732   }
1733
1734   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1735     return SDValue(N, 0);
1736
1737   // fold (a+b) -> (a|b) iff a and b share no bits.
1738   if (VT.isInteger() && !VT.isVector()) {
1739     APInt LHSZero, LHSOne;
1740     APInt RHSZero, RHSOne;
1741     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1742
1743     if (LHSZero.getBoolValue()) {
1744       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1745
1746       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1747       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1748       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1749         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1750           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1751       }
1752     }
1753   }
1754
1755   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1756   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1757       isNullConstant(N1.getOperand(0).getOperand(0)))
1758     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1759                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1760                                    N1.getOperand(0).getOperand(1),
1761                                    N1.getOperand(1)));
1762   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1763       isNullConstant(N0.getOperand(0).getOperand(0)))
1764     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1765                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1766                                    N0.getOperand(0).getOperand(1),
1767                                    N0.getOperand(1)));
1768
1769   if (N1.getOpcode() == ISD::AND) {
1770     SDValue AndOp0 = N1.getOperand(0);
1771     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1772     unsigned DestBits = VT.getScalarType().getSizeInBits();
1773
1774     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1775     // and similar xforms where the inner op is either ~0 or 0.
1776     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1777       SDLoc DL(N);
1778       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1779     }
1780   }
1781
1782   // add (sext i1), X -> sub X, (zext i1)
1783   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1784       N0.getOperand(0).getValueType() == MVT::i1 &&
1785       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1786     SDLoc DL(N);
1787     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1788     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1789   }
1790
1791   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1792   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1793     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1794     if (TN->getVT() == MVT::i1) {
1795       SDLoc DL(N);
1796       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1797                                  DAG.getConstant(1, DL, VT));
1798       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1799     }
1800   }
1801
1802   return SDValue();
1803 }
1804
1805 SDValue DAGCombiner::visitADDC(SDNode *N) {
1806   SDValue N0 = N->getOperand(0);
1807   SDValue N1 = N->getOperand(1);
1808   EVT VT = N0.getValueType();
1809
1810   // If the flag result is dead, turn this into an ADD.
1811   if (!N->hasAnyUseOfValue(1))
1812     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1813                      DAG.getNode(ISD::CARRY_FALSE,
1814                                  SDLoc(N), MVT::Glue));
1815
1816   // canonicalize constant to RHS.
1817   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1818   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1819   if (N0C && !N1C)
1820     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1821
1822   // fold (addc x, 0) -> x + no carry out
1823   if (isNullConstant(N1))
1824     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1825                                         SDLoc(N), MVT::Glue));
1826
1827   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1828   APInt LHSZero, LHSOne;
1829   APInt RHSZero, RHSOne;
1830   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1831
1832   if (LHSZero.getBoolValue()) {
1833     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1834
1835     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1836     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1837     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1838       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1839                        DAG.getNode(ISD::CARRY_FALSE,
1840                                    SDLoc(N), MVT::Glue));
1841   }
1842
1843   return SDValue();
1844 }
1845
1846 SDValue DAGCombiner::visitADDE(SDNode *N) {
1847   SDValue N0 = N->getOperand(0);
1848   SDValue N1 = N->getOperand(1);
1849   SDValue CarryIn = N->getOperand(2);
1850
1851   // canonicalize constant to RHS
1852   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1853   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1854   if (N0C && !N1C)
1855     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1856                        N1, N0, CarryIn);
1857
1858   // fold (adde x, y, false) -> (addc x, y)
1859   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1860     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1861
1862   return SDValue();
1863 }
1864
1865 // Since it may not be valid to emit a fold to zero for vector initializers
1866 // check if we can before folding.
1867 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1868                              SelectionDAG &DAG,
1869                              bool LegalOperations, bool LegalTypes) {
1870   if (!VT.isVector())
1871     return DAG.getConstant(0, DL, VT);
1872   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1873     return DAG.getConstant(0, DL, VT);
1874   return SDValue();
1875 }
1876
1877 SDValue DAGCombiner::visitSUB(SDNode *N) {
1878   SDValue N0 = N->getOperand(0);
1879   SDValue N1 = N->getOperand(1);
1880   EVT VT = N0.getValueType();
1881
1882   // fold vector ops
1883   if (VT.isVector()) {
1884     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1885       return FoldedVOp;
1886
1887     // fold (sub x, 0) -> x, vector edition
1888     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1889       return N0;
1890   }
1891
1892   // fold (sub x, x) -> 0
1893   // FIXME: Refactor this and xor and other similar operations together.
1894   if (N0 == N1)
1895     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1896   // fold (sub c1, c2) -> c1-c2
1897   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1898   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1899   if (N0C && N1C)
1900     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1901   // fold (sub x, c) -> (add x, -c)
1902   if (N1C) {
1903     SDLoc DL(N);
1904     return DAG.getNode(ISD::ADD, DL, VT, N0,
1905                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1906   }
1907   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1908   if (isAllOnesConstant(N0))
1909     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1910   // fold A-(A-B) -> B
1911   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1912     return N1.getOperand(1);
1913   // fold (A+B)-A -> B
1914   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1915     return N0.getOperand(1);
1916   // fold (A+B)-B -> A
1917   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1918     return N0.getOperand(0);
1919   // fold C2-(A+C1) -> (C2-C1)-A
1920   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1921     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1922   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1923     SDLoc DL(N);
1924     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1925                                    DL, VT);
1926     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1927                        N1.getOperand(0));
1928   }
1929   // fold ((A+(B+or-C))-B) -> A+or-C
1930   if (N0.getOpcode() == ISD::ADD &&
1931       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1932        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1933       N0.getOperand(1).getOperand(0) == N1)
1934     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1935                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1936   // fold ((A+(C+B))-B) -> A+C
1937   if (N0.getOpcode() == ISD::ADD &&
1938       N0.getOperand(1).getOpcode() == ISD::ADD &&
1939       N0.getOperand(1).getOperand(1) == N1)
1940     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1941                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1942   // fold ((A-(B-C))-C) -> A-B
1943   if (N0.getOpcode() == ISD::SUB &&
1944       N0.getOperand(1).getOpcode() == ISD::SUB &&
1945       N0.getOperand(1).getOperand(1) == N1)
1946     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1947                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1948
1949   // If either operand of a sub is undef, the result is undef
1950   if (N0.getOpcode() == ISD::UNDEF)
1951     return N0;
1952   if (N1.getOpcode() == ISD::UNDEF)
1953     return N1;
1954
1955   // If the relocation model supports it, consider symbol offsets.
1956   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1957     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1958       // fold (sub Sym, c) -> Sym-c
1959       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1960         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1961                                     GA->getOffset() -
1962                                       (uint64_t)N1C->getSExtValue());
1963       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1964       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1965         if (GA->getGlobal() == GB->getGlobal())
1966           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1967                                  SDLoc(N), VT);
1968     }
1969
1970   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1971   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1972     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1973     if (TN->getVT() == MVT::i1) {
1974       SDLoc DL(N);
1975       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1976                                  DAG.getConstant(1, DL, VT));
1977       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1978     }
1979   }
1980
1981   return SDValue();
1982 }
1983
1984 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1985   SDValue N0 = N->getOperand(0);
1986   SDValue N1 = N->getOperand(1);
1987   EVT VT = N0.getValueType();
1988
1989   // If the flag result is dead, turn this into an SUB.
1990   if (!N->hasAnyUseOfValue(1))
1991     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1992                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1993                                  MVT::Glue));
1994
1995   // fold (subc x, x) -> 0 + no borrow
1996   if (N0 == N1) {
1997     SDLoc DL(N);
1998     return CombineTo(N, DAG.getConstant(0, DL, VT),
1999                      DAG.getNode(ISD::CARRY_FALSE, DL,
2000                                  MVT::Glue));
2001   }
2002
2003   // fold (subc x, 0) -> x + no borrow
2004   if (isNullConstant(N1))
2005     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2006                                         MVT::Glue));
2007
2008   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2009   if (isAllOnesConstant(N0))
2010     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2011                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2012                                  MVT::Glue));
2013
2014   return SDValue();
2015 }
2016
2017 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2018   SDValue N0 = N->getOperand(0);
2019   SDValue N1 = N->getOperand(1);
2020   SDValue CarryIn = N->getOperand(2);
2021
2022   // fold (sube x, y, false) -> (subc x, y)
2023   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2024     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2025
2026   return SDValue();
2027 }
2028
2029 SDValue DAGCombiner::visitMUL(SDNode *N) {
2030   SDValue N0 = N->getOperand(0);
2031   SDValue N1 = N->getOperand(1);
2032   EVT VT = N0.getValueType();
2033
2034   // fold (mul x, undef) -> 0
2035   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2036     return DAG.getConstant(0, SDLoc(N), VT);
2037
2038   bool N0IsConst = false;
2039   bool N1IsConst = false;
2040   bool N1IsOpaqueConst = false;
2041   bool N0IsOpaqueConst = false;
2042   APInt ConstValue0, ConstValue1;
2043   // fold vector ops
2044   if (VT.isVector()) {
2045     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2046       return FoldedVOp;
2047
2048     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2049     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2050   } else {
2051     N0IsConst = isa<ConstantSDNode>(N0);
2052     if (N0IsConst) {
2053       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2054       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2055     }
2056     N1IsConst = isa<ConstantSDNode>(N1);
2057     if (N1IsConst) {
2058       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2059       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2060     }
2061   }
2062
2063   // fold (mul c1, c2) -> c1*c2
2064   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2065     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2066                                       N0.getNode(), N1.getNode());
2067
2068   // canonicalize constant to RHS (vector doesn't have to splat)
2069   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2070      !isConstantIntBuildVectorOrConstantInt(N1))
2071     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2072   // fold (mul x, 0) -> 0
2073   if (N1IsConst && ConstValue1 == 0)
2074     return N1;
2075   // We require a splat of the entire scalar bit width for non-contiguous
2076   // bit patterns.
2077   bool IsFullSplat =
2078     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2079   // fold (mul x, 1) -> x
2080   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2081     return N0;
2082   // fold (mul x, -1) -> 0-x
2083   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2084     SDLoc DL(N);
2085     return DAG.getNode(ISD::SUB, DL, VT,
2086                        DAG.getConstant(0, DL, VT), N0);
2087   }
2088   // fold (mul x, (1 << c)) -> x << c
2089   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2090       IsFullSplat) {
2091     SDLoc DL(N);
2092     return DAG.getNode(ISD::SHL, DL, VT, N0,
2093                        DAG.getConstant(ConstValue1.logBase2(), DL,
2094                                        getShiftAmountTy(N0.getValueType())));
2095   }
2096   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2097   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2098       IsFullSplat) {
2099     unsigned Log2Val = (-ConstValue1).logBase2();
2100     SDLoc DL(N);
2101     // FIXME: If the input is something that is easily negated (e.g. a
2102     // single-use add), we should put the negate there.
2103     return DAG.getNode(ISD::SUB, DL, VT,
2104                        DAG.getConstant(0, DL, VT),
2105                        DAG.getNode(ISD::SHL, DL, VT, N0,
2106                             DAG.getConstant(Log2Val, DL,
2107                                       getShiftAmountTy(N0.getValueType()))));
2108   }
2109
2110   APInt Val;
2111   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2112   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2113       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2114                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2115     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2116                              N1, N0.getOperand(1));
2117     AddToWorklist(C3.getNode());
2118     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2119                        N0.getOperand(0), C3);
2120   }
2121
2122   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2123   // use.
2124   {
2125     SDValue Sh(nullptr,0), Y(nullptr,0);
2126     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2127     if (N0.getOpcode() == ISD::SHL &&
2128         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2129                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2130         N0.getNode()->hasOneUse()) {
2131       Sh = N0; Y = N1;
2132     } else if (N1.getOpcode() == ISD::SHL &&
2133                isa<ConstantSDNode>(N1.getOperand(1)) &&
2134                N1.getNode()->hasOneUse()) {
2135       Sh = N1; Y = N0;
2136     }
2137
2138     if (Sh.getNode()) {
2139       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2140                                 Sh.getOperand(0), Y);
2141       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2142                          Mul, Sh.getOperand(1));
2143     }
2144   }
2145
2146   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2147   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2148       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2149                      isa<ConstantSDNode>(N0.getOperand(1))))
2150     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2151                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2152                                    N0.getOperand(0), N1),
2153                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2154                                    N0.getOperand(1), N1));
2155
2156   // reassociate mul
2157   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2158     return RMUL;
2159
2160   return SDValue();
2161 }
2162
2163 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2164   SDValue N0 = N->getOperand(0);
2165   SDValue N1 = N->getOperand(1);
2166   EVT VT = N->getValueType(0);
2167
2168   // fold vector ops
2169   if (VT.isVector())
2170     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2171       return FoldedVOp;
2172
2173   // fold (sdiv c1, c2) -> c1/c2
2174   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2175   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2176   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2177     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2178   // fold (sdiv X, 1) -> X
2179   if (N1C && N1C->isOne())
2180     return N0;
2181   // fold (sdiv X, -1) -> 0-X
2182   if (N1C && N1C->isAllOnesValue()) {
2183     SDLoc DL(N);
2184     return DAG.getNode(ISD::SUB, DL, VT,
2185                        DAG.getConstant(0, DL, VT), N0);
2186   }
2187   // If we know the sign bits of both operands are zero, strength reduce to a
2188   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2189   if (!VT.isVector()) {
2190     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2191       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2192                          N0, N1);
2193   }
2194
2195   // fold (sdiv X, pow2) -> simple ops after legalize
2196   // FIXME: We check for the exact bit here because the generic lowering gives
2197   // better results in that case. The target-specific lowering should learn how
2198   // to handle exact sdivs efficiently.
2199   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2200       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2201       (N1C->getAPIntValue().isPowerOf2() ||
2202        (-N1C->getAPIntValue()).isPowerOf2())) {
2203     // Target-specific implementation of sdiv x, pow2.
2204     if (SDValue Res = BuildSDIVPow2(N))
2205       return Res;
2206
2207     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2208     SDLoc DL(N);
2209
2210     // Splat the sign bit into the register
2211     SDValue SGN =
2212         DAG.getNode(ISD::SRA, DL, VT, N0,
2213                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2214                                     getShiftAmountTy(N0.getValueType())));
2215     AddToWorklist(SGN.getNode());
2216
2217     // Add (N0 < 0) ? abs2 - 1 : 0;
2218     SDValue SRL =
2219         DAG.getNode(ISD::SRL, DL, VT, SGN,
2220                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2221                                     getShiftAmountTy(SGN.getValueType())));
2222     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2223     AddToWorklist(SRL.getNode());
2224     AddToWorklist(ADD.getNode());    // Divide by pow2
2225     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2226                   DAG.getConstant(lg2, DL,
2227                                   getShiftAmountTy(ADD.getValueType())));
2228
2229     // If we're dividing by a positive value, we're done.  Otherwise, we must
2230     // negate the result.
2231     if (N1C->getAPIntValue().isNonNegative())
2232       return SRA;
2233
2234     AddToWorklist(SRA.getNode());
2235     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2236   }
2237
2238   // If integer divide is expensive and we satisfy the requirements, emit an
2239   // alternate sequence.  Targets may check function attributes for size/speed
2240   // trade-offs.
2241   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2242   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2243     if (SDValue Op = BuildSDIV(N))
2244       return Op;
2245
2246   // undef / X -> 0
2247   if (N0.getOpcode() == ISD::UNDEF)
2248     return DAG.getConstant(0, SDLoc(N), VT);
2249   // X / undef -> undef
2250   if (N1.getOpcode() == ISD::UNDEF)
2251     return N1;
2252
2253   return SDValue();
2254 }
2255
2256 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2257   SDValue N0 = N->getOperand(0);
2258   SDValue N1 = N->getOperand(1);
2259   EVT VT = N->getValueType(0);
2260
2261   // fold vector ops
2262   if (VT.isVector())
2263     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2264       return FoldedVOp;
2265
2266   // fold (udiv c1, c2) -> c1/c2
2267   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2268   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2269   if (N0C && N1C)
2270     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2271                                                     N0C, N1C))
2272       return Folded;
2273   // fold (udiv x, (1 << c)) -> x >>u c
2274   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2275     SDLoc DL(N);
2276     return DAG.getNode(ISD::SRL, DL, VT, N0,
2277                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2278                                        getShiftAmountTy(N0.getValueType())));
2279   }
2280   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2281   if (N1.getOpcode() == ISD::SHL) {
2282     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2283       if (SHC->getAPIntValue().isPowerOf2()) {
2284         EVT ADDVT = N1.getOperand(1).getValueType();
2285         SDLoc DL(N);
2286         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2287                                   N1.getOperand(1),
2288                                   DAG.getConstant(SHC->getAPIntValue()
2289                                                                   .logBase2(),
2290                                                   DL, ADDVT));
2291         AddToWorklist(Add.getNode());
2292         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2293       }
2294     }
2295   }
2296
2297   // fold (udiv x, c) -> alternate
2298   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2299   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2300     if (SDValue Op = BuildUDIV(N))
2301       return Op;
2302
2303   // undef / X -> 0
2304   if (N0.getOpcode() == ISD::UNDEF)
2305     return DAG.getConstant(0, SDLoc(N), VT);
2306   // X / undef -> undef
2307   if (N1.getOpcode() == ISD::UNDEF)
2308     return N1;
2309
2310   return SDValue();
2311 }
2312
2313 // handles ISD::SREM and ISD::UREM
2314 SDValue DAGCombiner::visitREM(SDNode *N) {
2315   unsigned Opcode = N->getOpcode();
2316   SDValue N0 = N->getOperand(0);
2317   SDValue N1 = N->getOperand(1);
2318   EVT VT = N->getValueType(0);
2319
2320   // fold (rem c1, c2) -> c1%c2
2321   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2322   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2323   if (N0C && N1C)
2324     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, SDLoc(N), VT,
2325                                                     N0C, N1C))
2326       return Folded;
2327
2328   if (Opcode == ISD::SREM) {
2329     // If we know the sign bits of both operands are zero, strength reduce to a
2330     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2331     if (!VT.isVector()) {
2332       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2333         return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2334     }
2335   } else {
2336     // fold (urem x, pow2) -> (and x, pow2-1)
2337     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2338         N1C->getAPIntValue().isPowerOf2()) {
2339       SDLoc DL(N);
2340       return DAG.getNode(ISD::AND, DL, VT, N0,
2341                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2342     }
2343     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2344     if (N1.getOpcode() == ISD::SHL) {
2345       if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2346         if (SHC->getAPIntValue().isPowerOf2()) {
2347           SDLoc DL(N);
2348           SDValue Add =
2349             DAG.getNode(ISD::ADD, DL, VT, N1,
2350                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2351                                  VT));
2352           AddToWorklist(Add.getNode());
2353           return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2354         }
2355       }
2356     }
2357   }
2358
2359   // If X/C can be simplified by the division-by-constant logic, lower
2360   // X%C to the equivalent of X-X/C*C.
2361   if (N1C && !N1C->isNullValue()) {
2362     unsigned DivOpcode = (Opcode == ISD::SREM ? ISD::SDIV : ISD::UDIV);
2363     SDValue Div = DAG.getNode(DivOpcode, SDLoc(N), VT, N0, N1);
2364     AddToWorklist(Div.getNode());
2365     SDValue OptimizedDiv = combine(Div.getNode());
2366     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2367       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2368                                 OptimizedDiv, N1);
2369       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2370       AddToWorklist(Mul.getNode());
2371       return Sub;
2372     }
2373   }
2374
2375   // undef % X -> 0
2376   if (N0.getOpcode() == ISD::UNDEF)
2377     return DAG.getConstant(0, SDLoc(N), VT);
2378   // X % undef -> undef
2379   if (N1.getOpcode() == ISD::UNDEF)
2380     return N1;
2381
2382   return SDValue();
2383 }
2384
2385 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2386   SDValue N0 = N->getOperand(0);
2387   SDValue N1 = N->getOperand(1);
2388   EVT VT = N->getValueType(0);
2389   SDLoc DL(N);
2390
2391   // fold (mulhs x, 0) -> 0
2392   if (isNullConstant(N1))
2393     return N1;
2394   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2395   if (isOneConstant(N1)) {
2396     SDLoc DL(N);
2397     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2398                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2399                                        DL,
2400                                        getShiftAmountTy(N0.getValueType())));
2401   }
2402   // fold (mulhs x, undef) -> 0
2403   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2404     return DAG.getConstant(0, SDLoc(N), VT);
2405
2406   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2407   // plus a shift.
2408   if (VT.isSimple() && !VT.isVector()) {
2409     MVT Simple = VT.getSimpleVT();
2410     unsigned SimpleSize = Simple.getSizeInBits();
2411     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2412     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2413       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2414       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2415       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2416       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2417             DAG.getConstant(SimpleSize, DL,
2418                             getShiftAmountTy(N1.getValueType())));
2419       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2420     }
2421   }
2422
2423   return SDValue();
2424 }
2425
2426 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2427   SDValue N0 = N->getOperand(0);
2428   SDValue N1 = N->getOperand(1);
2429   EVT VT = N->getValueType(0);
2430   SDLoc DL(N);
2431
2432   // fold (mulhu x, 0) -> 0
2433   if (isNullConstant(N1))
2434     return N1;
2435   // fold (mulhu x, 1) -> 0
2436   if (isOneConstant(N1))
2437     return DAG.getConstant(0, DL, N0.getValueType());
2438   // fold (mulhu x, undef) -> 0
2439   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2440     return DAG.getConstant(0, DL, VT);
2441
2442   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2443   // plus a shift.
2444   if (VT.isSimple() && !VT.isVector()) {
2445     MVT Simple = VT.getSimpleVT();
2446     unsigned SimpleSize = Simple.getSizeInBits();
2447     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2448     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2449       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2450       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2451       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2452       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2453             DAG.getConstant(SimpleSize, DL,
2454                             getShiftAmountTy(N1.getValueType())));
2455       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2456     }
2457   }
2458
2459   return SDValue();
2460 }
2461
2462 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2463 /// give the opcodes for the two computations that are being performed. Return
2464 /// true if a simplification was made.
2465 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2466                                                 unsigned HiOp) {
2467   // If the high half is not needed, just compute the low half.
2468   bool HiExists = N->hasAnyUseOfValue(1);
2469   if (!HiExists &&
2470       (!LegalOperations ||
2471        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2472     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2473     return CombineTo(N, Res, Res);
2474   }
2475
2476   // If the low half is not needed, just compute the high half.
2477   bool LoExists = N->hasAnyUseOfValue(0);
2478   if (!LoExists &&
2479       (!LegalOperations ||
2480        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2481     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2482     return CombineTo(N, Res, Res);
2483   }
2484
2485   // If both halves are used, return as it is.
2486   if (LoExists && HiExists)
2487     return SDValue();
2488
2489   // If the two computed results can be simplified separately, separate them.
2490   if (LoExists) {
2491     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2492     AddToWorklist(Lo.getNode());
2493     SDValue LoOpt = combine(Lo.getNode());
2494     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2495         (!LegalOperations ||
2496          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2497       return CombineTo(N, LoOpt, LoOpt);
2498   }
2499
2500   if (HiExists) {
2501     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2502     AddToWorklist(Hi.getNode());
2503     SDValue HiOpt = combine(Hi.getNode());
2504     if (HiOpt.getNode() && HiOpt != Hi &&
2505         (!LegalOperations ||
2506          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2507       return CombineTo(N, HiOpt, HiOpt);
2508   }
2509
2510   return SDValue();
2511 }
2512
2513 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2514   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2515     return Res;
2516
2517   EVT VT = N->getValueType(0);
2518   SDLoc DL(N);
2519
2520   // If the type is twice as wide is legal, transform the mulhu to a wider
2521   // multiply plus a shift.
2522   if (VT.isSimple() && !VT.isVector()) {
2523     MVT Simple = VT.getSimpleVT();
2524     unsigned SimpleSize = Simple.getSizeInBits();
2525     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2526     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2527       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2528       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2529       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2530       // Compute the high part as N1.
2531       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2532             DAG.getConstant(SimpleSize, DL,
2533                             getShiftAmountTy(Lo.getValueType())));
2534       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2535       // Compute the low part as N0.
2536       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2537       return CombineTo(N, Lo, Hi);
2538     }
2539   }
2540
2541   return SDValue();
2542 }
2543
2544 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2545   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2546     return Res;
2547
2548   EVT VT = N->getValueType(0);
2549   SDLoc DL(N);
2550
2551   // If the type is twice as wide is legal, transform the mulhu to a wider
2552   // multiply plus a shift.
2553   if (VT.isSimple() && !VT.isVector()) {
2554     MVT Simple = VT.getSimpleVT();
2555     unsigned SimpleSize = Simple.getSizeInBits();
2556     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2557     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2558       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2559       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2560       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2561       // Compute the high part as N1.
2562       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2563             DAG.getConstant(SimpleSize, DL,
2564                             getShiftAmountTy(Lo.getValueType())));
2565       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2566       // Compute the low part as N0.
2567       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2568       return CombineTo(N, Lo, Hi);
2569     }
2570   }
2571
2572   return SDValue();
2573 }
2574
2575 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2576   // (smulo x, 2) -> (saddo x, x)
2577   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2578     if (C2->getAPIntValue() == 2)
2579       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2580                          N->getOperand(0), N->getOperand(0));
2581
2582   return SDValue();
2583 }
2584
2585 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2586   // (umulo x, 2) -> (uaddo x, x)
2587   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2588     if (C2->getAPIntValue() == 2)
2589       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2590                          N->getOperand(0), N->getOperand(0));
2591
2592   return SDValue();
2593 }
2594
2595 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2596   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2597     return Res;
2598
2599   return SDValue();
2600 }
2601
2602 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2603   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2604     return Res;
2605
2606   return SDValue();
2607 }
2608
2609 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2610   SDValue N0 = N->getOperand(0);
2611   SDValue N1 = N->getOperand(1);
2612   EVT VT = N0.getValueType();
2613
2614   // fold vector ops
2615   if (VT.isVector())
2616     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2617       return FoldedVOp;
2618
2619   // fold (add c1, c2) -> c1+c2
2620   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2621   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2622   if (N0C && N1C)
2623     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2624
2625   // canonicalize constant to RHS
2626   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2627      !isConstantIntBuildVectorOrConstantInt(N1))
2628     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2629
2630   return SDValue();
2631 }
2632
2633 /// If this is a binary operator with two operands of the same opcode, try to
2634 /// simplify it.
2635 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2636   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2637   EVT VT = N0.getValueType();
2638   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2639
2640   // Bail early if none of these transforms apply.
2641   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2642
2643   // For each of OP in AND/OR/XOR:
2644   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2645   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2646   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2647   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2648   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2649   //
2650   // do not sink logical op inside of a vector extend, since it may combine
2651   // into a vsetcc.
2652   EVT Op0VT = N0.getOperand(0).getValueType();
2653   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2654        N0.getOpcode() == ISD::SIGN_EXTEND ||
2655        N0.getOpcode() == ISD::BSWAP ||
2656        // Avoid infinite looping with PromoteIntBinOp.
2657        (N0.getOpcode() == ISD::ANY_EXTEND &&
2658         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2659        (N0.getOpcode() == ISD::TRUNCATE &&
2660         (!TLI.isZExtFree(VT, Op0VT) ||
2661          !TLI.isTruncateFree(Op0VT, VT)) &&
2662         TLI.isTypeLegal(Op0VT))) &&
2663       !VT.isVector() &&
2664       Op0VT == N1.getOperand(0).getValueType() &&
2665       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2666     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2667                                  N0.getOperand(0).getValueType(),
2668                                  N0.getOperand(0), N1.getOperand(0));
2669     AddToWorklist(ORNode.getNode());
2670     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2671   }
2672
2673   // For each of OP in SHL/SRL/SRA/AND...
2674   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2675   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2676   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2677   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2678        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2679       N0.getOperand(1) == N1.getOperand(1)) {
2680     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2681                                  N0.getOperand(0).getValueType(),
2682                                  N0.getOperand(0), N1.getOperand(0));
2683     AddToWorklist(ORNode.getNode());
2684     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2685                        ORNode, N0.getOperand(1));
2686   }
2687
2688   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2689   // Only perform this optimization after type legalization and before
2690   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2691   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2692   // we don't want to undo this promotion.
2693   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2694   // on scalars.
2695   if ((N0.getOpcode() == ISD::BITCAST ||
2696        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2697       Level == AfterLegalizeTypes) {
2698     SDValue In0 = N0.getOperand(0);
2699     SDValue In1 = N1.getOperand(0);
2700     EVT In0Ty = In0.getValueType();
2701     EVT In1Ty = In1.getValueType();
2702     SDLoc DL(N);
2703     // If both incoming values are integers, and the original types are the
2704     // same.
2705     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2706       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2707       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2708       AddToWorklist(Op.getNode());
2709       return BC;
2710     }
2711   }
2712
2713   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2714   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2715   // If both shuffles use the same mask, and both shuffle within a single
2716   // vector, then it is worthwhile to move the swizzle after the operation.
2717   // The type-legalizer generates this pattern when loading illegal
2718   // vector types from memory. In many cases this allows additional shuffle
2719   // optimizations.
2720   // There are other cases where moving the shuffle after the xor/and/or
2721   // is profitable even if shuffles don't perform a swizzle.
2722   // If both shuffles use the same mask, and both shuffles have the same first
2723   // or second operand, then it might still be profitable to move the shuffle
2724   // after the xor/and/or operation.
2725   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2726     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2727     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2728
2729     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2730            "Inputs to shuffles are not the same type");
2731
2732     // Check that both shuffles use the same mask. The masks are known to be of
2733     // the same length because the result vector type is the same.
2734     // Check also that shuffles have only one use to avoid introducing extra
2735     // instructions.
2736     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2737         SVN0->getMask().equals(SVN1->getMask())) {
2738       SDValue ShOp = N0->getOperand(1);
2739
2740       // Don't try to fold this node if it requires introducing a
2741       // build vector of all zeros that might be illegal at this stage.
2742       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2743         if (!LegalTypes)
2744           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2745         else
2746           ShOp = SDValue();
2747       }
2748
2749       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2750       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2751       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2752       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2753         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2754                                       N0->getOperand(0), N1->getOperand(0));
2755         AddToWorklist(NewNode.getNode());
2756         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2757                                     &SVN0->getMask()[0]);
2758       }
2759
2760       // Don't try to fold this node if it requires introducing a
2761       // build vector of all zeros that might be illegal at this stage.
2762       ShOp = N0->getOperand(0);
2763       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2764         if (!LegalTypes)
2765           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2766         else
2767           ShOp = SDValue();
2768       }
2769
2770       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2771       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2772       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2773       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2774         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2775                                       N0->getOperand(1), N1->getOperand(1));
2776         AddToWorklist(NewNode.getNode());
2777         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2778                                     &SVN0->getMask()[0]);
2779       }
2780     }
2781   }
2782
2783   return SDValue();
2784 }
2785
2786 /// This contains all DAGCombine rules which reduce two values combined by
2787 /// an And operation to a single value. This makes them reusable in the context
2788 /// of visitSELECT(). Rules involving constants are not included as
2789 /// visitSELECT() already handles those cases.
2790 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2791                                   SDNode *LocReference) {
2792   EVT VT = N1.getValueType();
2793
2794   // fold (and x, undef) -> 0
2795   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2796     return DAG.getConstant(0, SDLoc(LocReference), VT);
2797   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2798   SDValue LL, LR, RL, RR, CC0, CC1;
2799   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2800     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2801     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2802
2803     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2804         LL.getValueType().isInteger()) {
2805       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2806       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2807         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2808                                      LR.getValueType(), LL, RL);
2809         AddToWorklist(ORNode.getNode());
2810         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2811       }
2812       if (isAllOnesConstant(LR)) {
2813         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2814         if (Op1 == ISD::SETEQ) {
2815           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2816                                         LR.getValueType(), LL, RL);
2817           AddToWorklist(ANDNode.getNode());
2818           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2819         }
2820         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2821         if (Op1 == ISD::SETGT) {
2822           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2823                                        LR.getValueType(), LL, RL);
2824           AddToWorklist(ORNode.getNode());
2825           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2826         }
2827       }
2828     }
2829     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2830     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2831         Op0 == Op1 && LL.getValueType().isInteger() &&
2832       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2833                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2834       SDLoc DL(N0);
2835       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2836                                     LL, DAG.getConstant(1, DL,
2837                                                         LL.getValueType()));
2838       AddToWorklist(ADDNode.getNode());
2839       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2840                           DAG.getConstant(2, DL, LL.getValueType()),
2841                           ISD::SETUGE);
2842     }
2843     // canonicalize equivalent to ll == rl
2844     if (LL == RR && LR == RL) {
2845       Op1 = ISD::getSetCCSwappedOperands(Op1);
2846       std::swap(RL, RR);
2847     }
2848     if (LL == RL && LR == RR) {
2849       bool isInteger = LL.getValueType().isInteger();
2850       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2851       if (Result != ISD::SETCC_INVALID &&
2852           (!LegalOperations ||
2853            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2854             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2855         EVT CCVT = getSetCCResultType(LL.getValueType());
2856         if (N0.getValueType() == CCVT ||
2857             (!LegalOperations && N0.getValueType() == MVT::i1))
2858           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2859                               LL, LR, Result);
2860       }
2861     }
2862   }
2863
2864   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2865       VT.getSizeInBits() <= 64) {
2866     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2867       APInt ADDC = ADDI->getAPIntValue();
2868       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2869         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2870         // immediate for an add, but it is legal if its top c2 bits are set,
2871         // transform the ADD so the immediate doesn't need to be materialized
2872         // in a register.
2873         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2874           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2875                                              SRLI->getZExtValue());
2876           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2877             ADDC |= Mask;
2878             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2879               SDLoc DL(N0);
2880               SDValue NewAdd =
2881                 DAG.getNode(ISD::ADD, DL, VT,
2882                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2883               CombineTo(N0.getNode(), NewAdd);
2884               // Return N so it doesn't get rechecked!
2885               return SDValue(LocReference, 0);
2886             }
2887           }
2888         }
2889       }
2890     }
2891   }
2892
2893   return SDValue();
2894 }
2895
2896 SDValue DAGCombiner::visitAND(SDNode *N) {
2897   SDValue N0 = N->getOperand(0);
2898   SDValue N1 = N->getOperand(1);
2899   EVT VT = N1.getValueType();
2900
2901   // fold vector ops
2902   if (VT.isVector()) {
2903     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2904       return FoldedVOp;
2905
2906     // fold (and x, 0) -> 0, vector edition
2907     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2908       // do not return N0, because undef node may exist in N0
2909       return DAG.getConstant(
2910           APInt::getNullValue(
2911               N0.getValueType().getScalarType().getSizeInBits()),
2912           SDLoc(N), N0.getValueType());
2913     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2914       // do not return N1, because undef node may exist in N1
2915       return DAG.getConstant(
2916           APInt::getNullValue(
2917               N1.getValueType().getScalarType().getSizeInBits()),
2918           SDLoc(N), N1.getValueType());
2919
2920     // fold (and x, -1) -> x, vector edition
2921     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2922       return N1;
2923     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2924       return N0;
2925   }
2926
2927   // fold (and c1, c2) -> c1&c2
2928   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2929   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2930   if (N0C && N1C && !N1C->isOpaque())
2931     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2932   // canonicalize constant to RHS
2933   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2934      !isConstantIntBuildVectorOrConstantInt(N1))
2935     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2936   // fold (and x, -1) -> x
2937   if (isAllOnesConstant(N1))
2938     return N0;
2939   // if (and x, c) is known to be zero, return 0
2940   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2941   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2942                                    APInt::getAllOnesValue(BitWidth)))
2943     return DAG.getConstant(0, SDLoc(N), VT);
2944   // reassociate and
2945   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2946     return RAND;
2947   // fold (and (or x, C), D) -> D if (C & D) == D
2948   if (N1C && N0.getOpcode() == ISD::OR)
2949     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2950       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2951         return N1;
2952   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2953   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2954     SDValue N0Op0 = N0.getOperand(0);
2955     APInt Mask = ~N1C->getAPIntValue();
2956     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2957     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2958       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2959                                  N0.getValueType(), N0Op0);
2960
2961       // Replace uses of the AND with uses of the Zero extend node.
2962       CombineTo(N, Zext);
2963
2964       // We actually want to replace all uses of the any_extend with the
2965       // zero_extend, to avoid duplicating things.  This will later cause this
2966       // AND to be folded.
2967       CombineTo(N0.getNode(), Zext);
2968       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2969     }
2970   }
2971   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2972   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2973   // already be zero by virtue of the width of the base type of the load.
2974   //
2975   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2976   // more cases.
2977   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2978        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2979       N0.getOpcode() == ISD::LOAD) {
2980     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2981                                          N0 : N0.getOperand(0) );
2982
2983     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2984     // This can be a pure constant or a vector splat, in which case we treat the
2985     // vector as a scalar and use the splat value.
2986     APInt Constant = APInt::getNullValue(1);
2987     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2988       Constant = C->getAPIntValue();
2989     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2990       APInt SplatValue, SplatUndef;
2991       unsigned SplatBitSize;
2992       bool HasAnyUndefs;
2993       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2994                                              SplatBitSize, HasAnyUndefs);
2995       if (IsSplat) {
2996         // Undef bits can contribute to a possible optimisation if set, so
2997         // set them.
2998         SplatValue |= SplatUndef;
2999
3000         // The splat value may be something like "0x00FFFFFF", which means 0 for
3001         // the first vector value and FF for the rest, repeating. We need a mask
3002         // that will apply equally to all members of the vector, so AND all the
3003         // lanes of the constant together.
3004         EVT VT = Vector->getValueType(0);
3005         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3006
3007         // If the splat value has been compressed to a bitlength lower
3008         // than the size of the vector lane, we need to re-expand it to
3009         // the lane size.
3010         if (BitWidth > SplatBitSize)
3011           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3012                SplatBitSize < BitWidth;
3013                SplatBitSize = SplatBitSize * 2)
3014             SplatValue |= SplatValue.shl(SplatBitSize);
3015
3016         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3017         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3018         if (SplatBitSize % BitWidth == 0) {
3019           Constant = APInt::getAllOnesValue(BitWidth);
3020           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3021             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3022         }
3023       }
3024     }
3025
3026     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3027     // actually legal and isn't going to get expanded, else this is a false
3028     // optimisation.
3029     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3030                                                     Load->getValueType(0),
3031                                                     Load->getMemoryVT());
3032
3033     // Resize the constant to the same size as the original memory access before
3034     // extension. If it is still the AllOnesValue then this AND is completely
3035     // unneeded.
3036     Constant =
3037       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3038
3039     bool B;
3040     switch (Load->getExtensionType()) {
3041     default: B = false; break;
3042     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3043     case ISD::ZEXTLOAD:
3044     case ISD::NON_EXTLOAD: B = true; break;
3045     }
3046
3047     if (B && Constant.isAllOnesValue()) {
3048       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3049       // preserve semantics once we get rid of the AND.
3050       SDValue NewLoad(Load, 0);
3051       if (Load->getExtensionType() == ISD::EXTLOAD) {
3052         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3053                               Load->getValueType(0), SDLoc(Load),
3054                               Load->getChain(), Load->getBasePtr(),
3055                               Load->getOffset(), Load->getMemoryVT(),
3056                               Load->getMemOperand());
3057         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3058         if (Load->getNumValues() == 3) {
3059           // PRE/POST_INC loads have 3 values.
3060           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3061                            NewLoad.getValue(2) };
3062           CombineTo(Load, To, 3, true);
3063         } else {
3064           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3065         }
3066       }
3067
3068       // Fold the AND away, taking care not to fold to the old load node if we
3069       // replaced it.
3070       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3071
3072       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3073     }
3074   }
3075
3076   // fold (and (load x), 255) -> (zextload x, i8)
3077   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3078   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3079   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3080               (N0.getOpcode() == ISD::ANY_EXTEND &&
3081                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3082     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3083     LoadSDNode *LN0 = HasAnyExt
3084       ? cast<LoadSDNode>(N0.getOperand(0))
3085       : cast<LoadSDNode>(N0);
3086     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3087         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3088       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3089       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3090         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3091         EVT LoadedVT = LN0->getMemoryVT();
3092         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3093
3094         if (ExtVT == LoadedVT &&
3095             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3096                                                     ExtVT))) {
3097
3098           SDValue NewLoad =
3099             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3100                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3101                            LN0->getMemOperand());
3102           AddToWorklist(N);
3103           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3104           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3105         }
3106
3107         // Do not change the width of a volatile load.
3108         // Do not generate loads of non-round integer types since these can
3109         // be expensive (and would be wrong if the type is not byte sized).
3110         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3111             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3112                                                     ExtVT))) {
3113           EVT PtrType = LN0->getOperand(1).getValueType();
3114
3115           unsigned Alignment = LN0->getAlignment();
3116           SDValue NewPtr = LN0->getBasePtr();
3117
3118           // For big endian targets, we need to add an offset to the pointer
3119           // to load the correct bytes.  For little endian systems, we merely
3120           // need to read fewer bytes from the same pointer.
3121           if (DAG.getDataLayout().isBigEndian()) {
3122             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3123             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3124             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3125             SDLoc DL(LN0);
3126             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3127                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3128             Alignment = MinAlign(Alignment, PtrOff);
3129           }
3130
3131           AddToWorklist(NewPtr.getNode());
3132
3133           SDValue Load =
3134             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3135                            LN0->getChain(), NewPtr,
3136                            LN0->getPointerInfo(),
3137                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3138                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3139           AddToWorklist(N);
3140           CombineTo(LN0, Load, Load.getValue(1));
3141           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3142         }
3143       }
3144     }
3145   }
3146
3147   if (SDValue Combined = visitANDLike(N0, N1, N))
3148     return Combined;
3149
3150   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3151   if (N0.getOpcode() == N1.getOpcode())
3152     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3153       return Tmp;
3154
3155   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3156   // fold (and (sra)) -> (and (srl)) when possible.
3157   if (!VT.isVector() &&
3158       SimplifyDemandedBits(SDValue(N, 0)))
3159     return SDValue(N, 0);
3160
3161   // fold (zext_inreg (extload x)) -> (zextload x)
3162   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3163     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3164     EVT MemVT = LN0->getMemoryVT();
3165     // If we zero all the possible extended bits, then we can turn this into
3166     // a zextload if we are running before legalize or the operation is legal.
3167     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3168     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3169                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3170         ((!LegalOperations && !LN0->isVolatile()) ||
3171          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3172       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3173                                        LN0->getChain(), LN0->getBasePtr(),
3174                                        MemVT, LN0->getMemOperand());
3175       AddToWorklist(N);
3176       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3177       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3178     }
3179   }
3180   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3181   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3182       N0.hasOneUse()) {
3183     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3184     EVT MemVT = LN0->getMemoryVT();
3185     // If we zero all the possible extended bits, then we can turn this into
3186     // a zextload if we are running before legalize or the operation is legal.
3187     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3188     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3189                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3190         ((!LegalOperations && !LN0->isVolatile()) ||
3191          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3192       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3193                                        LN0->getChain(), LN0->getBasePtr(),
3194                                        MemVT, LN0->getMemOperand());
3195       AddToWorklist(N);
3196       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3197       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3198     }
3199   }
3200   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3201   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3202     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3203                                        N0.getOperand(1), false);
3204     if (BSwap.getNode())
3205       return BSwap;
3206   }
3207
3208   return SDValue();
3209 }
3210
3211 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3212 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3213                                         bool DemandHighBits) {
3214   if (!LegalOperations)
3215     return SDValue();
3216
3217   EVT VT = N->getValueType(0);
3218   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3219     return SDValue();
3220   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3221     return SDValue();
3222
3223   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3224   bool LookPassAnd0 = false;
3225   bool LookPassAnd1 = false;
3226   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3227       std::swap(N0, N1);
3228   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3229       std::swap(N0, N1);
3230   if (N0.getOpcode() == ISD::AND) {
3231     if (!N0.getNode()->hasOneUse())
3232       return SDValue();
3233     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3234     if (!N01C || N01C->getZExtValue() != 0xFF00)
3235       return SDValue();
3236     N0 = N0.getOperand(0);
3237     LookPassAnd0 = true;
3238   }
3239
3240   if (N1.getOpcode() == ISD::AND) {
3241     if (!N1.getNode()->hasOneUse())
3242       return SDValue();
3243     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3244     if (!N11C || N11C->getZExtValue() != 0xFF)
3245       return SDValue();
3246     N1 = N1.getOperand(0);
3247     LookPassAnd1 = true;
3248   }
3249
3250   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3251     std::swap(N0, N1);
3252   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3253     return SDValue();
3254   if (!N0.getNode()->hasOneUse() ||
3255       !N1.getNode()->hasOneUse())
3256     return SDValue();
3257
3258   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3259   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3260   if (!N01C || !N11C)
3261     return SDValue();
3262   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3263     return SDValue();
3264
3265   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3266   SDValue N00 = N0->getOperand(0);
3267   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3268     if (!N00.getNode()->hasOneUse())
3269       return SDValue();
3270     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3271     if (!N001C || N001C->getZExtValue() != 0xFF)
3272       return SDValue();
3273     N00 = N00.getOperand(0);
3274     LookPassAnd0 = true;
3275   }
3276
3277   SDValue N10 = N1->getOperand(0);
3278   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3279     if (!N10.getNode()->hasOneUse())
3280       return SDValue();
3281     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3282     if (!N101C || N101C->getZExtValue() != 0xFF00)
3283       return SDValue();
3284     N10 = N10.getOperand(0);
3285     LookPassAnd1 = true;
3286   }
3287
3288   if (N00 != N10)
3289     return SDValue();
3290
3291   // Make sure everything beyond the low halfword gets set to zero since the SRL
3292   // 16 will clear the top bits.
3293   unsigned OpSizeInBits = VT.getSizeInBits();
3294   if (DemandHighBits && OpSizeInBits > 16) {
3295     // If the left-shift isn't masked out then the only way this is a bswap is
3296     // if all bits beyond the low 8 are 0. In that case the entire pattern
3297     // reduces to a left shift anyway: leave it for other parts of the combiner.
3298     if (!LookPassAnd0)
3299       return SDValue();
3300
3301     // However, if the right shift isn't masked out then it might be because
3302     // it's not needed. See if we can spot that too.
3303     if (!LookPassAnd1 &&
3304         !DAG.MaskedValueIsZero(
3305             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3306       return SDValue();
3307   }
3308
3309   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3310   if (OpSizeInBits > 16) {
3311     SDLoc DL(N);
3312     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3313                       DAG.getConstant(OpSizeInBits - 16, DL,
3314                                       getShiftAmountTy(VT)));
3315   }
3316   return Res;
3317 }
3318
3319 /// Return true if the specified node is an element that makes up a 32-bit
3320 /// packed halfword byteswap.
3321 /// ((x & 0x000000ff) << 8) |
3322 /// ((x & 0x0000ff00) >> 8) |
3323 /// ((x & 0x00ff0000) << 8) |
3324 /// ((x & 0xff000000) >> 8)
3325 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3326   if (!N.getNode()->hasOneUse())
3327     return false;
3328
3329   unsigned Opc = N.getOpcode();
3330   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3331     return false;
3332
3333   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3334   if (!N1C)
3335     return false;
3336
3337   unsigned Num;
3338   switch (N1C->getZExtValue()) {
3339   default:
3340     return false;
3341   case 0xFF:       Num = 0; break;
3342   case 0xFF00:     Num = 1; break;
3343   case 0xFF0000:   Num = 2; break;
3344   case 0xFF000000: Num = 3; break;
3345   }
3346
3347   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3348   SDValue N0 = N.getOperand(0);
3349   if (Opc == ISD::AND) {
3350     if (Num == 0 || Num == 2) {
3351       // (x >> 8) & 0xff
3352       // (x >> 8) & 0xff0000
3353       if (N0.getOpcode() != ISD::SRL)
3354         return false;
3355       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3356       if (!C || C->getZExtValue() != 8)
3357         return false;
3358     } else {
3359       // (x << 8) & 0xff00
3360       // (x << 8) & 0xff000000
3361       if (N0.getOpcode() != ISD::SHL)
3362         return false;
3363       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3364       if (!C || C->getZExtValue() != 8)
3365         return false;
3366     }
3367   } else if (Opc == ISD::SHL) {
3368     // (x & 0xff) << 8
3369     // (x & 0xff0000) << 8
3370     if (Num != 0 && Num != 2)
3371       return false;
3372     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3373     if (!C || C->getZExtValue() != 8)
3374       return false;
3375   } else { // Opc == ISD::SRL
3376     // (x & 0xff00) >> 8
3377     // (x & 0xff000000) >> 8
3378     if (Num != 1 && Num != 3)
3379       return false;
3380     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3381     if (!C || C->getZExtValue() != 8)
3382       return false;
3383   }
3384
3385   if (Parts[Num])
3386     return false;
3387
3388   Parts[Num] = N0.getOperand(0).getNode();
3389   return true;
3390 }
3391
3392 /// Match a 32-bit packed halfword bswap. That is
3393 /// ((x & 0x000000ff) << 8) |
3394 /// ((x & 0x0000ff00) >> 8) |
3395 /// ((x & 0x00ff0000) << 8) |
3396 /// ((x & 0xff000000) >> 8)
3397 /// => (rotl (bswap x), 16)
3398 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3399   if (!LegalOperations)
3400     return SDValue();
3401
3402   EVT VT = N->getValueType(0);
3403   if (VT != MVT::i32)
3404     return SDValue();
3405   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3406     return SDValue();
3407
3408   // Look for either
3409   // (or (or (and), (and)), (or (and), (and)))
3410   // (or (or (or (and), (and)), (and)), (and))
3411   if (N0.getOpcode() != ISD::OR)
3412     return SDValue();
3413   SDValue N00 = N0.getOperand(0);
3414   SDValue N01 = N0.getOperand(1);
3415   SDNode *Parts[4] = {};
3416
3417   if (N1.getOpcode() == ISD::OR &&
3418       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3419     // (or (or (and), (and)), (or (and), (and)))
3420     SDValue N000 = N00.getOperand(0);
3421     if (!isBSwapHWordElement(N000, Parts))
3422       return SDValue();
3423
3424     SDValue N001 = N00.getOperand(1);
3425     if (!isBSwapHWordElement(N001, Parts))
3426       return SDValue();
3427     SDValue N010 = N01.getOperand(0);
3428     if (!isBSwapHWordElement(N010, Parts))
3429       return SDValue();
3430     SDValue N011 = N01.getOperand(1);
3431     if (!isBSwapHWordElement(N011, Parts))
3432       return SDValue();
3433   } else {
3434     // (or (or (or (and), (and)), (and)), (and))
3435     if (!isBSwapHWordElement(N1, Parts))
3436       return SDValue();
3437     if (!isBSwapHWordElement(N01, Parts))
3438       return SDValue();
3439     if (N00.getOpcode() != ISD::OR)
3440       return SDValue();
3441     SDValue N000 = N00.getOperand(0);
3442     if (!isBSwapHWordElement(N000, Parts))
3443       return SDValue();
3444     SDValue N001 = N00.getOperand(1);
3445     if (!isBSwapHWordElement(N001, Parts))
3446       return SDValue();
3447   }
3448
3449   // Make sure the parts are all coming from the same node.
3450   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3451     return SDValue();
3452
3453   SDLoc DL(N);
3454   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3455                               SDValue(Parts[0], 0));
3456
3457   // Result of the bswap should be rotated by 16. If it's not legal, then
3458   // do  (x << 16) | (x >> 16).
3459   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3460   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3461     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3462   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3463     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3464   return DAG.getNode(ISD::OR, DL, VT,
3465                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3466                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3467 }
3468
3469 /// This contains all DAGCombine rules which reduce two values combined by
3470 /// an Or operation to a single value \see visitANDLike().
3471 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3472   EVT VT = N1.getValueType();
3473   // fold (or x, undef) -> -1
3474   if (!LegalOperations &&
3475       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3476     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3477     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3478                            SDLoc(LocReference), VT);
3479   }
3480   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3481   SDValue LL, LR, RL, RR, CC0, CC1;
3482   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3483     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3484     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3485
3486     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3487       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3488       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3489       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3490         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3491                                      LR.getValueType(), LL, RL);
3492         AddToWorklist(ORNode.getNode());
3493         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3494       }
3495       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3496       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3497       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3498         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3499                                       LR.getValueType(), LL, RL);
3500         AddToWorklist(ANDNode.getNode());
3501         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3502       }
3503     }
3504     // canonicalize equivalent to ll == rl
3505     if (LL == RR && LR == RL) {
3506       Op1 = ISD::getSetCCSwappedOperands(Op1);
3507       std::swap(RL, RR);
3508     }
3509     if (LL == RL && LR == RR) {
3510       bool isInteger = LL.getValueType().isInteger();
3511       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3512       if (Result != ISD::SETCC_INVALID &&
3513           (!LegalOperations ||
3514            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3515             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3516         EVT CCVT = getSetCCResultType(LL.getValueType());
3517         if (N0.getValueType() == CCVT ||
3518             (!LegalOperations && N0.getValueType() == MVT::i1))
3519           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3520                               LL, LR, Result);
3521       }
3522     }
3523   }
3524
3525   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3526   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3527       // Don't increase # computations.
3528       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3529     // We can only do this xform if we know that bits from X that are set in C2
3530     // but not in C1 are already zero.  Likewise for Y.
3531     if (const ConstantSDNode *N0O1C =
3532         getAsNonOpaqueConstant(N0.getOperand(1))) {
3533       if (const ConstantSDNode *N1O1C =
3534           getAsNonOpaqueConstant(N1.getOperand(1))) {
3535         // We can only do this xform if we know that bits from X that are set in
3536         // C2 but not in C1 are already zero.  Likewise for Y.
3537         const APInt &LHSMask = N0O1C->getAPIntValue();
3538         const APInt &RHSMask = N1O1C->getAPIntValue();
3539
3540         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3541             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3542           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3543                                   N0.getOperand(0), N1.getOperand(0));
3544           SDLoc DL(LocReference);
3545           return DAG.getNode(ISD::AND, DL, VT, X,
3546                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3547         }
3548       }
3549     }
3550   }
3551
3552   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3553   if (N0.getOpcode() == ISD::AND &&
3554       N1.getOpcode() == ISD::AND &&
3555       N0.getOperand(0) == N1.getOperand(0) &&
3556       // Don't increase # computations.
3557       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3558     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3559                             N0.getOperand(1), N1.getOperand(1));
3560     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3561   }
3562
3563   return SDValue();
3564 }
3565
3566 SDValue DAGCombiner::visitOR(SDNode *N) {
3567   SDValue N0 = N->getOperand(0);
3568   SDValue N1 = N->getOperand(1);
3569   EVT VT = N1.getValueType();
3570
3571   // fold vector ops
3572   if (VT.isVector()) {
3573     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3574       return FoldedVOp;
3575
3576     // fold (or x, 0) -> x, vector edition
3577     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3578       return N1;
3579     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3580       return N0;
3581
3582     // fold (or x, -1) -> -1, vector edition
3583     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3584       // do not return N0, because undef node may exist in N0
3585       return DAG.getConstant(
3586           APInt::getAllOnesValue(
3587               N0.getValueType().getScalarType().getSizeInBits()),
3588           SDLoc(N), N0.getValueType());
3589     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3590       // do not return N1, because undef node may exist in N1
3591       return DAG.getConstant(
3592           APInt::getAllOnesValue(
3593               N1.getValueType().getScalarType().getSizeInBits()),
3594           SDLoc(N), N1.getValueType());
3595
3596     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3597     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3598     // Do this only if the resulting shuffle is legal.
3599     if (isa<ShuffleVectorSDNode>(N0) &&
3600         isa<ShuffleVectorSDNode>(N1) &&
3601         // Avoid folding a node with illegal type.
3602         TLI.isTypeLegal(VT) &&
3603         N0->getOperand(1) == N1->getOperand(1) &&
3604         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3605       bool CanFold = true;
3606       unsigned NumElts = VT.getVectorNumElements();
3607       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3608       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3609       // We construct two shuffle masks:
3610       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3611       // and N1 as the second operand.
3612       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3613       // and N0 as the second operand.
3614       // We do this because OR is commutable and therefore there might be
3615       // two ways to fold this node into a shuffle.
3616       SmallVector<int,4> Mask1;
3617       SmallVector<int,4> Mask2;
3618
3619       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3620         int M0 = SV0->getMaskElt(i);
3621         int M1 = SV1->getMaskElt(i);
3622
3623         // Both shuffle indexes are undef. Propagate Undef.
3624         if (M0 < 0 && M1 < 0) {
3625           Mask1.push_back(M0);
3626           Mask2.push_back(M0);
3627           continue;
3628         }
3629
3630         if (M0 < 0 || M1 < 0 ||
3631             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3632             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3633           CanFold = false;
3634           break;
3635         }
3636
3637         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3638         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3639       }
3640
3641       if (CanFold) {
3642         // Fold this sequence only if the resulting shuffle is 'legal'.
3643         if (TLI.isShuffleMaskLegal(Mask1, VT))
3644           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3645                                       N1->getOperand(0), &Mask1[0]);
3646         if (TLI.isShuffleMaskLegal(Mask2, VT))
3647           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3648                                       N0->getOperand(0), &Mask2[0]);
3649       }
3650     }
3651   }
3652
3653   // fold (or c1, c2) -> c1|c2
3654   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3655   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3656   if (N0C && N1C && !N1C->isOpaque())
3657     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3658   // canonicalize constant to RHS
3659   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3660      !isConstantIntBuildVectorOrConstantInt(N1))
3661     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3662   // fold (or x, 0) -> x
3663   if (isNullConstant(N1))
3664     return N0;
3665   // fold (or x, -1) -> -1
3666   if (isAllOnesConstant(N1))
3667     return N1;
3668   // fold (or x, c) -> c iff (x & ~c) == 0
3669   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3670     return N1;
3671
3672   if (SDValue Combined = visitORLike(N0, N1, N))
3673     return Combined;
3674
3675   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3676   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3677     return BSwap;
3678   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3679     return BSwap;
3680
3681   // reassociate or
3682   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3683     return ROR;
3684   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3685   // iff (c1 & c2) == 0.
3686   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3687              isa<ConstantSDNode>(N0.getOperand(1))) {
3688     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3689     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3690       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3691                                                    N1C, C1))
3692         return DAG.getNode(
3693             ISD::AND, SDLoc(N), VT,
3694             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3695       return SDValue();
3696     }
3697   }
3698   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3699   if (N0.getOpcode() == N1.getOpcode())
3700     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3701       return Tmp;
3702
3703   // See if this is some rotate idiom.
3704   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3705     return SDValue(Rot, 0);
3706
3707   // Simplify the operands using demanded-bits information.
3708   if (!VT.isVector() &&
3709       SimplifyDemandedBits(SDValue(N, 0)))
3710     return SDValue(N, 0);
3711
3712   return SDValue();
3713 }
3714
3715 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3716 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3717   if (Op.getOpcode() == ISD::AND) {
3718     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3719       Mask = Op.getOperand(1);
3720       Op = Op.getOperand(0);
3721     } else {
3722       return false;
3723     }
3724   }
3725
3726   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3727     Shift = Op;
3728     return true;
3729   }
3730
3731   return false;
3732 }
3733
3734 // Return true if we can prove that, whenever Neg and Pos are both in the
3735 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3736 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3737 //
3738 //     (or (shift1 X, Neg), (shift2 X, Pos))
3739 //
3740 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3741 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3742 // to consider shift amounts with defined behavior.
3743 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3744   // If OpSize is a power of 2 then:
3745   //
3746   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3747   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3748   //
3749   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3750   // for the stronger condition:
3751   //
3752   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3753   //
3754   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3755   // we can just replace Neg with Neg' for the rest of the function.
3756   //
3757   // In other cases we check for the even stronger condition:
3758   //
3759   //     Neg == OpSize - Pos                                    [B]
3760   //
3761   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3762   // behavior if Pos == 0 (and consequently Neg == OpSize).
3763   //
3764   // We could actually use [A] whenever OpSize is a power of 2, but the
3765   // only extra cases that it would match are those uninteresting ones
3766   // where Neg and Pos are never in range at the same time.  E.g. for
3767   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3768   // as well as (sub 32, Pos), but:
3769   //
3770   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3771   //
3772   // always invokes undefined behavior for 32-bit X.
3773   //
3774   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3775   unsigned MaskLoBits = 0;
3776   if (Neg.getOpcode() == ISD::AND &&
3777       isPowerOf2_64(OpSize) &&
3778       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3779       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3780     Neg = Neg.getOperand(0);
3781     MaskLoBits = Log2_64(OpSize);
3782   }
3783
3784   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3785   if (Neg.getOpcode() != ISD::SUB)
3786     return 0;
3787   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3788   if (!NegC)
3789     return 0;
3790   SDValue NegOp1 = Neg.getOperand(1);
3791
3792   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3793   // Pos'.  The truncation is redundant for the purpose of the equality.
3794   if (MaskLoBits &&
3795       Pos.getOpcode() == ISD::AND &&
3796       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3797       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3798     Pos = Pos.getOperand(0);
3799
3800   // The condition we need is now:
3801   //
3802   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3803   //
3804   // If NegOp1 == Pos then we need:
3805   //
3806   //              OpSize & Mask == NegC & Mask
3807   //
3808   // (because "x & Mask" is a truncation and distributes through subtraction).
3809   APInt Width;
3810   if (Pos == NegOp1)
3811     Width = NegC->getAPIntValue();
3812   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3813   // Then the condition we want to prove becomes:
3814   //
3815   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3816   //
3817   // which, again because "x & Mask" is a truncation, becomes:
3818   //
3819   //                NegC & Mask == (OpSize - PosC) & Mask
3820   //              OpSize & Mask == (NegC + PosC) & Mask
3821   else if (Pos.getOpcode() == ISD::ADD &&
3822            Pos.getOperand(0) == NegOp1 &&
3823            Pos.getOperand(1).getOpcode() == ISD::Constant)
3824     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3825              NegC->getAPIntValue());
3826   else
3827     return false;
3828
3829   // Now we just need to check that OpSize & Mask == Width & Mask.
3830   if (MaskLoBits)
3831     // Opsize & Mask is 0 since Mask is Opsize - 1.
3832     return Width.getLoBits(MaskLoBits) == 0;
3833   return Width == OpSize;
3834 }
3835
3836 // A subroutine of MatchRotate used once we have found an OR of two opposite
3837 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3838 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3839 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3840 // Neg with outer conversions stripped away.
3841 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3842                                        SDValue Neg, SDValue InnerPos,
3843                                        SDValue InnerNeg, unsigned PosOpcode,
3844                                        unsigned NegOpcode, SDLoc DL) {
3845   // fold (or (shl x, (*ext y)),
3846   //          (srl x, (*ext (sub 32, y)))) ->
3847   //   (rotl x, y) or (rotr x, (sub 32, y))
3848   //
3849   // fold (or (shl x, (*ext (sub 32, y))),
3850   //          (srl x, (*ext y))) ->
3851   //   (rotr x, y) or (rotl x, (sub 32, y))
3852   EVT VT = Shifted.getValueType();
3853   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3854     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3855     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3856                        HasPos ? Pos : Neg).getNode();
3857   }
3858
3859   return nullptr;
3860 }
3861
3862 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3863 // idioms for rotate, and if the target supports rotation instructions, generate
3864 // a rot[lr].
3865 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3866   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3867   EVT VT = LHS.getValueType();
3868   if (!TLI.isTypeLegal(VT)) return nullptr;
3869
3870   // The target must have at least one rotate flavor.
3871   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3872   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3873   if (!HasROTL && !HasROTR) return nullptr;
3874
3875   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3876   SDValue LHSShift;   // The shift.
3877   SDValue LHSMask;    // AND value if any.
3878   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3879     return nullptr; // Not part of a rotate.
3880
3881   SDValue RHSShift;   // The shift.
3882   SDValue RHSMask;    // AND value if any.
3883   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3884     return nullptr; // Not part of a rotate.
3885
3886   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3887     return nullptr;   // Not shifting the same value.
3888
3889   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3890     return nullptr;   // Shifts must disagree.
3891
3892   // Canonicalize shl to left side in a shl/srl pair.
3893   if (RHSShift.getOpcode() == ISD::SHL) {
3894     std::swap(LHS, RHS);
3895     std::swap(LHSShift, RHSShift);
3896     std::swap(LHSMask , RHSMask );
3897   }
3898
3899   unsigned OpSizeInBits = VT.getSizeInBits();
3900   SDValue LHSShiftArg = LHSShift.getOperand(0);
3901   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3902   SDValue RHSShiftArg = RHSShift.getOperand(0);
3903   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3904
3905   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3906   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3907   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3908       RHSShiftAmt.getOpcode() == ISD::Constant) {
3909     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3910     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3911     if ((LShVal + RShVal) != OpSizeInBits)
3912       return nullptr;
3913
3914     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3915                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3916
3917     // If there is an AND of either shifted operand, apply it to the result.
3918     if (LHSMask.getNode() || RHSMask.getNode()) {
3919       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3920
3921       if (LHSMask.getNode()) {
3922         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3923         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3924       }
3925       if (RHSMask.getNode()) {
3926         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3927         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3928       }
3929
3930       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3931     }
3932
3933     return Rot.getNode();
3934   }
3935
3936   // If there is a mask here, and we have a variable shift, we can't be sure
3937   // that we're masking out the right stuff.
3938   if (LHSMask.getNode() || RHSMask.getNode())
3939     return nullptr;
3940
3941   // If the shift amount is sign/zext/any-extended just peel it off.
3942   SDValue LExtOp0 = LHSShiftAmt;
3943   SDValue RExtOp0 = RHSShiftAmt;
3944   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3945        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3946        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3947        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3948       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3949        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3950        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3951        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3952     LExtOp0 = LHSShiftAmt.getOperand(0);
3953     RExtOp0 = RHSShiftAmt.getOperand(0);
3954   }
3955
3956   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3957                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3958   if (TryL)
3959     return TryL;
3960
3961   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3962                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3963   if (TryR)
3964     return TryR;
3965
3966   return nullptr;
3967 }
3968
3969 SDValue DAGCombiner::visitXOR(SDNode *N) {
3970   SDValue N0 = N->getOperand(0);
3971   SDValue N1 = N->getOperand(1);
3972   EVT VT = N0.getValueType();
3973
3974   // fold vector ops
3975   if (VT.isVector()) {
3976     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3977       return FoldedVOp;
3978
3979     // fold (xor x, 0) -> x, vector edition
3980     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3981       return N1;
3982     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3983       return N0;
3984   }
3985
3986   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3987   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3988     return DAG.getConstant(0, SDLoc(N), VT);
3989   // fold (xor x, undef) -> undef
3990   if (N0.getOpcode() == ISD::UNDEF)
3991     return N0;
3992   if (N1.getOpcode() == ISD::UNDEF)
3993     return N1;
3994   // fold (xor c1, c2) -> c1^c2
3995   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3996   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3997   if (N0C && N1C)
3998     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3999   // canonicalize constant to RHS
4000   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4001      !isConstantIntBuildVectorOrConstantInt(N1))
4002     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4003   // fold (xor x, 0) -> x
4004   if (isNullConstant(N1))
4005     return N0;
4006   // reassociate xor
4007   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4008     return RXOR;
4009
4010   // fold !(x cc y) -> (x !cc y)
4011   SDValue LHS, RHS, CC;
4012   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4013     bool isInt = LHS.getValueType().isInteger();
4014     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4015                                                isInt);
4016
4017     if (!LegalOperations ||
4018         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4019       switch (N0.getOpcode()) {
4020       default:
4021         llvm_unreachable("Unhandled SetCC Equivalent!");
4022       case ISD::SETCC:
4023         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4024       case ISD::SELECT_CC:
4025         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4026                                N0.getOperand(3), NotCC);
4027       }
4028     }
4029   }
4030
4031   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4032   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4033       N0.getNode()->hasOneUse() &&
4034       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4035     SDValue V = N0.getOperand(0);
4036     SDLoc DL(N0);
4037     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4038                     DAG.getConstant(1, DL, V.getValueType()));
4039     AddToWorklist(V.getNode());
4040     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4041   }
4042
4043   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4044   if (isOneConstant(N1) && VT == MVT::i1 &&
4045       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4046     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4047     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4048       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4049       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4050       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4051       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4052       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4053     }
4054   }
4055   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4056   if (isAllOnesConstant(N1) &&
4057       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4058     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4059     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4060       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4061       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4062       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4063       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4064       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4065     }
4066   }
4067   // fold (xor (and x, y), y) -> (and (not x), y)
4068   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4069       N0->getOperand(1) == N1) {
4070     SDValue X = N0->getOperand(0);
4071     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4072     AddToWorklist(NotX.getNode());
4073     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4074   }
4075   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4076   if (N1C && N0.getOpcode() == ISD::XOR) {
4077     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4078       SDLoc DL(N);
4079       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4080                          DAG.getConstant(N1C->getAPIntValue() ^
4081                                          N00C->getAPIntValue(), DL, VT));
4082     }
4083     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4084       SDLoc DL(N);
4085       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4086                          DAG.getConstant(N1C->getAPIntValue() ^
4087                                          N01C->getAPIntValue(), DL, VT));
4088     }
4089   }
4090   // fold (xor x, x) -> 0
4091   if (N0 == N1)
4092     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4093
4094   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4095   // Here is a concrete example of this equivalence:
4096   // i16   x ==  14
4097   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4098   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4099   //
4100   // =>
4101   //
4102   // i16     ~1      == 0b1111111111111110
4103   // i16 rol(~1, 14) == 0b1011111111111111
4104   //
4105   // Some additional tips to help conceptualize this transform:
4106   // - Try to see the operation as placing a single zero in a value of all ones.
4107   // - There exists no value for x which would allow the result to contain zero.
4108   // - Values of x larger than the bitwidth are undefined and do not require a
4109   //   consistent result.
4110   // - Pushing the zero left requires shifting one bits in from the right.
4111   // A rotate left of ~1 is a nice way of achieving the desired result.
4112   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4113       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4114     SDLoc DL(N);
4115     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4116                        N0.getOperand(1));
4117   }
4118
4119   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4120   if (N0.getOpcode() == N1.getOpcode())
4121     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4122       return Tmp;
4123
4124   // Simplify the expression using non-local knowledge.
4125   if (!VT.isVector() &&
4126       SimplifyDemandedBits(SDValue(N, 0)))
4127     return SDValue(N, 0);
4128
4129   return SDValue();
4130 }
4131
4132 /// Handle transforms common to the three shifts, when the shift amount is a
4133 /// constant.
4134 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4135   SDNode *LHS = N->getOperand(0).getNode();
4136   if (!LHS->hasOneUse()) return SDValue();
4137
4138   // We want to pull some binops through shifts, so that we have (and (shift))
4139   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4140   // thing happens with address calculations, so it's important to canonicalize
4141   // it.
4142   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4143
4144   switch (LHS->getOpcode()) {
4145   default: return SDValue();
4146   case ISD::OR:
4147   case ISD::XOR:
4148     HighBitSet = false; // We can only transform sra if the high bit is clear.
4149     break;
4150   case ISD::AND:
4151     HighBitSet = true;  // We can only transform sra if the high bit is set.
4152     break;
4153   case ISD::ADD:
4154     if (N->getOpcode() != ISD::SHL)
4155       return SDValue(); // only shl(add) not sr[al](add).
4156     HighBitSet = false; // We can only transform sra if the high bit is clear.
4157     break;
4158   }
4159
4160   // We require the RHS of the binop to be a constant and not opaque as well.
4161   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4162   if (!BinOpCst) return SDValue();
4163
4164   // FIXME: disable this unless the input to the binop is a shift by a constant.
4165   // If it is not a shift, it pessimizes some common cases like:
4166   //
4167   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4168   //    int bar(int *X, int i) { return X[i & 255]; }
4169   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4170   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4171        BinOpLHSVal->getOpcode() != ISD::SRA &&
4172        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4173       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4174     return SDValue();
4175
4176   EVT VT = N->getValueType(0);
4177
4178   // If this is a signed shift right, and the high bit is modified by the
4179   // logical operation, do not perform the transformation. The highBitSet
4180   // boolean indicates the value of the high bit of the constant which would
4181   // cause it to be modified for this operation.
4182   if (N->getOpcode() == ISD::SRA) {
4183     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4184     if (BinOpRHSSignSet != HighBitSet)
4185       return SDValue();
4186   }
4187
4188   if (!TLI.isDesirableToCommuteWithShift(LHS))
4189     return SDValue();
4190
4191   // Fold the constants, shifting the binop RHS by the shift amount.
4192   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4193                                N->getValueType(0),
4194                                LHS->getOperand(1), N->getOperand(1));
4195   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4196
4197   // Create the new shift.
4198   SDValue NewShift = DAG.getNode(N->getOpcode(),
4199                                  SDLoc(LHS->getOperand(0)),
4200                                  VT, LHS->getOperand(0), N->getOperand(1));
4201
4202   // Create the new binop.
4203   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4204 }
4205
4206 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4207   assert(N->getOpcode() == ISD::TRUNCATE);
4208   assert(N->getOperand(0).getOpcode() == ISD::AND);
4209
4210   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4211   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4212     SDValue N01 = N->getOperand(0).getOperand(1);
4213
4214     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4215       if (!N01C->isOpaque()) {
4216         EVT TruncVT = N->getValueType(0);
4217         SDValue N00 = N->getOperand(0).getOperand(0);
4218         APInt TruncC = N01C->getAPIntValue();
4219         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4220         SDLoc DL(N);
4221
4222         return DAG.getNode(ISD::AND, DL, TruncVT,
4223                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4224                            DAG.getConstant(TruncC, DL, TruncVT));
4225       }
4226     }
4227   }
4228
4229   return SDValue();
4230 }
4231
4232 SDValue DAGCombiner::visitRotate(SDNode *N) {
4233   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4234   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4235       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4236     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4237     if (NewOp1.getNode())
4238       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4239                          N->getOperand(0), NewOp1);
4240   }
4241   return SDValue();
4242 }
4243
4244 SDValue DAGCombiner::visitSHL(SDNode *N) {
4245   SDValue N0 = N->getOperand(0);
4246   SDValue N1 = N->getOperand(1);
4247   EVT VT = N0.getValueType();
4248   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4249
4250   // fold vector ops
4251   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4252   if (VT.isVector()) {
4253     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4254       return FoldedVOp;
4255
4256     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4257     // If setcc produces all-one true value then:
4258     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4259     if (N1CV && N1CV->isConstant()) {
4260       if (N0.getOpcode() == ISD::AND) {
4261         SDValue N00 = N0->getOperand(0);
4262         SDValue N01 = N0->getOperand(1);
4263         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4264
4265         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4266             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4267                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4268           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4269                                                      N01CV, N1CV))
4270             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4271         }
4272       } else {
4273         N1C = isConstOrConstSplat(N1);
4274       }
4275     }
4276   }
4277
4278   // fold (shl c1, c2) -> c1<<c2
4279   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4280   if (N0C && N1C && !N1C->isOpaque())
4281     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4282   // fold (shl 0, x) -> 0
4283   if (isNullConstant(N0))
4284     return N0;
4285   // fold (shl x, c >= size(x)) -> undef
4286   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4287     return DAG.getUNDEF(VT);
4288   // fold (shl x, 0) -> x
4289   if (N1C && N1C->isNullValue())
4290     return N0;
4291   // fold (shl undef, x) -> 0
4292   if (N0.getOpcode() == ISD::UNDEF)
4293     return DAG.getConstant(0, SDLoc(N), VT);
4294   // if (shl x, c) is known to be zero, return 0
4295   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4296                             APInt::getAllOnesValue(OpSizeInBits)))
4297     return DAG.getConstant(0, SDLoc(N), VT);
4298   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4299   if (N1.getOpcode() == ISD::TRUNCATE &&
4300       N1.getOperand(0).getOpcode() == ISD::AND) {
4301     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4302     if (NewOp1.getNode())
4303       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4304   }
4305
4306   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4307     return SDValue(N, 0);
4308
4309   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4310   if (N1C && N0.getOpcode() == ISD::SHL) {
4311     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4312       uint64_t c1 = N0C1->getZExtValue();
4313       uint64_t c2 = N1C->getZExtValue();
4314       SDLoc DL(N);
4315       if (c1 + c2 >= OpSizeInBits)
4316         return DAG.getConstant(0, DL, VT);
4317       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4318                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4319     }
4320   }
4321
4322   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4323   // For this to be valid, the second form must not preserve any of the bits
4324   // that are shifted out by the inner shift in the first form.  This means
4325   // the outer shift size must be >= the number of bits added by the ext.
4326   // As a corollary, we don't care what kind of ext it is.
4327   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4328               N0.getOpcode() == ISD::ANY_EXTEND ||
4329               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4330       N0.getOperand(0).getOpcode() == ISD::SHL) {
4331     SDValue N0Op0 = N0.getOperand(0);
4332     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4333       uint64_t c1 = N0Op0C1->getZExtValue();
4334       uint64_t c2 = N1C->getZExtValue();
4335       EVT InnerShiftVT = N0Op0.getValueType();
4336       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4337       if (c2 >= OpSizeInBits - InnerShiftSize) {
4338         SDLoc DL(N0);
4339         if (c1 + c2 >= OpSizeInBits)
4340           return DAG.getConstant(0, DL, VT);
4341         return DAG.getNode(ISD::SHL, DL, VT,
4342                            DAG.getNode(N0.getOpcode(), DL, VT,
4343                                        N0Op0->getOperand(0)),
4344                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4345       }
4346     }
4347   }
4348
4349   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4350   // Only fold this if the inner zext has no other uses to avoid increasing
4351   // the total number of instructions.
4352   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4353       N0.getOperand(0).getOpcode() == ISD::SRL) {
4354     SDValue N0Op0 = N0.getOperand(0);
4355     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4356       uint64_t c1 = N0Op0C1->getZExtValue();
4357       if (c1 < VT.getScalarSizeInBits()) {
4358         uint64_t c2 = N1C->getZExtValue();
4359         if (c1 == c2) {
4360           SDValue NewOp0 = N0.getOperand(0);
4361           EVT CountVT = NewOp0.getOperand(1).getValueType();
4362           SDLoc DL(N);
4363           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4364                                        NewOp0,
4365                                        DAG.getConstant(c2, DL, CountVT));
4366           AddToWorklist(NewSHL.getNode());
4367           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4368         }
4369       }
4370     }
4371   }
4372
4373   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4374   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4375   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4376       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4377     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4378       uint64_t C1 = N0C1->getZExtValue();
4379       uint64_t C2 = N1C->getZExtValue();
4380       SDLoc DL(N);
4381       if (C1 <= C2)
4382         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4383                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4384       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4385                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4386     }
4387   }
4388
4389   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4390   //                               (and (srl x, (sub c1, c2), MASK)
4391   // Only fold this if the inner shift has no other uses -- if it does, folding
4392   // this will increase the total number of instructions.
4393   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4394     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4395       uint64_t c1 = N0C1->getZExtValue();
4396       if (c1 < OpSizeInBits) {
4397         uint64_t c2 = N1C->getZExtValue();
4398         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4399         SDValue Shift;
4400         if (c2 > c1) {
4401           Mask = Mask.shl(c2 - c1);
4402           SDLoc DL(N);
4403           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4404                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4405         } else {
4406           Mask = Mask.lshr(c1 - c2);
4407           SDLoc DL(N);
4408           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4409                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4410         }
4411         SDLoc DL(N0);
4412         return DAG.getNode(ISD::AND, DL, VT, Shift,
4413                            DAG.getConstant(Mask, DL, VT));
4414       }
4415     }
4416   }
4417   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4418   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4419     unsigned BitSize = VT.getScalarSizeInBits();
4420     SDLoc DL(N);
4421     SDValue HiBitsMask =
4422       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4423                                             BitSize - N1C->getZExtValue()),
4424                       DL, VT);
4425     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4426                        HiBitsMask);
4427   }
4428
4429   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4430   // Variant of version done on multiply, except mul by a power of 2 is turned
4431   // into a shift.
4432   APInt Val;
4433   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4434       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4435        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4436     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4437     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4438     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4439   }
4440
4441   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4442   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4443     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4444       if (SDValue Folded =
4445               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4446         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4447     }
4448   }
4449
4450   if (N1C && !N1C->isOpaque())
4451     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4452       return NewSHL;
4453
4454   return SDValue();
4455 }
4456
4457 SDValue DAGCombiner::visitSRA(SDNode *N) {
4458   SDValue N0 = N->getOperand(0);
4459   SDValue N1 = N->getOperand(1);
4460   EVT VT = N0.getValueType();
4461   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4462
4463   // fold vector ops
4464   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4465   if (VT.isVector()) {
4466     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4467       return FoldedVOp;
4468
4469     N1C = isConstOrConstSplat(N1);
4470   }
4471
4472   // fold (sra c1, c2) -> (sra c1, c2)
4473   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4474   if (N0C && N1C && !N1C->isOpaque())
4475     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4476   // fold (sra 0, x) -> 0
4477   if (isNullConstant(N0))
4478     return N0;
4479   // fold (sra -1, x) -> -1
4480   if (isAllOnesConstant(N0))
4481     return N0;
4482   // fold (sra x, (setge c, size(x))) -> undef
4483   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4484     return DAG.getUNDEF(VT);
4485   // fold (sra x, 0) -> x
4486   if (N1C && N1C->isNullValue())
4487     return N0;
4488   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4489   // sext_inreg.
4490   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4491     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4492     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4493     if (VT.isVector())
4494       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4495                                ExtVT, VT.getVectorNumElements());
4496     if ((!LegalOperations ||
4497          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4498       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4499                          N0.getOperand(0), DAG.getValueType(ExtVT));
4500   }
4501
4502   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4503   if (N1C && N0.getOpcode() == ISD::SRA) {
4504     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4505       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4506       if (Sum >= OpSizeInBits)
4507         Sum = OpSizeInBits - 1;
4508       SDLoc DL(N);
4509       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4510                          DAG.getConstant(Sum, DL, N1.getValueType()));
4511     }
4512   }
4513
4514   // fold (sra (shl X, m), (sub result_size, n))
4515   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4516   // result_size - n != m.
4517   // If truncate is free for the target sext(shl) is likely to result in better
4518   // code.
4519   if (N0.getOpcode() == ISD::SHL && N1C) {
4520     // Get the two constanst of the shifts, CN0 = m, CN = n.
4521     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4522     if (N01C) {
4523       LLVMContext &Ctx = *DAG.getContext();
4524       // Determine what the truncate's result bitsize and type would be.
4525       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4526
4527       if (VT.isVector())
4528         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4529
4530       // Determine the residual right-shift amount.
4531       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4532
4533       // If the shift is not a no-op (in which case this should be just a sign
4534       // extend already), the truncated to type is legal, sign_extend is legal
4535       // on that type, and the truncate to that type is both legal and free,
4536       // perform the transform.
4537       if ((ShiftAmt > 0) &&
4538           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4539           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4540           TLI.isTruncateFree(VT, TruncVT)) {
4541
4542         SDLoc DL(N);
4543         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4544             getShiftAmountTy(N0.getOperand(0).getValueType()));
4545         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4546                                     N0.getOperand(0), Amt);
4547         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4548                                     Shift);
4549         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4550                            N->getValueType(0), Trunc);
4551       }
4552     }
4553   }
4554
4555   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4556   if (N1.getOpcode() == ISD::TRUNCATE &&
4557       N1.getOperand(0).getOpcode() == ISD::AND) {
4558     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4559     if (NewOp1.getNode())
4560       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4561   }
4562
4563   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4564   //      if c1 is equal to the number of bits the trunc removes
4565   if (N0.getOpcode() == ISD::TRUNCATE &&
4566       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4567        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4568       N0.getOperand(0).hasOneUse() &&
4569       N0.getOperand(0).getOperand(1).hasOneUse() &&
4570       N1C) {
4571     SDValue N0Op0 = N0.getOperand(0);
4572     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4573       unsigned LargeShiftVal = LargeShift->getZExtValue();
4574       EVT LargeVT = N0Op0.getValueType();
4575
4576       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4577         SDLoc DL(N);
4578         SDValue Amt =
4579           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4580                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4581         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4582                                   N0Op0.getOperand(0), Amt);
4583         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4584       }
4585     }
4586   }
4587
4588   // Simplify, based on bits shifted out of the LHS.
4589   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4590     return SDValue(N, 0);
4591
4592
4593   // If the sign bit is known to be zero, switch this to a SRL.
4594   if (DAG.SignBitIsZero(N0))
4595     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4596
4597   if (N1C && !N1C->isOpaque())
4598     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4599       return NewSRA;
4600
4601   return SDValue();
4602 }
4603
4604 SDValue DAGCombiner::visitSRL(SDNode *N) {
4605   SDValue N0 = N->getOperand(0);
4606   SDValue N1 = N->getOperand(1);
4607   EVT VT = N0.getValueType();
4608   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4609
4610   // fold vector ops
4611   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4612   if (VT.isVector()) {
4613     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4614       return FoldedVOp;
4615
4616     N1C = isConstOrConstSplat(N1);
4617   }
4618
4619   // fold (srl c1, c2) -> c1 >>u c2
4620   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4621   if (N0C && N1C && !N1C->isOpaque())
4622     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4623   // fold (srl 0, x) -> 0
4624   if (isNullConstant(N0))
4625     return N0;
4626   // fold (srl x, c >= size(x)) -> undef
4627   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4628     return DAG.getUNDEF(VT);
4629   // fold (srl x, 0) -> x
4630   if (N1C && N1C->isNullValue())
4631     return N0;
4632   // if (srl x, c) is known to be zero, return 0
4633   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4634                                    APInt::getAllOnesValue(OpSizeInBits)))
4635     return DAG.getConstant(0, SDLoc(N), VT);
4636
4637   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4638   if (N1C && N0.getOpcode() == ISD::SRL) {
4639     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4640       uint64_t c1 = N01C->getZExtValue();
4641       uint64_t c2 = N1C->getZExtValue();
4642       SDLoc DL(N);
4643       if (c1 + c2 >= OpSizeInBits)
4644         return DAG.getConstant(0, DL, VT);
4645       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4646                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4647     }
4648   }
4649
4650   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4651   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4652       N0.getOperand(0).getOpcode() == ISD::SRL &&
4653       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4654     uint64_t c1 =
4655       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4656     uint64_t c2 = N1C->getZExtValue();
4657     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4658     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4659     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4660     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4661     if (c1 + OpSizeInBits == InnerShiftSize) {
4662       SDLoc DL(N0);
4663       if (c1 + c2 >= InnerShiftSize)
4664         return DAG.getConstant(0, DL, VT);
4665       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4666                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4667                                      N0.getOperand(0)->getOperand(0),
4668                                      DAG.getConstant(c1 + c2, DL,
4669                                                      ShiftCountVT)));
4670     }
4671   }
4672
4673   // fold (srl (shl x, c), c) -> (and x, cst2)
4674   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4675     unsigned BitSize = N0.getScalarValueSizeInBits();
4676     if (BitSize <= 64) {
4677       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4678       SDLoc DL(N);
4679       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4680                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4681     }
4682   }
4683
4684   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4685   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4686     // Shifting in all undef bits?
4687     EVT SmallVT = N0.getOperand(0).getValueType();
4688     unsigned BitSize = SmallVT.getScalarSizeInBits();
4689     if (N1C->getZExtValue() >= BitSize)
4690       return DAG.getUNDEF(VT);
4691
4692     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4693       uint64_t ShiftAmt = N1C->getZExtValue();
4694       SDLoc DL0(N0);
4695       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4696                                        N0.getOperand(0),
4697                           DAG.getConstant(ShiftAmt, DL0,
4698                                           getShiftAmountTy(SmallVT)));
4699       AddToWorklist(SmallShift.getNode());
4700       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4701       SDLoc DL(N);
4702       return DAG.getNode(ISD::AND, DL, VT,
4703                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4704                          DAG.getConstant(Mask, DL, VT));
4705     }
4706   }
4707
4708   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4709   // bit, which is unmodified by sra.
4710   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4711     if (N0.getOpcode() == ISD::SRA)
4712       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4713   }
4714
4715   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4716   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4717       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4718     APInt KnownZero, KnownOne;
4719     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4720
4721     // If any of the input bits are KnownOne, then the input couldn't be all
4722     // zeros, thus the result of the srl will always be zero.
4723     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4724
4725     // If all of the bits input the to ctlz node are known to be zero, then
4726     // the result of the ctlz is "32" and the result of the shift is one.
4727     APInt UnknownBits = ~KnownZero;
4728     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4729
4730     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4731     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4732       // Okay, we know that only that the single bit specified by UnknownBits
4733       // could be set on input to the CTLZ node. If this bit is set, the SRL
4734       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4735       // to an SRL/XOR pair, which is likely to simplify more.
4736       unsigned ShAmt = UnknownBits.countTrailingZeros();
4737       SDValue Op = N0.getOperand(0);
4738
4739       if (ShAmt) {
4740         SDLoc DL(N0);
4741         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4742                   DAG.getConstant(ShAmt, DL,
4743                                   getShiftAmountTy(Op.getValueType())));
4744         AddToWorklist(Op.getNode());
4745       }
4746
4747       SDLoc DL(N);
4748       return DAG.getNode(ISD::XOR, DL, VT,
4749                          Op, DAG.getConstant(1, DL, VT));
4750     }
4751   }
4752
4753   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4754   if (N1.getOpcode() == ISD::TRUNCATE &&
4755       N1.getOperand(0).getOpcode() == ISD::AND) {
4756     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4757       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4758   }
4759
4760   // fold operands of srl based on knowledge that the low bits are not
4761   // demanded.
4762   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4763     return SDValue(N, 0);
4764
4765   if (N1C && !N1C->isOpaque())
4766     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4767       return NewSRL;
4768
4769   // Attempt to convert a srl of a load into a narrower zero-extending load.
4770   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4771     return NarrowLoad;
4772
4773   // Here is a common situation. We want to optimize:
4774   //
4775   //   %a = ...
4776   //   %b = and i32 %a, 2
4777   //   %c = srl i32 %b, 1
4778   //   brcond i32 %c ...
4779   //
4780   // into
4781   //
4782   //   %a = ...
4783   //   %b = and %a, 2
4784   //   %c = setcc eq %b, 0
4785   //   brcond %c ...
4786   //
4787   // However when after the source operand of SRL is optimized into AND, the SRL
4788   // itself may not be optimized further. Look for it and add the BRCOND into
4789   // the worklist.
4790   if (N->hasOneUse()) {
4791     SDNode *Use = *N->use_begin();
4792     if (Use->getOpcode() == ISD::BRCOND)
4793       AddToWorklist(Use);
4794     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4795       // Also look pass the truncate.
4796       Use = *Use->use_begin();
4797       if (Use->getOpcode() == ISD::BRCOND)
4798         AddToWorklist(Use);
4799     }
4800   }
4801
4802   return SDValue();
4803 }
4804
4805 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4806   SDValue N0 = N->getOperand(0);
4807   EVT VT = N->getValueType(0);
4808
4809   // fold (bswap c1) -> c2
4810   if (isConstantIntBuildVectorOrConstantInt(N0))
4811     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4812   // fold (bswap (bswap x)) -> x
4813   if (N0.getOpcode() == ISD::BSWAP)
4814     return N0->getOperand(0);
4815   return SDValue();
4816 }
4817
4818 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4819   SDValue N0 = N->getOperand(0);
4820   EVT VT = N->getValueType(0);
4821
4822   // fold (ctlz c1) -> c2
4823   if (isConstantIntBuildVectorOrConstantInt(N0))
4824     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4825   return SDValue();
4826 }
4827
4828 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4829   SDValue N0 = N->getOperand(0);
4830   EVT VT = N->getValueType(0);
4831
4832   // fold (ctlz_zero_undef c1) -> c2
4833   if (isConstantIntBuildVectorOrConstantInt(N0))
4834     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4835   return SDValue();
4836 }
4837
4838 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4839   SDValue N0 = N->getOperand(0);
4840   EVT VT = N->getValueType(0);
4841
4842   // fold (cttz c1) -> c2
4843   if (isConstantIntBuildVectorOrConstantInt(N0))
4844     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4845   return SDValue();
4846 }
4847
4848 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4849   SDValue N0 = N->getOperand(0);
4850   EVT VT = N->getValueType(0);
4851
4852   // fold (cttz_zero_undef c1) -> c2
4853   if (isConstantIntBuildVectorOrConstantInt(N0))
4854     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4855   return SDValue();
4856 }
4857
4858 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4859   SDValue N0 = N->getOperand(0);
4860   EVT VT = N->getValueType(0);
4861
4862   // fold (ctpop c1) -> c2
4863   if (isConstantIntBuildVectorOrConstantInt(N0))
4864     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4865   return SDValue();
4866 }
4867
4868
4869 /// \brief Generate Min/Max node
4870 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4871                                    SDValue True, SDValue False,
4872                                    ISD::CondCode CC, const TargetLowering &TLI,
4873                                    SelectionDAG &DAG) {
4874   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4875     return SDValue();
4876
4877   switch (CC) {
4878   case ISD::SETOLT:
4879   case ISD::SETOLE:
4880   case ISD::SETLT:
4881   case ISD::SETLE:
4882   case ISD::SETULT:
4883   case ISD::SETULE: {
4884     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4885     if (TLI.isOperationLegal(Opcode, VT))
4886       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4887     return SDValue();
4888   }
4889   case ISD::SETOGT:
4890   case ISD::SETOGE:
4891   case ISD::SETGT:
4892   case ISD::SETGE:
4893   case ISD::SETUGT:
4894   case ISD::SETUGE: {
4895     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4896     if (TLI.isOperationLegal(Opcode, VT))
4897       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4898     return SDValue();
4899   }
4900   default:
4901     return SDValue();
4902   }
4903 }
4904
4905 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4906   SDValue N0 = N->getOperand(0);
4907   SDValue N1 = N->getOperand(1);
4908   SDValue N2 = N->getOperand(2);
4909   EVT VT = N->getValueType(0);
4910   EVT VT0 = N0.getValueType();
4911
4912   // fold (select C, X, X) -> X
4913   if (N1 == N2)
4914     return N1;
4915   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4916     // fold (select true, X, Y) -> X
4917     // fold (select false, X, Y) -> Y
4918     return !N0C->isNullValue() ? N1 : N2;
4919   }
4920   // fold (select C, 1, X) -> (or C, X)
4921   if (VT == MVT::i1 && isOneConstant(N1))
4922     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4923   // fold (select C, 0, 1) -> (xor C, 1)
4924   // We can't do this reliably if integer based booleans have different contents
4925   // to floating point based booleans. This is because we can't tell whether we
4926   // have an integer-based boolean or a floating-point-based boolean unless we
4927   // can find the SETCC that produced it and inspect its operands. This is
4928   // fairly easy if C is the SETCC node, but it can potentially be
4929   // undiscoverable (or not reasonably discoverable). For example, it could be
4930   // in another basic block or it could require searching a complicated
4931   // expression.
4932   if (VT.isInteger() &&
4933       (VT0 == MVT::i1 || (VT0.isInteger() &&
4934                           TLI.getBooleanContents(false, false) ==
4935                               TLI.getBooleanContents(false, true) &&
4936                           TLI.getBooleanContents(false, false) ==
4937                               TargetLowering::ZeroOrOneBooleanContent)) &&
4938       isNullConstant(N1) && isOneConstant(N2)) {
4939     SDValue XORNode;
4940     if (VT == VT0) {
4941       SDLoc DL(N);
4942       return DAG.getNode(ISD::XOR, DL, VT0,
4943                          N0, DAG.getConstant(1, DL, VT0));
4944     }
4945     SDLoc DL0(N0);
4946     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4947                           N0, DAG.getConstant(1, DL0, VT0));
4948     AddToWorklist(XORNode.getNode());
4949     if (VT.bitsGT(VT0))
4950       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4951     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4952   }
4953   // fold (select C, 0, X) -> (and (not C), X)
4954   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4955     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4956     AddToWorklist(NOTNode.getNode());
4957     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4958   }
4959   // fold (select C, X, 1) -> (or (not C), X)
4960   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4961     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4962     AddToWorklist(NOTNode.getNode());
4963     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4964   }
4965   // fold (select C, X, 0) -> (and C, X)
4966   if (VT == MVT::i1 && isNullConstant(N2))
4967     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4968   // fold (select X, X, Y) -> (or X, Y)
4969   // fold (select X, 1, Y) -> (or X, Y)
4970   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4971     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4972   // fold (select X, Y, X) -> (and X, Y)
4973   // fold (select X, Y, 0) -> (and X, Y)
4974   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4975     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4976
4977   // If we can fold this based on the true/false value, do so.
4978   if (SimplifySelectOps(N, N1, N2))
4979     return SDValue(N, 0);  // Don't revisit N.
4980
4981   if (VT0 == MVT::i1) {
4982     // The code in this block deals with the following 2 equivalences:
4983     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
4984     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
4985     // The target can specify its prefered form with the
4986     // shouldNormalizeToSelectSequence() callback. However we always transform
4987     // to the right anyway if we find the inner select exists in the DAG anyway
4988     // and we always transform to the left side if we know that we can further
4989     // optimize the combination of the conditions.
4990     bool normalizeToSequence
4991       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
4992     // select (and Cond0, Cond1), X, Y
4993     //   -> select Cond0, (select Cond1, X, Y), Y
4994     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4995       SDValue Cond0 = N0->getOperand(0);
4996       SDValue Cond1 = N0->getOperand(1);
4997       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4998                                         N1.getValueType(), Cond1, N1, N2);
4999       if (normalizeToSequence || !InnerSelect.use_empty())
5000         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5001                            InnerSelect, N2);
5002     }
5003     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5004     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5005       SDValue Cond0 = N0->getOperand(0);
5006       SDValue Cond1 = N0->getOperand(1);
5007       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5008                                         N1.getValueType(), Cond1, N1, N2);
5009       if (normalizeToSequence || !InnerSelect.use_empty())
5010         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5011                            InnerSelect);
5012     }
5013
5014     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5015     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5016       SDValue N1_0 = N1->getOperand(0);
5017       SDValue N1_1 = N1->getOperand(1);
5018       SDValue N1_2 = N1->getOperand(2);
5019       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5020         // Create the actual and node if we can generate good code for it.
5021         if (!normalizeToSequence) {
5022           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5023                                     N0, N1_0);
5024           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5025                              N1_1, N2);
5026         }
5027         // Otherwise see if we can optimize the "and" to a better pattern.
5028         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5029           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5030                              N1_1, N2);
5031       }
5032     }
5033     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5034     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5035       SDValue N2_0 = N2->getOperand(0);
5036       SDValue N2_1 = N2->getOperand(1);
5037       SDValue N2_2 = N2->getOperand(2);
5038       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5039         // Create the actual or node if we can generate good code for it.
5040         if (!normalizeToSequence) {
5041           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5042                                    N0, N2_0);
5043           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5044                              N1, N2_2);
5045         }
5046         // Otherwise see if we can optimize to a better pattern.
5047         if (SDValue Combined = visitORLike(N0, N2_0, N))
5048           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5049                              N1, N2_2);
5050       }
5051     }
5052   }
5053
5054   // fold selects based on a setcc into other things, such as min/max/abs
5055   if (N0.getOpcode() == ISD::SETCC) {
5056     // select x, y (fcmp lt x, y) -> fminnum x, y
5057     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5058     //
5059     // This is OK if we don't care about what happens if either operand is a
5060     // NaN.
5061     //
5062
5063     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5064     // no signed zeros as well as no nans.
5065     const TargetOptions &Options = DAG.getTarget().Options;
5066     if (Options.UnsafeFPMath &&
5067         VT.isFloatingPoint() && N0.hasOneUse() &&
5068         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5069       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5070
5071       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5072                                                 N0.getOperand(1), N1, N2, CC,
5073                                                 TLI, DAG))
5074         return FMinMax;
5075     }
5076
5077     if ((!LegalOperations &&
5078          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5079         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5080       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5081                          N0.getOperand(0), N0.getOperand(1),
5082                          N1, N2, N0.getOperand(2));
5083     return SimplifySelect(SDLoc(N), N0, N1, N2);
5084   }
5085
5086   return SDValue();
5087 }
5088
5089 static
5090 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5091   SDLoc DL(N);
5092   EVT LoVT, HiVT;
5093   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5094
5095   // Split the inputs.
5096   SDValue Lo, Hi, LL, LH, RL, RH;
5097   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5098   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5099
5100   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5101   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5102
5103   return std::make_pair(Lo, Hi);
5104 }
5105
5106 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5107 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5108 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5109   SDLoc dl(N);
5110   SDValue Cond = N->getOperand(0);
5111   SDValue LHS = N->getOperand(1);
5112   SDValue RHS = N->getOperand(2);
5113   EVT VT = N->getValueType(0);
5114   int NumElems = VT.getVectorNumElements();
5115   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5116          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5117          Cond.getOpcode() == ISD::BUILD_VECTOR);
5118
5119   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5120   // binary ones here.
5121   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5122     return SDValue();
5123
5124   // We're sure we have an even number of elements due to the
5125   // concat_vectors we have as arguments to vselect.
5126   // Skip BV elements until we find one that's not an UNDEF
5127   // After we find an UNDEF element, keep looping until we get to half the
5128   // length of the BV and see if all the non-undef nodes are the same.
5129   ConstantSDNode *BottomHalf = nullptr;
5130   for (int i = 0; i < NumElems / 2; ++i) {
5131     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5132       continue;
5133
5134     if (BottomHalf == nullptr)
5135       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5136     else if (Cond->getOperand(i).getNode() != BottomHalf)
5137       return SDValue();
5138   }
5139
5140   // Do the same for the second half of the BuildVector
5141   ConstantSDNode *TopHalf = nullptr;
5142   for (int i = NumElems / 2; i < NumElems; ++i) {
5143     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5144       continue;
5145
5146     if (TopHalf == nullptr)
5147       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5148     else if (Cond->getOperand(i).getNode() != TopHalf)
5149       return SDValue();
5150   }
5151
5152   assert(TopHalf && BottomHalf &&
5153          "One half of the selector was all UNDEFs and the other was all the "
5154          "same value. This should have been addressed before this function.");
5155   return DAG.getNode(
5156       ISD::CONCAT_VECTORS, dl, VT,
5157       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5158       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5159 }
5160
5161 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5162
5163   if (Level >= AfterLegalizeTypes)
5164     return SDValue();
5165
5166   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5167   SDValue Mask = MSC->getMask();
5168   SDValue Data  = MSC->getValue();
5169   SDLoc DL(N);
5170
5171   // If the MSCATTER data type requires splitting and the mask is provided by a
5172   // SETCC, then split both nodes and its operands before legalization. This
5173   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5174   // and enables future optimizations (e.g. min/max pattern matching on X86).
5175   if (Mask.getOpcode() != ISD::SETCC)
5176     return SDValue();
5177
5178   // Check if any splitting is required.
5179   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5180       TargetLowering::TypeSplitVector)
5181     return SDValue();
5182   SDValue MaskLo, MaskHi, Lo, Hi;
5183   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5184
5185   EVT LoVT, HiVT;
5186   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5187
5188   SDValue Chain = MSC->getChain();
5189
5190   EVT MemoryVT = MSC->getMemoryVT();
5191   unsigned Alignment = MSC->getOriginalAlignment();
5192
5193   EVT LoMemVT, HiMemVT;
5194   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5195
5196   SDValue DataLo, DataHi;
5197   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5198
5199   SDValue BasePtr = MSC->getBasePtr();
5200   SDValue IndexLo, IndexHi;
5201   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5202
5203   MachineMemOperand *MMO = DAG.getMachineFunction().
5204     getMachineMemOperand(MSC->getPointerInfo(),
5205                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5206                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5207
5208   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5209   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5210                             DL, OpsLo, MMO);
5211
5212   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5213   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5214                             DL, OpsHi, MMO);
5215
5216   AddToWorklist(Lo.getNode());
5217   AddToWorklist(Hi.getNode());
5218
5219   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5220 }
5221
5222 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5223
5224   if (Level >= AfterLegalizeTypes)
5225     return SDValue();
5226
5227   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5228   SDValue Mask = MST->getMask();
5229   SDValue Data  = MST->getValue();
5230   SDLoc DL(N);
5231
5232   // If the MSTORE data type requires splitting and the mask is provided by a
5233   // SETCC, then split both nodes and its operands before legalization. This
5234   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5235   // and enables future optimizations (e.g. min/max pattern matching on X86).
5236   if (Mask.getOpcode() == ISD::SETCC) {
5237
5238     // Check if any splitting is required.
5239     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5240         TargetLowering::TypeSplitVector)
5241       return SDValue();
5242
5243     SDValue MaskLo, MaskHi, Lo, Hi;
5244     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5245
5246     EVT LoVT, HiVT;
5247     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5248
5249     SDValue Chain = MST->getChain();
5250     SDValue Ptr   = MST->getBasePtr();
5251
5252     EVT MemoryVT = MST->getMemoryVT();
5253     unsigned Alignment = MST->getOriginalAlignment();
5254
5255     // if Alignment is equal to the vector size,
5256     // take the half of it for the second part
5257     unsigned SecondHalfAlignment =
5258       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5259          Alignment/2 : Alignment;
5260
5261     EVT LoMemVT, HiMemVT;
5262     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5263
5264     SDValue DataLo, DataHi;
5265     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5266
5267     MachineMemOperand *MMO = DAG.getMachineFunction().
5268       getMachineMemOperand(MST->getPointerInfo(),
5269                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5270                            Alignment, MST->getAAInfo(), MST->getRanges());
5271
5272     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5273                             MST->isTruncatingStore());
5274
5275     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5276     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5277                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5278
5279     MMO = DAG.getMachineFunction().
5280       getMachineMemOperand(MST->getPointerInfo(),
5281                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5282                            SecondHalfAlignment, MST->getAAInfo(),
5283                            MST->getRanges());
5284
5285     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5286                             MST->isTruncatingStore());
5287
5288     AddToWorklist(Lo.getNode());
5289     AddToWorklist(Hi.getNode());
5290
5291     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5292   }
5293   return SDValue();
5294 }
5295
5296 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5297
5298   if (Level >= AfterLegalizeTypes)
5299     return SDValue();
5300
5301   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5302   SDValue Mask = MGT->getMask();
5303   SDLoc DL(N);
5304
5305   // If the MGATHER result requires splitting and the mask is provided by a
5306   // SETCC, then split both nodes and its operands before legalization. This
5307   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5308   // and enables future optimizations (e.g. min/max pattern matching on X86).
5309
5310   if (Mask.getOpcode() != ISD::SETCC)
5311     return SDValue();
5312
5313   EVT VT = N->getValueType(0);
5314
5315   // Check if any splitting is required.
5316   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5317       TargetLowering::TypeSplitVector)
5318     return SDValue();
5319
5320   SDValue MaskLo, MaskHi, Lo, Hi;
5321   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5322
5323   SDValue Src0 = MGT->getValue();
5324   SDValue Src0Lo, Src0Hi;
5325   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5326
5327   EVT LoVT, HiVT;
5328   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5329
5330   SDValue Chain = MGT->getChain();
5331   EVT MemoryVT = MGT->getMemoryVT();
5332   unsigned Alignment = MGT->getOriginalAlignment();
5333
5334   EVT LoMemVT, HiMemVT;
5335   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5336
5337   SDValue BasePtr = MGT->getBasePtr();
5338   SDValue Index = MGT->getIndex();
5339   SDValue IndexLo, IndexHi;
5340   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5341
5342   MachineMemOperand *MMO = DAG.getMachineFunction().
5343     getMachineMemOperand(MGT->getPointerInfo(),
5344                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5345                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5346
5347   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5348   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5349                             MMO);
5350
5351   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5352   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5353                             MMO);
5354
5355   AddToWorklist(Lo.getNode());
5356   AddToWorklist(Hi.getNode());
5357
5358   // Build a factor node to remember that this load is independent of the
5359   // other one.
5360   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5361                       Hi.getValue(1));
5362
5363   // Legalized the chain result - switch anything that used the old chain to
5364   // use the new one.
5365   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5366
5367   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5368
5369   SDValue RetOps[] = { GatherRes, Chain };
5370   return DAG.getMergeValues(RetOps, DL);
5371 }
5372
5373 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5374
5375   if (Level >= AfterLegalizeTypes)
5376     return SDValue();
5377
5378   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5379   SDValue Mask = MLD->getMask();
5380   SDLoc DL(N);
5381
5382   // If the MLOAD result requires splitting and the mask is provided by a
5383   // SETCC, then split both nodes and its operands before legalization. This
5384   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5385   // and enables future optimizations (e.g. min/max pattern matching on X86).
5386
5387   if (Mask.getOpcode() == ISD::SETCC) {
5388     EVT VT = N->getValueType(0);
5389
5390     // Check if any splitting is required.
5391     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5392         TargetLowering::TypeSplitVector)
5393       return SDValue();
5394
5395     SDValue MaskLo, MaskHi, Lo, Hi;
5396     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5397
5398     SDValue Src0 = MLD->getSrc0();
5399     SDValue Src0Lo, Src0Hi;
5400     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5401
5402     EVT LoVT, HiVT;
5403     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5404
5405     SDValue Chain = MLD->getChain();
5406     SDValue Ptr   = MLD->getBasePtr();
5407     EVT MemoryVT = MLD->getMemoryVT();
5408     unsigned Alignment = MLD->getOriginalAlignment();
5409
5410     // if Alignment is equal to the vector size,
5411     // take the half of it for the second part
5412     unsigned SecondHalfAlignment =
5413       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5414          Alignment/2 : Alignment;
5415
5416     EVT LoMemVT, HiMemVT;
5417     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5418
5419     MachineMemOperand *MMO = DAG.getMachineFunction().
5420     getMachineMemOperand(MLD->getPointerInfo(),
5421                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5422                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5423
5424     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5425                            ISD::NON_EXTLOAD);
5426
5427     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5428     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5429                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5430
5431     MMO = DAG.getMachineFunction().
5432     getMachineMemOperand(MLD->getPointerInfo(),
5433                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5434                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5435
5436     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5437                            ISD::NON_EXTLOAD);
5438
5439     AddToWorklist(Lo.getNode());
5440     AddToWorklist(Hi.getNode());
5441
5442     // Build a factor node to remember that this load is independent of the
5443     // other one.
5444     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5445                         Hi.getValue(1));
5446
5447     // Legalized the chain result - switch anything that used the old chain to
5448     // use the new one.
5449     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5450
5451     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5452
5453     SDValue RetOps[] = { LoadRes, Chain };
5454     return DAG.getMergeValues(RetOps, DL);
5455   }
5456   return SDValue();
5457 }
5458
5459 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5460   SDValue N0 = N->getOperand(0);
5461   SDValue N1 = N->getOperand(1);
5462   SDValue N2 = N->getOperand(2);
5463   SDLoc DL(N);
5464
5465   // Canonicalize integer abs.
5466   // vselect (setg[te] X,  0),  X, -X ->
5467   // vselect (setgt    X, -1),  X, -X ->
5468   // vselect (setl[te] X,  0), -X,  X ->
5469   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5470   if (N0.getOpcode() == ISD::SETCC) {
5471     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5472     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5473     bool isAbs = false;
5474     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5475
5476     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5477          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5478         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5479       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5480     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5481              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5482       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5483
5484     if (isAbs) {
5485       EVT VT = LHS.getValueType();
5486       SDValue Shift = DAG.getNode(
5487           ISD::SRA, DL, VT, LHS,
5488           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5489       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5490       AddToWorklist(Shift.getNode());
5491       AddToWorklist(Add.getNode());
5492       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5493     }
5494   }
5495
5496   if (SimplifySelectOps(N, N1, N2))
5497     return SDValue(N, 0);  // Don't revisit N.
5498
5499   // If the VSELECT result requires splitting and the mask is provided by a
5500   // SETCC, then split both nodes and its operands before legalization. This
5501   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5502   // and enables future optimizations (e.g. min/max pattern matching on X86).
5503   if (N0.getOpcode() == ISD::SETCC) {
5504     EVT VT = N->getValueType(0);
5505
5506     // Check if any splitting is required.
5507     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5508         TargetLowering::TypeSplitVector)
5509       return SDValue();
5510
5511     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5512     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5513     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5514     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5515
5516     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5517     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5518
5519     // Add the new VSELECT nodes to the work list in case they need to be split
5520     // again.
5521     AddToWorklist(Lo.getNode());
5522     AddToWorklist(Hi.getNode());
5523
5524     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5525   }
5526
5527   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5528   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5529     return N1;
5530   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5531   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5532     return N2;
5533
5534   // The ConvertSelectToConcatVector function is assuming both the above
5535   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5536   // and addressed.
5537   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5538       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5539       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5540     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5541       return CV;
5542   }
5543
5544   return SDValue();
5545 }
5546
5547 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5548   SDValue N0 = N->getOperand(0);
5549   SDValue N1 = N->getOperand(1);
5550   SDValue N2 = N->getOperand(2);
5551   SDValue N3 = N->getOperand(3);
5552   SDValue N4 = N->getOperand(4);
5553   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5554
5555   // fold select_cc lhs, rhs, x, x, cc -> x
5556   if (N2 == N3)
5557     return N2;
5558
5559   // Determine if the condition we're dealing with is constant
5560   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5561                               N0, N1, CC, SDLoc(N), false);
5562   if (SCC.getNode()) {
5563     AddToWorklist(SCC.getNode());
5564
5565     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5566       if (!SCCC->isNullValue())
5567         return N2;    // cond always true -> true val
5568       else
5569         return N3;    // cond always false -> false val
5570     } else if (SCC->getOpcode() == ISD::UNDEF) {
5571       // When the condition is UNDEF, just return the first operand. This is
5572       // coherent the DAG creation, no setcc node is created in this case
5573       return N2;
5574     } else if (SCC.getOpcode() == ISD::SETCC) {
5575       // Fold to a simpler select_cc
5576       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5577                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5578                          SCC.getOperand(2));
5579     }
5580   }
5581
5582   // If we can fold this based on the true/false value, do so.
5583   if (SimplifySelectOps(N, N2, N3))
5584     return SDValue(N, 0);  // Don't revisit N.
5585
5586   // fold select_cc into other things, such as min/max/abs
5587   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5588 }
5589
5590 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5591   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5592                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5593                        SDLoc(N));
5594 }
5595
5596 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5597 /// a build_vector of constants.
5598 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5599 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5600 /// Vector extends are not folded if operations are legal; this is to
5601 /// avoid introducing illegal build_vector dag nodes.
5602 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5603                                          SelectionDAG &DAG, bool LegalTypes,
5604                                          bool LegalOperations) {
5605   unsigned Opcode = N->getOpcode();
5606   SDValue N0 = N->getOperand(0);
5607   EVT VT = N->getValueType(0);
5608
5609   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5610          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5611          && "Expected EXTEND dag node in input!");
5612
5613   // fold (sext c1) -> c1
5614   // fold (zext c1) -> c1
5615   // fold (aext c1) -> c1
5616   if (isa<ConstantSDNode>(N0))
5617     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5618
5619   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5620   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5621   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5622   EVT SVT = VT.getScalarType();
5623   if (!(VT.isVector() &&
5624       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5625       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5626     return nullptr;
5627
5628   // We can fold this node into a build_vector.
5629   unsigned VTBits = SVT.getSizeInBits();
5630   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5631   SmallVector<SDValue, 8> Elts;
5632   unsigned NumElts = VT.getVectorNumElements();
5633   SDLoc DL(N);
5634
5635   for (unsigned i=0; i != NumElts; ++i) {
5636     SDValue Op = N0->getOperand(i);
5637     if (Op->getOpcode() == ISD::UNDEF) {
5638       Elts.push_back(DAG.getUNDEF(SVT));
5639       continue;
5640     }
5641
5642     SDLoc DL(Op);
5643     // Get the constant value and if needed trunc it to the size of the type.
5644     // Nodes like build_vector might have constants wider than the scalar type.
5645     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5646     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5647       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5648     else
5649       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5650   }
5651
5652   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5653 }
5654
5655 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5656 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5657 // transformation. Returns true if extension are possible and the above
5658 // mentioned transformation is profitable.
5659 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5660                                     unsigned ExtOpc,
5661                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5662                                     const TargetLowering &TLI) {
5663   bool HasCopyToRegUses = false;
5664   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5665   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5666                             UE = N0.getNode()->use_end();
5667        UI != UE; ++UI) {
5668     SDNode *User = *UI;
5669     if (User == N)
5670       continue;
5671     if (UI.getUse().getResNo() != N0.getResNo())
5672       continue;
5673     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5674     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5675       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5676       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5677         // Sign bits will be lost after a zext.
5678         return false;
5679       bool Add = false;
5680       for (unsigned i = 0; i != 2; ++i) {
5681         SDValue UseOp = User->getOperand(i);
5682         if (UseOp == N0)
5683           continue;
5684         if (!isa<ConstantSDNode>(UseOp))
5685           return false;
5686         Add = true;
5687       }
5688       if (Add)
5689         ExtendNodes.push_back(User);
5690       continue;
5691     }
5692     // If truncates aren't free and there are users we can't
5693     // extend, it isn't worthwhile.
5694     if (!isTruncFree)
5695       return false;
5696     // Remember if this value is live-out.
5697     if (User->getOpcode() == ISD::CopyToReg)
5698       HasCopyToRegUses = true;
5699   }
5700
5701   if (HasCopyToRegUses) {
5702     bool BothLiveOut = false;
5703     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5704          UI != UE; ++UI) {
5705       SDUse &Use = UI.getUse();
5706       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5707         BothLiveOut = true;
5708         break;
5709       }
5710     }
5711     if (BothLiveOut)
5712       // Both unextended and extended values are live out. There had better be
5713       // a good reason for the transformation.
5714       return ExtendNodes.size();
5715   }
5716   return true;
5717 }
5718
5719 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5720                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5721                                   ISD::NodeType ExtType) {
5722   // Extend SetCC uses if necessary.
5723   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5724     SDNode *SetCC = SetCCs[i];
5725     SmallVector<SDValue, 4> Ops;
5726
5727     for (unsigned j = 0; j != 2; ++j) {
5728       SDValue SOp = SetCC->getOperand(j);
5729       if (SOp == Trunc)
5730         Ops.push_back(ExtLoad);
5731       else
5732         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5733     }
5734
5735     Ops.push_back(SetCC->getOperand(2));
5736     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5737   }
5738 }
5739
5740 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5741 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5742   SDValue N0 = N->getOperand(0);
5743   EVT DstVT = N->getValueType(0);
5744   EVT SrcVT = N0.getValueType();
5745
5746   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5747           N->getOpcode() == ISD::ZERO_EXTEND) &&
5748          "Unexpected node type (not an extend)!");
5749
5750   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5751   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5752   //   (v8i32 (sext (v8i16 (load x))))
5753   // into:
5754   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5755   //                          (v4i32 (sextload (x + 16)))))
5756   // Where uses of the original load, i.e.:
5757   //   (v8i16 (load x))
5758   // are replaced with:
5759   //   (v8i16 (truncate
5760   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5761   //                            (v4i32 (sextload (x + 16)))))))
5762   //
5763   // This combine is only applicable to illegal, but splittable, vectors.
5764   // All legal types, and illegal non-vector types, are handled elsewhere.
5765   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5766   //
5767   if (N0->getOpcode() != ISD::LOAD)
5768     return SDValue();
5769
5770   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5771
5772   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5773       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5774       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5775     return SDValue();
5776
5777   SmallVector<SDNode *, 4> SetCCs;
5778   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5779     return SDValue();
5780
5781   ISD::LoadExtType ExtType =
5782       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5783
5784   // Try to split the vector types to get down to legal types.
5785   EVT SplitSrcVT = SrcVT;
5786   EVT SplitDstVT = DstVT;
5787   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5788          SplitSrcVT.getVectorNumElements() > 1) {
5789     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5790     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5791   }
5792
5793   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5794     return SDValue();
5795
5796   SDLoc DL(N);
5797   const unsigned NumSplits =
5798       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5799   const unsigned Stride = SplitSrcVT.getStoreSize();
5800   SmallVector<SDValue, 4> Loads;
5801   SmallVector<SDValue, 4> Chains;
5802
5803   SDValue BasePtr = LN0->getBasePtr();
5804   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5805     const unsigned Offset = Idx * Stride;
5806     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5807
5808     SDValue SplitLoad = DAG.getExtLoad(
5809         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5810         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5811         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5812         Align, LN0->getAAInfo());
5813
5814     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5815                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5816
5817     Loads.push_back(SplitLoad.getValue(0));
5818     Chains.push_back(SplitLoad.getValue(1));
5819   }
5820
5821   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5822   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5823
5824   CombineTo(N, NewValue);
5825
5826   // Replace uses of the original load (before extension)
5827   // with a truncate of the concatenated sextloaded vectors.
5828   SDValue Trunc =
5829       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5830   CombineTo(N0.getNode(), Trunc, NewChain);
5831   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5832                   (ISD::NodeType)N->getOpcode());
5833   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5834 }
5835
5836 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5837   SDValue N0 = N->getOperand(0);
5838   EVT VT = N->getValueType(0);
5839
5840   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5841                                               LegalOperations))
5842     return SDValue(Res, 0);
5843
5844   // fold (sext (sext x)) -> (sext x)
5845   // fold (sext (aext x)) -> (sext x)
5846   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5847     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5848                        N0.getOperand(0));
5849
5850   if (N0.getOpcode() == ISD::TRUNCATE) {
5851     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5852     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5853     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5854       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5855       if (NarrowLoad.getNode() != N0.getNode()) {
5856         CombineTo(N0.getNode(), NarrowLoad);
5857         // CombineTo deleted the truncate, if needed, but not what's under it.
5858         AddToWorklist(oye);
5859       }
5860       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5861     }
5862
5863     // See if the value being truncated is already sign extended.  If so, just
5864     // eliminate the trunc/sext pair.
5865     SDValue Op = N0.getOperand(0);
5866     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5867     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5868     unsigned DestBits = VT.getScalarType().getSizeInBits();
5869     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5870
5871     if (OpBits == DestBits) {
5872       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5873       // bits, it is already ready.
5874       if (NumSignBits > DestBits-MidBits)
5875         return Op;
5876     } else if (OpBits < DestBits) {
5877       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5878       // bits, just sext from i32.
5879       if (NumSignBits > OpBits-MidBits)
5880         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5881     } else {
5882       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5883       // bits, just truncate to i32.
5884       if (NumSignBits > OpBits-MidBits)
5885         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5886     }
5887
5888     // fold (sext (truncate x)) -> (sextinreg x).
5889     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5890                                                  N0.getValueType())) {
5891       if (OpBits < DestBits)
5892         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5893       else if (OpBits > DestBits)
5894         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5895       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5896                          DAG.getValueType(N0.getValueType()));
5897     }
5898   }
5899
5900   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5901   // Only generate vector extloads when 1) they're legal, and 2) they are
5902   // deemed desirable by the target.
5903   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5904       ((!LegalOperations && !VT.isVector() &&
5905         !cast<LoadSDNode>(N0)->isVolatile()) ||
5906        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5907     bool DoXform = true;
5908     SmallVector<SDNode*, 4> SetCCs;
5909     if (!N0.hasOneUse())
5910       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5911     if (VT.isVector())
5912       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5913     if (DoXform) {
5914       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5915       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5916                                        LN0->getChain(),
5917                                        LN0->getBasePtr(), N0.getValueType(),
5918                                        LN0->getMemOperand());
5919       CombineTo(N, ExtLoad);
5920       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5921                                   N0.getValueType(), ExtLoad);
5922       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5923       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5924                       ISD::SIGN_EXTEND);
5925       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5926     }
5927   }
5928
5929   // fold (sext (load x)) to multiple smaller sextloads.
5930   // Only on illegal but splittable vectors.
5931   if (SDValue ExtLoad = CombineExtLoad(N))
5932     return ExtLoad;
5933
5934   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5935   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5936   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5937       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5938     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5939     EVT MemVT = LN0->getMemoryVT();
5940     if ((!LegalOperations && !LN0->isVolatile()) ||
5941         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5942       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5943                                        LN0->getChain(),
5944                                        LN0->getBasePtr(), MemVT,
5945                                        LN0->getMemOperand());
5946       CombineTo(N, ExtLoad);
5947       CombineTo(N0.getNode(),
5948                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5949                             N0.getValueType(), ExtLoad),
5950                 ExtLoad.getValue(1));
5951       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5952     }
5953   }
5954
5955   // fold (sext (and/or/xor (load x), cst)) ->
5956   //      (and/or/xor (sextload x), (sext cst))
5957   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5958        N0.getOpcode() == ISD::XOR) &&
5959       isa<LoadSDNode>(N0.getOperand(0)) &&
5960       N0.getOperand(1).getOpcode() == ISD::Constant &&
5961       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5962       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5963     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5964     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5965       bool DoXform = true;
5966       SmallVector<SDNode*, 4> SetCCs;
5967       if (!N0.hasOneUse())
5968         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5969                                           SetCCs, TLI);
5970       if (DoXform) {
5971         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5972                                          LN0->getChain(), LN0->getBasePtr(),
5973                                          LN0->getMemoryVT(),
5974                                          LN0->getMemOperand());
5975         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5976         Mask = Mask.sext(VT.getSizeInBits());
5977         SDLoc DL(N);
5978         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5979                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5980         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5981                                     SDLoc(N0.getOperand(0)),
5982                                     N0.getOperand(0).getValueType(), ExtLoad);
5983         CombineTo(N, And);
5984         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5985         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5986                         ISD::SIGN_EXTEND);
5987         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5988       }
5989     }
5990   }
5991
5992   if (N0.getOpcode() == ISD::SETCC) {
5993     EVT N0VT = N0.getOperand(0).getValueType();
5994     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5995     // Only do this before legalize for now.
5996     if (VT.isVector() && !LegalOperations &&
5997         TLI.getBooleanContents(N0VT) ==
5998             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5999       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6000       // of the same size as the compared operands. Only optimize sext(setcc())
6001       // if this is the case.
6002       EVT SVT = getSetCCResultType(N0VT);
6003
6004       // We know that the # elements of the results is the same as the
6005       // # elements of the compare (and the # elements of the compare result
6006       // for that matter).  Check to see that they are the same size.  If so,
6007       // we know that the element size of the sext'd result matches the
6008       // element size of the compare operands.
6009       if (VT.getSizeInBits() == SVT.getSizeInBits())
6010         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6011                              N0.getOperand(1),
6012                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6013
6014       // If the desired elements are smaller or larger than the source
6015       // elements we can use a matching integer vector type and then
6016       // truncate/sign extend
6017       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6018       if (SVT == MatchingVectorType) {
6019         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6020                                N0.getOperand(0), N0.getOperand(1),
6021                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6022         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6023       }
6024     }
6025
6026     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6027     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6028     SDLoc DL(N);
6029     SDValue NegOne =
6030       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6031     SDValue SCC =
6032       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6033                        NegOne, DAG.getConstant(0, DL, VT),
6034                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6035     if (SCC.getNode()) return SCC;
6036
6037     if (!VT.isVector()) {
6038       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6039       if (!LegalOperations ||
6040           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6041         SDLoc DL(N);
6042         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6043         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6044                                      N0.getOperand(0), N0.getOperand(1), CC);
6045         return DAG.getSelect(DL, VT, SetCC,
6046                              NegOne, DAG.getConstant(0, DL, VT));
6047       }
6048     }
6049   }
6050
6051   // fold (sext x) -> (zext x) if the sign bit is known zero.
6052   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6053       DAG.SignBitIsZero(N0))
6054     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6055
6056   return SDValue();
6057 }
6058
6059 // isTruncateOf - If N is a truncate of some other value, return true, record
6060 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6061 // This function computes KnownZero to avoid a duplicated call to
6062 // computeKnownBits in the caller.
6063 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6064                          APInt &KnownZero) {
6065   APInt KnownOne;
6066   if (N->getOpcode() == ISD::TRUNCATE) {
6067     Op = N->getOperand(0);
6068     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6069     return true;
6070   }
6071
6072   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6073       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6074     return false;
6075
6076   SDValue Op0 = N->getOperand(0);
6077   SDValue Op1 = N->getOperand(1);
6078   assert(Op0.getValueType() == Op1.getValueType());
6079
6080   if (isNullConstant(Op0))
6081     Op = Op1;
6082   else if (isNullConstant(Op1))
6083     Op = Op0;
6084   else
6085     return false;
6086
6087   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6088
6089   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6090     return false;
6091
6092   return true;
6093 }
6094
6095 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6096   SDValue N0 = N->getOperand(0);
6097   EVT VT = N->getValueType(0);
6098
6099   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6100                                               LegalOperations))
6101     return SDValue(Res, 0);
6102
6103   // fold (zext (zext x)) -> (zext x)
6104   // fold (zext (aext x)) -> (zext x)
6105   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6106     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6107                        N0.getOperand(0));
6108
6109   // fold (zext (truncate x)) -> (zext x) or
6110   //      (zext (truncate x)) -> (truncate x)
6111   // This is valid when the truncated bits of x are already zero.
6112   // FIXME: We should extend this to work for vectors too.
6113   SDValue Op;
6114   APInt KnownZero;
6115   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6116     APInt TruncatedBits =
6117       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6118       APInt(Op.getValueSizeInBits(), 0) :
6119       APInt::getBitsSet(Op.getValueSizeInBits(),
6120                         N0.getValueSizeInBits(),
6121                         std::min(Op.getValueSizeInBits(),
6122                                  VT.getSizeInBits()));
6123     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6124       if (VT.bitsGT(Op.getValueType()))
6125         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6126       if (VT.bitsLT(Op.getValueType()))
6127         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6128
6129       return Op;
6130     }
6131   }
6132
6133   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6134   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6135   if (N0.getOpcode() == ISD::TRUNCATE) {
6136     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6137       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6138       if (NarrowLoad.getNode() != N0.getNode()) {
6139         CombineTo(N0.getNode(), NarrowLoad);
6140         // CombineTo deleted the truncate, if needed, but not what's under it.
6141         AddToWorklist(oye);
6142       }
6143       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6144     }
6145   }
6146
6147   // fold (zext (truncate x)) -> (and x, mask)
6148   if (N0.getOpcode() == ISD::TRUNCATE) {
6149     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6150     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6151     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6152       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6153       if (NarrowLoad.getNode() != N0.getNode()) {
6154         CombineTo(N0.getNode(), NarrowLoad);
6155         // CombineTo deleted the truncate, if needed, but not what's under it.
6156         AddToWorklist(oye);
6157       }
6158       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6159     }
6160
6161     EVT SrcVT = N0.getOperand(0).getValueType();
6162     EVT MinVT = N0.getValueType();
6163
6164     // Try to mask before the extension to avoid having to generate a larger mask,
6165     // possibly over several sub-vectors.
6166     if (SrcVT.bitsLT(VT)) {
6167       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6168                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6169         SDValue Op = N0.getOperand(0);
6170         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6171         AddToWorklist(Op.getNode());
6172         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6173       }
6174     }
6175
6176     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6177       SDValue Op = N0.getOperand(0);
6178       if (SrcVT.bitsLT(VT)) {
6179         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6180         AddToWorklist(Op.getNode());
6181       } else if (SrcVT.bitsGT(VT)) {
6182         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6183         AddToWorklist(Op.getNode());
6184       }
6185       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6186     }
6187   }
6188
6189   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6190   // if either of the casts is not free.
6191   if (N0.getOpcode() == ISD::AND &&
6192       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6193       N0.getOperand(1).getOpcode() == ISD::Constant &&
6194       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6195                            N0.getValueType()) ||
6196        !TLI.isZExtFree(N0.getValueType(), VT))) {
6197     SDValue X = N0.getOperand(0).getOperand(0);
6198     if (X.getValueType().bitsLT(VT)) {
6199       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6200     } else if (X.getValueType().bitsGT(VT)) {
6201       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6202     }
6203     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6204     Mask = Mask.zext(VT.getSizeInBits());
6205     SDLoc DL(N);
6206     return DAG.getNode(ISD::AND, DL, VT,
6207                        X, DAG.getConstant(Mask, DL, VT));
6208   }
6209
6210   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6211   // Only generate vector extloads when 1) they're legal, and 2) they are
6212   // deemed desirable by the target.
6213   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6214       ((!LegalOperations && !VT.isVector() &&
6215         !cast<LoadSDNode>(N0)->isVolatile()) ||
6216        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6217     bool DoXform = true;
6218     SmallVector<SDNode*, 4> SetCCs;
6219     if (!N0.hasOneUse())
6220       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6221     if (VT.isVector())
6222       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6223     if (DoXform) {
6224       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6225       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6226                                        LN0->getChain(),
6227                                        LN0->getBasePtr(), N0.getValueType(),
6228                                        LN0->getMemOperand());
6229       CombineTo(N, ExtLoad);
6230       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6231                                   N0.getValueType(), ExtLoad);
6232       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6233
6234       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6235                       ISD::ZERO_EXTEND);
6236       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6237     }
6238   }
6239
6240   // fold (zext (load x)) to multiple smaller zextloads.
6241   // Only on illegal but splittable vectors.
6242   if (SDValue ExtLoad = CombineExtLoad(N))
6243     return ExtLoad;
6244
6245   // fold (zext (and/or/xor (load x), cst)) ->
6246   //      (and/or/xor (zextload x), (zext cst))
6247   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6248        N0.getOpcode() == ISD::XOR) &&
6249       isa<LoadSDNode>(N0.getOperand(0)) &&
6250       N0.getOperand(1).getOpcode() == ISD::Constant &&
6251       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6252       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6253     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6254     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6255       bool DoXform = true;
6256       SmallVector<SDNode*, 4> SetCCs;
6257       if (!N0.hasOneUse())
6258         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6259                                           SetCCs, TLI);
6260       if (DoXform) {
6261         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6262                                          LN0->getChain(), LN0->getBasePtr(),
6263                                          LN0->getMemoryVT(),
6264                                          LN0->getMemOperand());
6265         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6266         Mask = Mask.zext(VT.getSizeInBits());
6267         SDLoc DL(N);
6268         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6269                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6270         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6271                                     SDLoc(N0.getOperand(0)),
6272                                     N0.getOperand(0).getValueType(), ExtLoad);
6273         CombineTo(N, And);
6274         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6275         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6276                         ISD::ZERO_EXTEND);
6277         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6278       }
6279     }
6280   }
6281
6282   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6283   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6284   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6285       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6286     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6287     EVT MemVT = LN0->getMemoryVT();
6288     if ((!LegalOperations && !LN0->isVolatile()) ||
6289         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6290       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6291                                        LN0->getChain(),
6292                                        LN0->getBasePtr(), MemVT,
6293                                        LN0->getMemOperand());
6294       CombineTo(N, ExtLoad);
6295       CombineTo(N0.getNode(),
6296                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6297                             ExtLoad),
6298                 ExtLoad.getValue(1));
6299       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6300     }
6301   }
6302
6303   if (N0.getOpcode() == ISD::SETCC) {
6304     if (!LegalOperations && VT.isVector() &&
6305         N0.getValueType().getVectorElementType() == MVT::i1) {
6306       EVT N0VT = N0.getOperand(0).getValueType();
6307       if (getSetCCResultType(N0VT) == N0.getValueType())
6308         return SDValue();
6309
6310       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6311       // Only do this before legalize for now.
6312       EVT EltVT = VT.getVectorElementType();
6313       SDLoc DL(N);
6314       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6315                                     DAG.getConstant(1, DL, EltVT));
6316       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6317         // We know that the # elements of the results is the same as the
6318         // # elements of the compare (and the # elements of the compare result
6319         // for that matter).  Check to see that they are the same size.  If so,
6320         // we know that the element size of the sext'd result matches the
6321         // element size of the compare operands.
6322         return DAG.getNode(ISD::AND, DL, VT,
6323                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6324                                          N0.getOperand(1),
6325                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6326                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6327                                        OneOps));
6328
6329       // If the desired elements are smaller or larger than the source
6330       // elements we can use a matching integer vector type and then
6331       // truncate/sign extend
6332       EVT MatchingElementType =
6333         EVT::getIntegerVT(*DAG.getContext(),
6334                           N0VT.getScalarType().getSizeInBits());
6335       EVT MatchingVectorType =
6336         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6337                          N0VT.getVectorNumElements());
6338       SDValue VsetCC =
6339         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6340                       N0.getOperand(1),
6341                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6342       return DAG.getNode(ISD::AND, DL, VT,
6343                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6344                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6345     }
6346
6347     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6348     SDLoc DL(N);
6349     SDValue SCC =
6350       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6351                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6352                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6353     if (SCC.getNode()) return SCC;
6354   }
6355
6356   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6357   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6358       isa<ConstantSDNode>(N0.getOperand(1)) &&
6359       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6360       N0.hasOneUse()) {
6361     SDValue ShAmt = N0.getOperand(1);
6362     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6363     if (N0.getOpcode() == ISD::SHL) {
6364       SDValue InnerZExt = N0.getOperand(0);
6365       // If the original shl may be shifting out bits, do not perform this
6366       // transformation.
6367       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6368         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6369       if (ShAmtVal > KnownZeroBits)
6370         return SDValue();
6371     }
6372
6373     SDLoc DL(N);
6374
6375     // Ensure that the shift amount is wide enough for the shifted value.
6376     if (VT.getSizeInBits() >= 256)
6377       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6378
6379     return DAG.getNode(N0.getOpcode(), DL, VT,
6380                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6381                        ShAmt);
6382   }
6383
6384   return SDValue();
6385 }
6386
6387 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6388   SDValue N0 = N->getOperand(0);
6389   EVT VT = N->getValueType(0);
6390
6391   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6392                                               LegalOperations))
6393     return SDValue(Res, 0);
6394
6395   // fold (aext (aext x)) -> (aext x)
6396   // fold (aext (zext x)) -> (zext x)
6397   // fold (aext (sext x)) -> (sext x)
6398   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6399       N0.getOpcode() == ISD::ZERO_EXTEND ||
6400       N0.getOpcode() == ISD::SIGN_EXTEND)
6401     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6402
6403   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6404   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6405   if (N0.getOpcode() == ISD::TRUNCATE) {
6406     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6407       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6408       if (NarrowLoad.getNode() != N0.getNode()) {
6409         CombineTo(N0.getNode(), NarrowLoad);
6410         // CombineTo deleted the truncate, if needed, but not what's under it.
6411         AddToWorklist(oye);
6412       }
6413       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6414     }
6415   }
6416
6417   // fold (aext (truncate x))
6418   if (N0.getOpcode() == ISD::TRUNCATE) {
6419     SDValue TruncOp = N0.getOperand(0);
6420     if (TruncOp.getValueType() == VT)
6421       return TruncOp; // x iff x size == zext size.
6422     if (TruncOp.getValueType().bitsGT(VT))
6423       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6424     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6425   }
6426
6427   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6428   // if the trunc is not free.
6429   if (N0.getOpcode() == ISD::AND &&
6430       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6431       N0.getOperand(1).getOpcode() == ISD::Constant &&
6432       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6433                           N0.getValueType())) {
6434     SDValue X = N0.getOperand(0).getOperand(0);
6435     if (X.getValueType().bitsLT(VT)) {
6436       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6437     } else if (X.getValueType().bitsGT(VT)) {
6438       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6439     }
6440     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6441     Mask = Mask.zext(VT.getSizeInBits());
6442     SDLoc DL(N);
6443     return DAG.getNode(ISD::AND, DL, VT,
6444                        X, DAG.getConstant(Mask, DL, VT));
6445   }
6446
6447   // fold (aext (load x)) -> (aext (truncate (extload x)))
6448   // None of the supported targets knows how to perform load and any_ext
6449   // on vectors in one instruction.  We only perform this transformation on
6450   // scalars.
6451   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6452       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6453       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6454     bool DoXform = true;
6455     SmallVector<SDNode*, 4> SetCCs;
6456     if (!N0.hasOneUse())
6457       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6458     if (DoXform) {
6459       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6460       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6461                                        LN0->getChain(),
6462                                        LN0->getBasePtr(), N0.getValueType(),
6463                                        LN0->getMemOperand());
6464       CombineTo(N, ExtLoad);
6465       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6466                                   N0.getValueType(), ExtLoad);
6467       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6468       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6469                       ISD::ANY_EXTEND);
6470       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6471     }
6472   }
6473
6474   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6475   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6476   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6477   if (N0.getOpcode() == ISD::LOAD &&
6478       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6479       N0.hasOneUse()) {
6480     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6481     ISD::LoadExtType ExtType = LN0->getExtensionType();
6482     EVT MemVT = LN0->getMemoryVT();
6483     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6484       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6485                                        VT, LN0->getChain(), LN0->getBasePtr(),
6486                                        MemVT, LN0->getMemOperand());
6487       CombineTo(N, ExtLoad);
6488       CombineTo(N0.getNode(),
6489                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6490                             N0.getValueType(), ExtLoad),
6491                 ExtLoad.getValue(1));
6492       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6493     }
6494   }
6495
6496   if (N0.getOpcode() == ISD::SETCC) {
6497     // For vectors:
6498     // aext(setcc) -> vsetcc
6499     // aext(setcc) -> truncate(vsetcc)
6500     // aext(setcc) -> aext(vsetcc)
6501     // Only do this before legalize for now.
6502     if (VT.isVector() && !LegalOperations) {
6503       EVT N0VT = N0.getOperand(0).getValueType();
6504         // We know that the # elements of the results is the same as the
6505         // # elements of the compare (and the # elements of the compare result
6506         // for that matter).  Check to see that they are the same size.  If so,
6507         // we know that the element size of the sext'd result matches the
6508         // element size of the compare operands.
6509       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6510         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6511                              N0.getOperand(1),
6512                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6513       // If the desired elements are smaller or larger than the source
6514       // elements we can use a matching integer vector type and then
6515       // truncate/any extend
6516       else {
6517         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6518         SDValue VsetCC =
6519           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6520                         N0.getOperand(1),
6521                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6522         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6523       }
6524     }
6525
6526     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6527     SDLoc DL(N);
6528     SDValue SCC =
6529       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6530                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6531                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6532     if (SCC.getNode())
6533       return SCC;
6534   }
6535
6536   return SDValue();
6537 }
6538
6539 /// See if the specified operand can be simplified with the knowledge that only
6540 /// the bits specified by Mask are used.  If so, return the simpler operand,
6541 /// otherwise return a null SDValue.
6542 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6543   switch (V.getOpcode()) {
6544   default: break;
6545   case ISD::Constant: {
6546     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6547     assert(CV && "Const value should be ConstSDNode.");
6548     const APInt &CVal = CV->getAPIntValue();
6549     APInt NewVal = CVal & Mask;
6550     if (NewVal != CVal)
6551       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6552     break;
6553   }
6554   case ISD::OR:
6555   case ISD::XOR:
6556     // If the LHS or RHS don't contribute bits to the or, drop them.
6557     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6558       return V.getOperand(1);
6559     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6560       return V.getOperand(0);
6561     break;
6562   case ISD::SRL:
6563     // Only look at single-use SRLs.
6564     if (!V.getNode()->hasOneUse())
6565       break;
6566     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6567       // See if we can recursively simplify the LHS.
6568       unsigned Amt = RHSC->getZExtValue();
6569
6570       // Watch out for shift count overflow though.
6571       if (Amt >= Mask.getBitWidth()) break;
6572       APInt NewMask = Mask << Amt;
6573       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6574         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6575                            SimplifyLHS, V.getOperand(1));
6576     }
6577   }
6578   return SDValue();
6579 }
6580
6581 /// If the result of a wider load is shifted to right of N  bits and then
6582 /// truncated to a narrower type and where N is a multiple of number of bits of
6583 /// the narrower type, transform it to a narrower load from address + N / num of
6584 /// bits of new type. If the result is to be extended, also fold the extension
6585 /// to form a extending load.
6586 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6587   unsigned Opc = N->getOpcode();
6588
6589   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6590   SDValue N0 = N->getOperand(0);
6591   EVT VT = N->getValueType(0);
6592   EVT ExtVT = VT;
6593
6594   // This transformation isn't valid for vector loads.
6595   if (VT.isVector())
6596     return SDValue();
6597
6598   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6599   // extended to VT.
6600   if (Opc == ISD::SIGN_EXTEND_INREG) {
6601     ExtType = ISD::SEXTLOAD;
6602     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6603   } else if (Opc == ISD::SRL) {
6604     // Another special-case: SRL is basically zero-extending a narrower value.
6605     ExtType = ISD::ZEXTLOAD;
6606     N0 = SDValue(N, 0);
6607     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6608     if (!N01) return SDValue();
6609     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6610                               VT.getSizeInBits() - N01->getZExtValue());
6611   }
6612   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6613     return SDValue();
6614
6615   unsigned EVTBits = ExtVT.getSizeInBits();
6616
6617   // Do not generate loads of non-round integer types since these can
6618   // be expensive (and would be wrong if the type is not byte sized).
6619   if (!ExtVT.isRound())
6620     return SDValue();
6621
6622   unsigned ShAmt = 0;
6623   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6624     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6625       ShAmt = N01->getZExtValue();
6626       // Is the shift amount a multiple of size of VT?
6627       if ((ShAmt & (EVTBits-1)) == 0) {
6628         N0 = N0.getOperand(0);
6629         // Is the load width a multiple of size of VT?
6630         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6631           return SDValue();
6632       }
6633
6634       // At this point, we must have a load or else we can't do the transform.
6635       if (!isa<LoadSDNode>(N0)) return SDValue();
6636
6637       // Because a SRL must be assumed to *need* to zero-extend the high bits
6638       // (as opposed to anyext the high bits), we can't combine the zextload
6639       // lowering of SRL and an sextload.
6640       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6641         return SDValue();
6642
6643       // If the shift amount is larger than the input type then we're not
6644       // accessing any of the loaded bytes.  If the load was a zextload/extload
6645       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6646       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6647         return SDValue();
6648     }
6649   }
6650
6651   // If the load is shifted left (and the result isn't shifted back right),
6652   // we can fold the truncate through the shift.
6653   unsigned ShLeftAmt = 0;
6654   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6655       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6656     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6657       ShLeftAmt = N01->getZExtValue();
6658       N0 = N0.getOperand(0);
6659     }
6660   }
6661
6662   // If we haven't found a load, we can't narrow it.  Don't transform one with
6663   // multiple uses, this would require adding a new load.
6664   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6665     return SDValue();
6666
6667   // Don't change the width of a volatile load.
6668   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6669   if (LN0->isVolatile())
6670     return SDValue();
6671
6672   // Verify that we are actually reducing a load width here.
6673   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6674     return SDValue();
6675
6676   // For the transform to be legal, the load must produce only two values
6677   // (the value loaded and the chain).  Don't transform a pre-increment
6678   // load, for example, which produces an extra value.  Otherwise the
6679   // transformation is not equivalent, and the downstream logic to replace
6680   // uses gets things wrong.
6681   if (LN0->getNumValues() > 2)
6682     return SDValue();
6683
6684   // If the load that we're shrinking is an extload and we're not just
6685   // discarding the extension we can't simply shrink the load. Bail.
6686   // TODO: It would be possible to merge the extensions in some cases.
6687   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6688       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6689     return SDValue();
6690
6691   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6692     return SDValue();
6693
6694   EVT PtrType = N0.getOperand(1).getValueType();
6695
6696   if (PtrType == MVT::Untyped || PtrType.isExtended())
6697     // It's not possible to generate a constant of extended or untyped type.
6698     return SDValue();
6699
6700   // For big endian targets, we need to adjust the offset to the pointer to
6701   // load the correct bytes.
6702   if (DAG.getDataLayout().isBigEndian()) {
6703     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6704     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6705     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6706   }
6707
6708   uint64_t PtrOff = ShAmt / 8;
6709   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6710   SDLoc DL(LN0);
6711   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6712                                PtrType, LN0->getBasePtr(),
6713                                DAG.getConstant(PtrOff, DL, PtrType));
6714   AddToWorklist(NewPtr.getNode());
6715
6716   SDValue Load;
6717   if (ExtType == ISD::NON_EXTLOAD)
6718     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6719                         LN0->getPointerInfo().getWithOffset(PtrOff),
6720                         LN0->isVolatile(), LN0->isNonTemporal(),
6721                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6722   else
6723     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6724                           LN0->getPointerInfo().getWithOffset(PtrOff),
6725                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6726                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6727
6728   // Replace the old load's chain with the new load's chain.
6729   WorklistRemover DeadNodes(*this);
6730   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6731
6732   // Shift the result left, if we've swallowed a left shift.
6733   SDValue Result = Load;
6734   if (ShLeftAmt != 0) {
6735     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6736     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6737       ShImmTy = VT;
6738     // If the shift amount is as large as the result size (but, presumably,
6739     // no larger than the source) then the useful bits of the result are
6740     // zero; we can't simply return the shortened shift, because the result
6741     // of that operation is undefined.
6742     SDLoc DL(N0);
6743     if (ShLeftAmt >= VT.getSizeInBits())
6744       Result = DAG.getConstant(0, DL, VT);
6745     else
6746       Result = DAG.getNode(ISD::SHL, DL, VT,
6747                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6748   }
6749
6750   // Return the new loaded value.
6751   return Result;
6752 }
6753
6754 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6755   SDValue N0 = N->getOperand(0);
6756   SDValue N1 = N->getOperand(1);
6757   EVT VT = N->getValueType(0);
6758   EVT EVT = cast<VTSDNode>(N1)->getVT();
6759   unsigned VTBits = VT.getScalarType().getSizeInBits();
6760   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6761
6762   if (N0.isUndef())
6763     return DAG.getUNDEF(VT);
6764
6765   // fold (sext_in_reg c1) -> c1
6766   if (isConstantIntBuildVectorOrConstantInt(N0))
6767     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6768
6769   // If the input is already sign extended, just drop the extension.
6770   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6771     return N0;
6772
6773   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6774   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6775       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6776     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6777                        N0.getOperand(0), N1);
6778
6779   // fold (sext_in_reg (sext x)) -> (sext x)
6780   // fold (sext_in_reg (aext x)) -> (sext x)
6781   // if x is small enough.
6782   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6783     SDValue N00 = N0.getOperand(0);
6784     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6785         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6786       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6787   }
6788
6789   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6790   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6791     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6792
6793   // fold operands of sext_in_reg based on knowledge that the top bits are not
6794   // demanded.
6795   if (SimplifyDemandedBits(SDValue(N, 0)))
6796     return SDValue(N, 0);
6797
6798   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6799   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6800   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6801     return NarrowLoad;
6802
6803   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6804   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6805   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6806   if (N0.getOpcode() == ISD::SRL) {
6807     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6808       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6809         // We can turn this into an SRA iff the input to the SRL is already sign
6810         // extended enough.
6811         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6812         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6813           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6814                              N0.getOperand(0), N0.getOperand(1));
6815       }
6816   }
6817
6818   // fold (sext_inreg (extload x)) -> (sextload x)
6819   if (ISD::isEXTLoad(N0.getNode()) &&
6820       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6821       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6822       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6823        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6824     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6825     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6826                                      LN0->getChain(),
6827                                      LN0->getBasePtr(), EVT,
6828                                      LN0->getMemOperand());
6829     CombineTo(N, ExtLoad);
6830     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6831     AddToWorklist(ExtLoad.getNode());
6832     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6833   }
6834   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6835   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6836       N0.hasOneUse() &&
6837       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6838       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6839        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6840     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6841     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6842                                      LN0->getChain(),
6843                                      LN0->getBasePtr(), EVT,
6844                                      LN0->getMemOperand());
6845     CombineTo(N, ExtLoad);
6846     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6847     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6848   }
6849
6850   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6851   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6852     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6853                                        N0.getOperand(1), false);
6854     if (BSwap.getNode())
6855       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6856                          BSwap, N1);
6857   }
6858
6859   return SDValue();
6860 }
6861
6862 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6863   SDValue N0 = N->getOperand(0);
6864   EVT VT = N->getValueType(0);
6865
6866   if (N0.getOpcode() == ISD::UNDEF)
6867     return DAG.getUNDEF(VT);
6868
6869   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6870                                               LegalOperations))
6871     return SDValue(Res, 0);
6872
6873   return SDValue();
6874 }
6875
6876 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6877   SDValue N0 = N->getOperand(0);
6878   EVT VT = N->getValueType(0);
6879   bool isLE = DAG.getDataLayout().isLittleEndian();
6880
6881   // noop truncate
6882   if (N0.getValueType() == N->getValueType(0))
6883     return N0;
6884   // fold (truncate c1) -> c1
6885   if (isConstantIntBuildVectorOrConstantInt(N0))
6886     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6887   // fold (truncate (truncate x)) -> (truncate x)
6888   if (N0.getOpcode() == ISD::TRUNCATE)
6889     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6890   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6891   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6892       N0.getOpcode() == ISD::SIGN_EXTEND ||
6893       N0.getOpcode() == ISD::ANY_EXTEND) {
6894     if (N0.getOperand(0).getValueType().bitsLT(VT))
6895       // if the source is smaller than the dest, we still need an extend
6896       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6897                          N0.getOperand(0));
6898     if (N0.getOperand(0).getValueType().bitsGT(VT))
6899       // if the source is larger than the dest, than we just need the truncate
6900       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6901     // if the source and dest are the same type, we can drop both the extend
6902     // and the truncate.
6903     return N0.getOperand(0);
6904   }
6905
6906   // Fold extract-and-trunc into a narrow extract. For example:
6907   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6908   //   i32 y = TRUNCATE(i64 x)
6909   //        -- becomes --
6910   //   v16i8 b = BITCAST (v2i64 val)
6911   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6912   //
6913   // Note: We only run this optimization after type legalization (which often
6914   // creates this pattern) and before operation legalization after which
6915   // we need to be more careful about the vector instructions that we generate.
6916   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6917       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6918
6919     EVT VecTy = N0.getOperand(0).getValueType();
6920     EVT ExTy = N0.getValueType();
6921     EVT TrTy = N->getValueType(0);
6922
6923     unsigned NumElem = VecTy.getVectorNumElements();
6924     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6925
6926     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6927     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6928
6929     SDValue EltNo = N0->getOperand(1);
6930     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6931       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6932       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6933       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6934
6935       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6936                               NVT, N0.getOperand(0));
6937
6938       SDLoc DL(N);
6939       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6940                          DL, TrTy, V,
6941                          DAG.getConstant(Index, DL, IndexTy));
6942     }
6943   }
6944
6945   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6946   if (N0.getOpcode() == ISD::SELECT) {
6947     EVT SrcVT = N0.getValueType();
6948     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6949         TLI.isTruncateFree(SrcVT, VT)) {
6950       SDLoc SL(N0);
6951       SDValue Cond = N0.getOperand(0);
6952       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6953       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6954       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6955     }
6956   }
6957
6958   // Fold a series of buildvector, bitcast, and truncate if possible.
6959   // For example fold
6960   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6961   //   (2xi32 (buildvector x, y)).
6962   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6963       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6964       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6965       N0.getOperand(0).hasOneUse()) {
6966
6967     SDValue BuildVect = N0.getOperand(0);
6968     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6969     EVT TruncVecEltTy = VT.getVectorElementType();
6970
6971     // Check that the element types match.
6972     if (BuildVectEltTy == TruncVecEltTy) {
6973       // Now we only need to compute the offset of the truncated elements.
6974       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6975       unsigned TruncVecNumElts = VT.getVectorNumElements();
6976       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6977
6978       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6979              "Invalid number of elements");
6980
6981       SmallVector<SDValue, 8> Opnds;
6982       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6983         Opnds.push_back(BuildVect.getOperand(i));
6984
6985       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6986     }
6987   }
6988
6989   // See if we can simplify the input to this truncate through knowledge that
6990   // only the low bits are being used.
6991   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6992   // Currently we only perform this optimization on scalars because vectors
6993   // may have different active low bits.
6994   if (!VT.isVector()) {
6995     SDValue Shorter =
6996       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6997                                                VT.getSizeInBits()));
6998     if (Shorter.getNode())
6999       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7000   }
7001   // fold (truncate (load x)) -> (smaller load x)
7002   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7003   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7004     if (SDValue Reduced = ReduceLoadWidth(N))
7005       return Reduced;
7006
7007     // Handle the case where the load remains an extending load even
7008     // after truncation.
7009     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7010       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7011       if (!LN0->isVolatile() &&
7012           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7013         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7014                                          VT, LN0->getChain(), LN0->getBasePtr(),
7015                                          LN0->getMemoryVT(),
7016                                          LN0->getMemOperand());
7017         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7018         return NewLoad;
7019       }
7020     }
7021   }
7022   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7023   // where ... are all 'undef'.
7024   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7025     SmallVector<EVT, 8> VTs;
7026     SDValue V;
7027     unsigned Idx = 0;
7028     unsigned NumDefs = 0;
7029
7030     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7031       SDValue X = N0.getOperand(i);
7032       if (X.getOpcode() != ISD::UNDEF) {
7033         V = X;
7034         Idx = i;
7035         NumDefs++;
7036       }
7037       // Stop if more than one members are non-undef.
7038       if (NumDefs > 1)
7039         break;
7040       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7041                                      VT.getVectorElementType(),
7042                                      X.getValueType().getVectorNumElements()));
7043     }
7044
7045     if (NumDefs == 0)
7046       return DAG.getUNDEF(VT);
7047
7048     if (NumDefs == 1) {
7049       assert(V.getNode() && "The single defined operand is empty!");
7050       SmallVector<SDValue, 8> Opnds;
7051       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7052         if (i != Idx) {
7053           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7054           continue;
7055         }
7056         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7057         AddToWorklist(NV.getNode());
7058         Opnds.push_back(NV);
7059       }
7060       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7061     }
7062   }
7063
7064   // Simplify the operands using demanded-bits information.
7065   if (!VT.isVector() &&
7066       SimplifyDemandedBits(SDValue(N, 0)))
7067     return SDValue(N, 0);
7068
7069   return SDValue();
7070 }
7071
7072 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7073   SDValue Elt = N->getOperand(i);
7074   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7075     return Elt.getNode();
7076   return Elt.getOperand(Elt.getResNo()).getNode();
7077 }
7078
7079 /// build_pair (load, load) -> load
7080 /// if load locations are consecutive.
7081 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7082   assert(N->getOpcode() == ISD::BUILD_PAIR);
7083
7084   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7085   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7086   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7087       LD1->getAddressSpace() != LD2->getAddressSpace())
7088     return SDValue();
7089   EVT LD1VT = LD1->getValueType(0);
7090
7091   if (ISD::isNON_EXTLoad(LD2) &&
7092       LD2->hasOneUse() &&
7093       // If both are volatile this would reduce the number of volatile loads.
7094       // If one is volatile it might be ok, but play conservative and bail out.
7095       !LD1->isVolatile() &&
7096       !LD2->isVolatile() &&
7097       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7098     unsigned Align = LD1->getAlignment();
7099     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7100         VT.getTypeForEVT(*DAG.getContext()));
7101
7102     if (NewAlign <= Align &&
7103         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7104       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7105                          LD1->getBasePtr(), LD1->getPointerInfo(),
7106                          false, false, false, Align);
7107   }
7108
7109   return SDValue();
7110 }
7111
7112 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7113   SDValue N0 = N->getOperand(0);
7114   EVT VT = N->getValueType(0);
7115
7116   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7117   // Only do this before legalize, since afterward the target may be depending
7118   // on the bitconvert.
7119   // First check to see if this is all constant.
7120   if (!LegalTypes &&
7121       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7122       VT.isVector()) {
7123     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7124
7125     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7126     assert(!DestEltVT.isVector() &&
7127            "Element type of vector ValueType must not be vector!");
7128     if (isSimple)
7129       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7130   }
7131
7132   // If the input is a constant, let getNode fold it.
7133   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7134     // If we can't allow illegal operations, we need to check that this is just
7135     // a fp -> int or int -> conversion and that the resulting operation will
7136     // be legal.
7137     if (!LegalOperations ||
7138         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7139          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7140         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7141          TLI.isOperationLegal(ISD::Constant, VT)))
7142       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7143   }
7144
7145   // (conv (conv x, t1), t2) -> (conv x, t2)
7146   if (N0.getOpcode() == ISD::BITCAST)
7147     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7148                        N0.getOperand(0));
7149
7150   // fold (conv (load x)) -> (load (conv*)x)
7151   // If the resultant load doesn't need a higher alignment than the original!
7152   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7153       // Do not change the width of a volatile load.
7154       !cast<LoadSDNode>(N0)->isVolatile() &&
7155       // Do not remove the cast if the types differ in endian layout.
7156       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7157           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7158       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7159       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7160     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7161     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7162         VT.getTypeForEVT(*DAG.getContext()));
7163     unsigned OrigAlign = LN0->getAlignment();
7164
7165     if (Align <= OrigAlign) {
7166       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7167                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7168                                  LN0->isVolatile(), LN0->isNonTemporal(),
7169                                  LN0->isInvariant(), OrigAlign,
7170                                  LN0->getAAInfo());
7171       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7172       return Load;
7173     }
7174   }
7175
7176   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7177   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7178   // This often reduces constant pool loads.
7179   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7180        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7181       N0.getNode()->hasOneUse() && VT.isInteger() &&
7182       !VT.isVector() && !N0.getValueType().isVector()) {
7183     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7184                                   N0.getOperand(0));
7185     AddToWorklist(NewConv.getNode());
7186
7187     SDLoc DL(N);
7188     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7189     if (N0.getOpcode() == ISD::FNEG)
7190       return DAG.getNode(ISD::XOR, DL, VT,
7191                          NewConv, DAG.getConstant(SignBit, DL, VT));
7192     assert(N0.getOpcode() == ISD::FABS);
7193     return DAG.getNode(ISD::AND, DL, VT,
7194                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7195   }
7196
7197   // fold (bitconvert (fcopysign cst, x)) ->
7198   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7199   // Note that we don't handle (copysign x, cst) because this can always be
7200   // folded to an fneg or fabs.
7201   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7202       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7203       VT.isInteger() && !VT.isVector()) {
7204     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7205     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7206     if (isTypeLegal(IntXVT)) {
7207       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7208                               IntXVT, N0.getOperand(1));
7209       AddToWorklist(X.getNode());
7210
7211       // If X has a different width than the result/lhs, sext it or truncate it.
7212       unsigned VTWidth = VT.getSizeInBits();
7213       if (OrigXWidth < VTWidth) {
7214         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7215         AddToWorklist(X.getNode());
7216       } else if (OrigXWidth > VTWidth) {
7217         // To get the sign bit in the right place, we have to shift it right
7218         // before truncating.
7219         SDLoc DL(X);
7220         X = DAG.getNode(ISD::SRL, DL,
7221                         X.getValueType(), X,
7222                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7223                                         X.getValueType()));
7224         AddToWorklist(X.getNode());
7225         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7226         AddToWorklist(X.getNode());
7227       }
7228
7229       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7230       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7231                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7232       AddToWorklist(X.getNode());
7233
7234       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7235                                 VT, N0.getOperand(0));
7236       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7237                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7238       AddToWorklist(Cst.getNode());
7239
7240       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7241     }
7242   }
7243
7244   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7245   if (N0.getOpcode() == ISD::BUILD_PAIR)
7246     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7247       return CombineLD;
7248
7249   // Remove double bitcasts from shuffles - this is often a legacy of
7250   // XformToShuffleWithZero being used to combine bitmaskings (of
7251   // float vectors bitcast to integer vectors) into shuffles.
7252   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7253   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7254       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7255       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7256       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7257     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7258
7259     // If operands are a bitcast, peek through if it casts the original VT.
7260     // If operands are a constant, just bitcast back to original VT.
7261     auto PeekThroughBitcast = [&](SDValue Op) {
7262       if (Op.getOpcode() == ISD::BITCAST &&
7263           Op.getOperand(0).getValueType() == VT)
7264         return SDValue(Op.getOperand(0));
7265       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7266           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7267         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7268       return SDValue();
7269     };
7270
7271     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7272     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7273     if (!(SV0 && SV1))
7274       return SDValue();
7275
7276     int MaskScale =
7277         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7278     SmallVector<int, 8> NewMask;
7279     for (int M : SVN->getMask())
7280       for (int i = 0; i != MaskScale; ++i)
7281         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7282
7283     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7284     if (!LegalMask) {
7285       std::swap(SV0, SV1);
7286       ShuffleVectorSDNode::commuteMask(NewMask);
7287       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7288     }
7289
7290     if (LegalMask)
7291       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7292   }
7293
7294   return SDValue();
7295 }
7296
7297 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7298   EVT VT = N->getValueType(0);
7299   return CombineConsecutiveLoads(N, VT);
7300 }
7301
7302 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7303 /// operands. DstEltVT indicates the destination element value type.
7304 SDValue DAGCombiner::
7305 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7306   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7307
7308   // If this is already the right type, we're done.
7309   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7310
7311   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7312   unsigned DstBitSize = DstEltVT.getSizeInBits();
7313
7314   // If this is a conversion of N elements of one type to N elements of another
7315   // type, convert each element.  This handles FP<->INT cases.
7316   if (SrcBitSize == DstBitSize) {
7317     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7318                               BV->getValueType(0).getVectorNumElements());
7319
7320     // Due to the FP element handling below calling this routine recursively,
7321     // we can end up with a scalar-to-vector node here.
7322     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7323       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7324                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7325                                      DstEltVT, BV->getOperand(0)));
7326
7327     SmallVector<SDValue, 8> Ops;
7328     for (SDValue Op : BV->op_values()) {
7329       // If the vector element type is not legal, the BUILD_VECTOR operands
7330       // are promoted and implicitly truncated.  Make that explicit here.
7331       if (Op.getValueType() != SrcEltVT)
7332         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7333       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7334                                 DstEltVT, Op));
7335       AddToWorklist(Ops.back().getNode());
7336     }
7337     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7338   }
7339
7340   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7341   // handle annoying details of growing/shrinking FP values, we convert them to
7342   // int first.
7343   if (SrcEltVT.isFloatingPoint()) {
7344     // Convert the input float vector to a int vector where the elements are the
7345     // same sizes.
7346     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7347     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7348     SrcEltVT = IntVT;
7349   }
7350
7351   // Now we know the input is an integer vector.  If the output is a FP type,
7352   // convert to integer first, then to FP of the right size.
7353   if (DstEltVT.isFloatingPoint()) {
7354     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7355     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7356
7357     // Next, convert to FP elements of the same size.
7358     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7359   }
7360
7361   SDLoc DL(BV);
7362
7363   // Okay, we know the src/dst types are both integers of differing types.
7364   // Handling growing first.
7365   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7366   if (SrcBitSize < DstBitSize) {
7367     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7368
7369     SmallVector<SDValue, 8> Ops;
7370     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7371          i += NumInputsPerOutput) {
7372       bool isLE = DAG.getDataLayout().isLittleEndian();
7373       APInt NewBits = APInt(DstBitSize, 0);
7374       bool EltIsUndef = true;
7375       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7376         // Shift the previously computed bits over.
7377         NewBits <<= SrcBitSize;
7378         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7379         if (Op.getOpcode() == ISD::UNDEF) continue;
7380         EltIsUndef = false;
7381
7382         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7383                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7384       }
7385
7386       if (EltIsUndef)
7387         Ops.push_back(DAG.getUNDEF(DstEltVT));
7388       else
7389         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7390     }
7391
7392     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7393     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7394   }
7395
7396   // Finally, this must be the case where we are shrinking elements: each input
7397   // turns into multiple outputs.
7398   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7399   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7400                             NumOutputsPerInput*BV->getNumOperands());
7401   SmallVector<SDValue, 8> Ops;
7402
7403   for (const SDValue &Op : BV->op_values()) {
7404     if (Op.getOpcode() == ISD::UNDEF) {
7405       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7406       continue;
7407     }
7408
7409     APInt OpVal = cast<ConstantSDNode>(Op)->
7410                   getAPIntValue().zextOrTrunc(SrcBitSize);
7411
7412     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7413       APInt ThisVal = OpVal.trunc(DstBitSize);
7414       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7415       OpVal = OpVal.lshr(DstBitSize);
7416     }
7417
7418     // For big endian targets, swap the order of the pieces of each element.
7419     if (DAG.getDataLayout().isBigEndian())
7420       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7421   }
7422
7423   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7424 }
7425
7426 /// Try to perform FMA combining on a given FADD node.
7427 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7428   SDValue N0 = N->getOperand(0);
7429   SDValue N1 = N->getOperand(1);
7430   EVT VT = N->getValueType(0);
7431   SDLoc SL(N);
7432
7433   const TargetOptions &Options = DAG.getTarget().Options;
7434   bool AllowFusion =
7435       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7436
7437   // Floating-point multiply-add with intermediate rounding.
7438   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7439
7440   // Floating-point multiply-add without intermediate rounding.
7441   bool HasFMA =
7442       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7443       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7444
7445   // No valid opcode, do not combine.
7446   if (!HasFMAD && !HasFMA)
7447     return SDValue();
7448
7449   // Always prefer FMAD to FMA for precision.
7450   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7451   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7452   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7453
7454   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7455   // prefer to fold the multiply with fewer uses.
7456   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7457       N1.getOpcode() == ISD::FMUL) {
7458     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7459       std::swap(N0, N1);
7460   }
7461
7462   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7463   if (N0.getOpcode() == ISD::FMUL &&
7464       (Aggressive || N0->hasOneUse())) {
7465     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7466                        N0.getOperand(0), N0.getOperand(1), N1);
7467   }
7468
7469   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7470   // Note: Commutes FADD operands.
7471   if (N1.getOpcode() == ISD::FMUL &&
7472       (Aggressive || N1->hasOneUse())) {
7473     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7474                        N1.getOperand(0), N1.getOperand(1), N0);
7475   }
7476
7477   // Look through FP_EXTEND nodes to do more combining.
7478   if (AllowFusion && LookThroughFPExt) {
7479     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7480     if (N0.getOpcode() == ISD::FP_EXTEND) {
7481       SDValue N00 = N0.getOperand(0);
7482       if (N00.getOpcode() == ISD::FMUL)
7483         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7484                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7485                                        N00.getOperand(0)),
7486                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7487                                        N00.getOperand(1)), N1);
7488     }
7489
7490     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7491     // Note: Commutes FADD operands.
7492     if (N1.getOpcode() == ISD::FP_EXTEND) {
7493       SDValue N10 = N1.getOperand(0);
7494       if (N10.getOpcode() == ISD::FMUL)
7495         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7496                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7497                                        N10.getOperand(0)),
7498                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7499                                        N10.getOperand(1)), N0);
7500     }
7501   }
7502
7503   // More folding opportunities when target permits.
7504   if ((AllowFusion || HasFMAD)  && Aggressive) {
7505     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7506     if (N0.getOpcode() == PreferredFusedOpcode &&
7507         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7508       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7509                          N0.getOperand(0), N0.getOperand(1),
7510                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7511                                      N0.getOperand(2).getOperand(0),
7512                                      N0.getOperand(2).getOperand(1),
7513                                      N1));
7514     }
7515
7516     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7517     if (N1->getOpcode() == PreferredFusedOpcode &&
7518         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7519       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7520                          N1.getOperand(0), N1.getOperand(1),
7521                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7522                                      N1.getOperand(2).getOperand(0),
7523                                      N1.getOperand(2).getOperand(1),
7524                                      N0));
7525     }
7526
7527     if (AllowFusion && LookThroughFPExt) {
7528       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7529       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7530       auto FoldFAddFMAFPExtFMul = [&] (
7531           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7532         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7533                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7534                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7535                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7536                                        Z));
7537       };
7538       if (N0.getOpcode() == PreferredFusedOpcode) {
7539         SDValue N02 = N0.getOperand(2);
7540         if (N02.getOpcode() == ISD::FP_EXTEND) {
7541           SDValue N020 = N02.getOperand(0);
7542           if (N020.getOpcode() == ISD::FMUL)
7543             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7544                                         N020.getOperand(0), N020.getOperand(1),
7545                                         N1);
7546         }
7547       }
7548
7549       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7550       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7551       // FIXME: This turns two single-precision and one double-precision
7552       // operation into two double-precision operations, which might not be
7553       // interesting for all targets, especially GPUs.
7554       auto FoldFAddFPExtFMAFMul = [&] (
7555           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7556         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7557                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7558                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7559                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7560                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7561                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7562                                        Z));
7563       };
7564       if (N0.getOpcode() == ISD::FP_EXTEND) {
7565         SDValue N00 = N0.getOperand(0);
7566         if (N00.getOpcode() == PreferredFusedOpcode) {
7567           SDValue N002 = N00.getOperand(2);
7568           if (N002.getOpcode() == ISD::FMUL)
7569             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7570                                         N002.getOperand(0), N002.getOperand(1),
7571                                         N1);
7572         }
7573       }
7574
7575       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7576       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7577       if (N1.getOpcode() == PreferredFusedOpcode) {
7578         SDValue N12 = N1.getOperand(2);
7579         if (N12.getOpcode() == ISD::FP_EXTEND) {
7580           SDValue N120 = N12.getOperand(0);
7581           if (N120.getOpcode() == ISD::FMUL)
7582             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7583                                         N120.getOperand(0), N120.getOperand(1),
7584                                         N0);
7585         }
7586       }
7587
7588       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7589       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7590       // FIXME: This turns two single-precision and one double-precision
7591       // operation into two double-precision operations, which might not be
7592       // interesting for all targets, especially GPUs.
7593       if (N1.getOpcode() == ISD::FP_EXTEND) {
7594         SDValue N10 = N1.getOperand(0);
7595         if (N10.getOpcode() == PreferredFusedOpcode) {
7596           SDValue N102 = N10.getOperand(2);
7597           if (N102.getOpcode() == ISD::FMUL)
7598             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7599                                         N102.getOperand(0), N102.getOperand(1),
7600                                         N0);
7601         }
7602       }
7603     }
7604   }
7605
7606   return SDValue();
7607 }
7608
7609 /// Try to perform FMA combining on a given FSUB node.
7610 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7611   SDValue N0 = N->getOperand(0);
7612   SDValue N1 = N->getOperand(1);
7613   EVT VT = N->getValueType(0);
7614   SDLoc SL(N);
7615
7616   const TargetOptions &Options = DAG.getTarget().Options;
7617   bool AllowFusion =
7618       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7619
7620   // Floating-point multiply-add with intermediate rounding.
7621   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7622
7623   // Floating-point multiply-add without intermediate rounding.
7624   bool HasFMA =
7625       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7626       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7627
7628   // No valid opcode, do not combine.
7629   if (!HasFMAD && !HasFMA)
7630     return SDValue();
7631
7632   // Always prefer FMAD to FMA for precision.
7633   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7634   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7635   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7636
7637   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7638   if (N0.getOpcode() == ISD::FMUL &&
7639       (Aggressive || N0->hasOneUse())) {
7640     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7641                        N0.getOperand(0), N0.getOperand(1),
7642                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7643   }
7644
7645   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7646   // Note: Commutes FSUB operands.
7647   if (N1.getOpcode() == ISD::FMUL &&
7648       (Aggressive || N1->hasOneUse()))
7649     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7650                        DAG.getNode(ISD::FNEG, SL, VT,
7651                                    N1.getOperand(0)),
7652                        N1.getOperand(1), N0);
7653
7654   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7655   if (N0.getOpcode() == ISD::FNEG &&
7656       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7657       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7658     SDValue N00 = N0.getOperand(0).getOperand(0);
7659     SDValue N01 = N0.getOperand(0).getOperand(1);
7660     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7661                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7662                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7663   }
7664
7665   // Look through FP_EXTEND nodes to do more combining.
7666   if (AllowFusion && LookThroughFPExt) {
7667     // fold (fsub (fpext (fmul x, y)), z)
7668     //   -> (fma (fpext x), (fpext y), (fneg z))
7669     if (N0.getOpcode() == ISD::FP_EXTEND) {
7670       SDValue N00 = N0.getOperand(0);
7671       if (N00.getOpcode() == ISD::FMUL)
7672         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7673                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7674                                        N00.getOperand(0)),
7675                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7676                                        N00.getOperand(1)),
7677                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7678     }
7679
7680     // fold (fsub x, (fpext (fmul y, z)))
7681     //   -> (fma (fneg (fpext y)), (fpext z), x)
7682     // Note: Commutes FSUB operands.
7683     if (N1.getOpcode() == ISD::FP_EXTEND) {
7684       SDValue N10 = N1.getOperand(0);
7685       if (N10.getOpcode() == ISD::FMUL)
7686         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7687                            DAG.getNode(ISD::FNEG, SL, VT,
7688                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7689                                                    N10.getOperand(0))),
7690                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7691                                        N10.getOperand(1)),
7692                            N0);
7693     }
7694
7695     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7696     //   -> (fneg (fma (fpext x), (fpext y), z))
7697     // Note: This could be removed with appropriate canonicalization of the
7698     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7699     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7700     // from implementing the canonicalization in visitFSUB.
7701     if (N0.getOpcode() == ISD::FP_EXTEND) {
7702       SDValue N00 = N0.getOperand(0);
7703       if (N00.getOpcode() == ISD::FNEG) {
7704         SDValue N000 = N00.getOperand(0);
7705         if (N000.getOpcode() == ISD::FMUL) {
7706           return DAG.getNode(ISD::FNEG, SL, VT,
7707                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7708                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7709                                                      N000.getOperand(0)),
7710                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7711                                                      N000.getOperand(1)),
7712                                          N1));
7713         }
7714       }
7715     }
7716
7717     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7718     //   -> (fneg (fma (fpext x)), (fpext y), z)
7719     // Note: This could be removed with appropriate canonicalization of the
7720     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7721     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7722     // from implementing the canonicalization in visitFSUB.
7723     if (N0.getOpcode() == ISD::FNEG) {
7724       SDValue N00 = N0.getOperand(0);
7725       if (N00.getOpcode() == ISD::FP_EXTEND) {
7726         SDValue N000 = N00.getOperand(0);
7727         if (N000.getOpcode() == ISD::FMUL) {
7728           return DAG.getNode(ISD::FNEG, SL, VT,
7729                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7730                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7731                                                      N000.getOperand(0)),
7732                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7733                                                      N000.getOperand(1)),
7734                                          N1));
7735         }
7736       }
7737     }
7738
7739   }
7740
7741   // More folding opportunities when target permits.
7742   if ((AllowFusion || HasFMAD) && Aggressive) {
7743     // fold (fsub (fma x, y, (fmul u, v)), z)
7744     //   -> (fma x, y (fma u, v, (fneg z)))
7745     if (N0.getOpcode() == PreferredFusedOpcode &&
7746         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7747       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7748                          N0.getOperand(0), N0.getOperand(1),
7749                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7750                                      N0.getOperand(2).getOperand(0),
7751                                      N0.getOperand(2).getOperand(1),
7752                                      DAG.getNode(ISD::FNEG, SL, VT,
7753                                                  N1)));
7754     }
7755
7756     // fold (fsub x, (fma y, z, (fmul u, v)))
7757     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7758     if (N1.getOpcode() == PreferredFusedOpcode &&
7759         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7760       SDValue N20 = N1.getOperand(2).getOperand(0);
7761       SDValue N21 = N1.getOperand(2).getOperand(1);
7762       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7763                          DAG.getNode(ISD::FNEG, SL, VT,
7764                                      N1.getOperand(0)),
7765                          N1.getOperand(1),
7766                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7767                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7768
7769                                      N21, N0));
7770     }
7771
7772     if (AllowFusion && LookThroughFPExt) {
7773       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7774       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7775       if (N0.getOpcode() == PreferredFusedOpcode) {
7776         SDValue N02 = N0.getOperand(2);
7777         if (N02.getOpcode() == ISD::FP_EXTEND) {
7778           SDValue N020 = N02.getOperand(0);
7779           if (N020.getOpcode() == ISD::FMUL)
7780             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7781                                N0.getOperand(0), N0.getOperand(1),
7782                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7783                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7784                                                        N020.getOperand(0)),
7785                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7786                                                        N020.getOperand(1)),
7787                                            DAG.getNode(ISD::FNEG, SL, VT,
7788                                                        N1)));
7789         }
7790       }
7791
7792       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7793       //   -> (fma (fpext x), (fpext y),
7794       //           (fma (fpext u), (fpext v), (fneg z)))
7795       // FIXME: This turns two single-precision and one double-precision
7796       // operation into two double-precision operations, which might not be
7797       // interesting for all targets, especially GPUs.
7798       if (N0.getOpcode() == ISD::FP_EXTEND) {
7799         SDValue N00 = N0.getOperand(0);
7800         if (N00.getOpcode() == PreferredFusedOpcode) {
7801           SDValue N002 = N00.getOperand(2);
7802           if (N002.getOpcode() == ISD::FMUL)
7803             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7804                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7805                                            N00.getOperand(0)),
7806                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7807                                            N00.getOperand(1)),
7808                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7809                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7810                                                        N002.getOperand(0)),
7811                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7812                                                        N002.getOperand(1)),
7813                                            DAG.getNode(ISD::FNEG, SL, VT,
7814                                                        N1)));
7815         }
7816       }
7817
7818       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7819       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7820       if (N1.getOpcode() == PreferredFusedOpcode &&
7821         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7822         SDValue N120 = N1.getOperand(2).getOperand(0);
7823         if (N120.getOpcode() == ISD::FMUL) {
7824           SDValue N1200 = N120.getOperand(0);
7825           SDValue N1201 = N120.getOperand(1);
7826           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7827                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7828                              N1.getOperand(1),
7829                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7830                                          DAG.getNode(ISD::FNEG, SL, VT,
7831                                              DAG.getNode(ISD::FP_EXTEND, SL,
7832                                                          VT, N1200)),
7833                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7834                                                      N1201),
7835                                          N0));
7836         }
7837       }
7838
7839       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7840       //   -> (fma (fneg (fpext y)), (fpext z),
7841       //           (fma (fneg (fpext u)), (fpext v), x))
7842       // FIXME: This turns two single-precision and one double-precision
7843       // operation into two double-precision operations, which might not be
7844       // interesting for all targets, especially GPUs.
7845       if (N1.getOpcode() == ISD::FP_EXTEND &&
7846         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7847         SDValue N100 = N1.getOperand(0).getOperand(0);
7848         SDValue N101 = N1.getOperand(0).getOperand(1);
7849         SDValue N102 = N1.getOperand(0).getOperand(2);
7850         if (N102.getOpcode() == ISD::FMUL) {
7851           SDValue N1020 = N102.getOperand(0);
7852           SDValue N1021 = N102.getOperand(1);
7853           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7854                              DAG.getNode(ISD::FNEG, SL, VT,
7855                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7856                                                      N100)),
7857                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7858                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7859                                          DAG.getNode(ISD::FNEG, SL, VT,
7860                                              DAG.getNode(ISD::FP_EXTEND, SL,
7861                                                          VT, N1020)),
7862                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7863                                                      N1021),
7864                                          N0));
7865         }
7866       }
7867     }
7868   }
7869
7870   return SDValue();
7871 }
7872
7873 /// Try to perform FMA combining on a given FMUL node.
7874 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7875   SDValue N0 = N->getOperand(0);
7876   SDValue N1 = N->getOperand(1);
7877   EVT VT = N->getValueType(0);
7878   SDLoc SL(N);
7879
7880   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7881
7882   const TargetOptions &Options = DAG.getTarget().Options;
7883   bool AllowFusion =
7884       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7885
7886   // Floating-point multiply-add with intermediate rounding.
7887   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7888
7889   // Floating-point multiply-add without intermediate rounding.
7890   bool HasFMA =
7891       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7892       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7893
7894   // No valid opcode, do not combine.
7895   if (!HasFMAD && !HasFMA)
7896     return SDValue();
7897
7898   // Always prefer FMAD to FMA for precision.
7899   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7900   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7901
7902   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7903   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7904   auto FuseFADD = [&](SDValue X, SDValue Y) {
7905     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7906       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7907       if (XC1 && XC1->isExactlyValue(+1.0))
7908         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7909       if (XC1 && XC1->isExactlyValue(-1.0))
7910         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7911                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7912     }
7913     return SDValue();
7914   };
7915
7916   if (SDValue FMA = FuseFADD(N0, N1))
7917     return FMA;
7918   if (SDValue FMA = FuseFADD(N1, N0))
7919     return FMA;
7920
7921   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
7922   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
7923   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
7924   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
7925   auto FuseFSUB = [&](SDValue X, SDValue Y) {
7926     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
7927       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
7928       if (XC0 && XC0->isExactlyValue(+1.0))
7929         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7930                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7931                            Y);
7932       if (XC0 && XC0->isExactlyValue(-1.0))
7933         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7934                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7935                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7936
7937       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7938       if (XC1 && XC1->isExactlyValue(+1.0))
7939         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7940                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7941       if (XC1 && XC1->isExactlyValue(-1.0))
7942         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7943     }
7944     return SDValue();
7945   };
7946
7947   if (SDValue FMA = FuseFSUB(N0, N1))
7948     return FMA;
7949   if (SDValue FMA = FuseFSUB(N1, N0))
7950     return FMA;
7951
7952   return SDValue();
7953 }
7954
7955 SDValue DAGCombiner::visitFADD(SDNode *N) {
7956   SDValue N0 = N->getOperand(0);
7957   SDValue N1 = N->getOperand(1);
7958   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
7959   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
7960   EVT VT = N->getValueType(0);
7961   SDLoc DL(N);
7962   const TargetOptions &Options = DAG.getTarget().Options;
7963   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
7964
7965   // fold vector ops
7966   if (VT.isVector())
7967     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7968       return FoldedVOp;
7969
7970   // fold (fadd c1, c2) -> c1 + c2
7971   if (N0CFP && N1CFP)
7972     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
7973
7974   // canonicalize constant to RHS
7975   if (N0CFP && !N1CFP)
7976     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
7977
7978   // fold (fadd A, (fneg B)) -> (fsub A, B)
7979   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7980       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7981     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7982                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
7983
7984   // fold (fadd (fneg A), B) -> (fsub B, A)
7985   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7986       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7987     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7988                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
7989
7990   // If 'unsafe math' is enabled, fold lots of things.
7991   if (Options.UnsafeFPMath) {
7992     // No FP constant should be created after legalization as Instruction
7993     // Selection pass has a hard time dealing with FP constants.
7994     bool AllowNewConst = (Level < AfterLegalizeDAG);
7995
7996     // fold (fadd A, 0) -> A
7997     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
7998       if (N1C->isZero())
7999         return N0;
8000
8001     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8002     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8003         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8004       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8005                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8006                                      Flags),
8007                          Flags);
8008
8009     // If allowed, fold (fadd (fneg x), x) -> 0.0
8010     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8011       return DAG.getConstantFP(0.0, DL, VT);
8012
8013     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8014     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8015       return DAG.getConstantFP(0.0, DL, VT);
8016
8017     // We can fold chains of FADD's of the same value into multiplications.
8018     // This transform is not safe in general because we are reducing the number
8019     // of rounding steps.
8020     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8021       if (N0.getOpcode() == ISD::FMUL) {
8022         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8023         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8024
8025         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8026         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8027           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8028                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8029           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8030         }
8031
8032         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8033         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8034             N1.getOperand(0) == N1.getOperand(1) &&
8035             N0.getOperand(0) == N1.getOperand(0)) {
8036           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8037                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8038           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8039         }
8040       }
8041
8042       if (N1.getOpcode() == ISD::FMUL) {
8043         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8044         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8045
8046         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8047         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8048           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8049                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8050           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8051         }
8052
8053         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8054         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8055             N0.getOperand(0) == N0.getOperand(1) &&
8056             N1.getOperand(0) == N0.getOperand(0)) {
8057           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8058                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8059           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8060         }
8061       }
8062
8063       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8064         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8065         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8066         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8067             (N0.getOperand(0) == N1)) {
8068           return DAG.getNode(ISD::FMUL, DL, VT,
8069                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8070         }
8071       }
8072
8073       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8074         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8075         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8076         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8077             N1.getOperand(0) == N0) {
8078           return DAG.getNode(ISD::FMUL, DL, VT,
8079                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8080         }
8081       }
8082
8083       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8084       if (AllowNewConst &&
8085           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8086           N0.getOperand(0) == N0.getOperand(1) &&
8087           N1.getOperand(0) == N1.getOperand(1) &&
8088           N0.getOperand(0) == N1.getOperand(0)) {
8089         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8090                            DAG.getConstantFP(4.0, DL, VT), Flags);
8091       }
8092     }
8093   } // enable-unsafe-fp-math
8094
8095   // FADD -> FMA combines:
8096   if (SDValue Fused = visitFADDForFMACombine(N)) {
8097     AddToWorklist(Fused.getNode());
8098     return Fused;
8099   }
8100
8101   return SDValue();
8102 }
8103
8104 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8105   SDValue N0 = N->getOperand(0);
8106   SDValue N1 = N->getOperand(1);
8107   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8108   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8109   EVT VT = N->getValueType(0);
8110   SDLoc dl(N);
8111   const TargetOptions &Options = DAG.getTarget().Options;
8112   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8113
8114   // fold vector ops
8115   if (VT.isVector())
8116     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8117       return FoldedVOp;
8118
8119   // fold (fsub c1, c2) -> c1-c2
8120   if (N0CFP && N1CFP)
8121     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8122
8123   // fold (fsub A, (fneg B)) -> (fadd A, B)
8124   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8125     return DAG.getNode(ISD::FADD, dl, VT, N0,
8126                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8127
8128   // If 'unsafe math' is enabled, fold lots of things.
8129   if (Options.UnsafeFPMath) {
8130     // (fsub A, 0) -> A
8131     if (N1CFP && N1CFP->isZero())
8132       return N0;
8133
8134     // (fsub 0, B) -> -B
8135     if (N0CFP && N0CFP->isZero()) {
8136       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8137         return GetNegatedExpression(N1, DAG, LegalOperations);
8138       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8139         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8140     }
8141
8142     // (fsub x, x) -> 0.0
8143     if (N0 == N1)
8144       return DAG.getConstantFP(0.0f, dl, VT);
8145
8146     // (fsub x, (fadd x, y)) -> (fneg y)
8147     // (fsub x, (fadd y, x)) -> (fneg y)
8148     if (N1.getOpcode() == ISD::FADD) {
8149       SDValue N10 = N1->getOperand(0);
8150       SDValue N11 = N1->getOperand(1);
8151
8152       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8153         return GetNegatedExpression(N11, DAG, LegalOperations);
8154
8155       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8156         return GetNegatedExpression(N10, DAG, LegalOperations);
8157     }
8158   }
8159
8160   // FSUB -> FMA combines:
8161   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8162     AddToWorklist(Fused.getNode());
8163     return Fused;
8164   }
8165
8166   return SDValue();
8167 }
8168
8169 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8170   SDValue N0 = N->getOperand(0);
8171   SDValue N1 = N->getOperand(1);
8172   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8173   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8174   EVT VT = N->getValueType(0);
8175   SDLoc DL(N);
8176   const TargetOptions &Options = DAG.getTarget().Options;
8177   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8178
8179   // fold vector ops
8180   if (VT.isVector()) {
8181     // This just handles C1 * C2 for vectors. Other vector folds are below.
8182     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8183       return FoldedVOp;
8184   }
8185
8186   // fold (fmul c1, c2) -> c1*c2
8187   if (N0CFP && N1CFP)
8188     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8189
8190   // canonicalize constant to RHS
8191   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8192      !isConstantFPBuildVectorOrConstantFP(N1))
8193     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8194
8195   // fold (fmul A, 1.0) -> A
8196   if (N1CFP && N1CFP->isExactlyValue(1.0))
8197     return N0;
8198
8199   if (Options.UnsafeFPMath) {
8200     // fold (fmul A, 0) -> 0
8201     if (N1CFP && N1CFP->isZero())
8202       return N1;
8203
8204     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8205     if (N0.getOpcode() == ISD::FMUL) {
8206       // Fold scalars or any vector constants (not just splats).
8207       // This fold is done in general by InstCombine, but extra fmul insts
8208       // may have been generated during lowering.
8209       SDValue N00 = N0.getOperand(0);
8210       SDValue N01 = N0.getOperand(1);
8211       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8212       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8213       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8214
8215       // Check 1: Make sure that the first operand of the inner multiply is NOT
8216       // a constant. Otherwise, we may induce infinite looping.
8217       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8218         // Check 2: Make sure that the second operand of the inner multiply and
8219         // the second operand of the outer multiply are constants.
8220         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8221             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8222           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8223           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8224         }
8225       }
8226     }
8227
8228     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8229     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8230     // during an early run of DAGCombiner can prevent folding with fmuls
8231     // inserted during lowering.
8232     if (N0.getOpcode() == ISD::FADD &&
8233         (N0.getOperand(0) == N0.getOperand(1)) &&
8234         N0.hasOneUse()) {
8235       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8236       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8237       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8238     }
8239   }
8240
8241   // fold (fmul X, 2.0) -> (fadd X, X)
8242   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8243     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8244
8245   // fold (fmul X, -1.0) -> (fneg X)
8246   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8247     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8248       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8249
8250   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8251   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8252     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8253       // Both can be negated for free, check to see if at least one is cheaper
8254       // negated.
8255       if (LHSNeg == 2 || RHSNeg == 2)
8256         return DAG.getNode(ISD::FMUL, DL, VT,
8257                            GetNegatedExpression(N0, DAG, LegalOperations),
8258                            GetNegatedExpression(N1, DAG, LegalOperations),
8259                            Flags);
8260     }
8261   }
8262
8263   // FMUL -> FMA combines:
8264   if (SDValue Fused = visitFMULForFMACombine(N)) {
8265     AddToWorklist(Fused.getNode());
8266     return Fused;
8267   }
8268
8269   return SDValue();
8270 }
8271
8272 SDValue DAGCombiner::visitFMA(SDNode *N) {
8273   SDValue N0 = N->getOperand(0);
8274   SDValue N1 = N->getOperand(1);
8275   SDValue N2 = N->getOperand(2);
8276   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8277   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8278   EVT VT = N->getValueType(0);
8279   SDLoc dl(N);
8280   const TargetOptions &Options = DAG.getTarget().Options;
8281
8282   // Constant fold FMA.
8283   if (isa<ConstantFPSDNode>(N0) &&
8284       isa<ConstantFPSDNode>(N1) &&
8285       isa<ConstantFPSDNode>(N2)) {
8286     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8287   }
8288
8289   if (Options.UnsafeFPMath) {
8290     if (N0CFP && N0CFP->isZero())
8291       return N2;
8292     if (N1CFP && N1CFP->isZero())
8293       return N2;
8294   }
8295   // TODO: The FMA node should have flags that propagate to these nodes.
8296   if (N0CFP && N0CFP->isExactlyValue(1.0))
8297     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8298   if (N1CFP && N1CFP->isExactlyValue(1.0))
8299     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8300
8301   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8302   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8303      !isConstantFPBuildVectorOrConstantFP(N1))
8304     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8305
8306   // TODO: FMA nodes should have flags that propagate to the created nodes.
8307   // For now, create a Flags object for use with all unsafe math transforms.
8308   SDNodeFlags Flags;
8309   Flags.setUnsafeAlgebra(true);
8310
8311   if (Options.UnsafeFPMath) {
8312     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8313     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8314         isConstantFPBuildVectorOrConstantFP(N1) &&
8315         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8316       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8317                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8318                                      &Flags), &Flags);
8319     }
8320
8321     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8322     if (N0.getOpcode() == ISD::FMUL &&
8323         isConstantFPBuildVectorOrConstantFP(N1) &&
8324         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8325       return DAG.getNode(ISD::FMA, dl, VT,
8326                          N0.getOperand(0),
8327                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8328                                      &Flags),
8329                          N2);
8330     }
8331   }
8332
8333   // (fma x, 1, y) -> (fadd x, y)
8334   // (fma x, -1, y) -> (fadd (fneg x), y)
8335   if (N1CFP) {
8336     if (N1CFP->isExactlyValue(1.0))
8337       // TODO: The FMA node should have flags that propagate to this node.
8338       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8339
8340     if (N1CFP->isExactlyValue(-1.0) &&
8341         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8342       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8343       AddToWorklist(RHSNeg.getNode());
8344       // TODO: The FMA node should have flags that propagate to this node.
8345       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8346     }
8347   }
8348
8349   if (Options.UnsafeFPMath) {
8350     // (fma x, c, x) -> (fmul x, (c+1))
8351     if (N1CFP && N0 == N2) {
8352     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8353                          DAG.getNode(ISD::FADD, dl, VT,
8354                                      N1, DAG.getConstantFP(1.0, dl, VT),
8355                                      &Flags), &Flags);
8356     }
8357
8358     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8359     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8360       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8361                          DAG.getNode(ISD::FADD, dl, VT,
8362                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8363                                      &Flags), &Flags);
8364     }
8365   }
8366
8367   return SDValue();
8368 }
8369
8370 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8371 // reciprocal.
8372 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8373 // Notice that this is not always beneficial. One reason is different target
8374 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8375 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8376 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8377 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8378   if (!DAG.getTarget().Options.UnsafeFPMath)
8379     return SDValue();
8380
8381   // Skip if current node is a reciprocal.
8382   SDValue N0 = N->getOperand(0);
8383   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8384   if (N0CFP && N0CFP->isExactlyValue(1.0))
8385     return SDValue();
8386
8387   // Exit early if the target does not want this transform or if there can't
8388   // possibly be enough uses of the divisor to make the transform worthwhile.
8389   SDValue N1 = N->getOperand(1);
8390   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8391   if (!MinUses || N1->use_size() < MinUses)
8392     return SDValue();
8393
8394   // Find all FDIV users of the same divisor.
8395   // Use a set because duplicates may be present in the user list.
8396   SetVector<SDNode *> Users;
8397   for (auto *U : N1->uses())
8398     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8399       Users.insert(U);
8400
8401   // Now that we have the actual number of divisor uses, make sure it meets
8402   // the minimum threshold specified by the target.
8403   if (Users.size() < MinUses)
8404     return SDValue();
8405
8406   EVT VT = N->getValueType(0);
8407   SDLoc DL(N);
8408   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8409   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8410   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8411
8412   // Dividend / Divisor -> Dividend * Reciprocal
8413   for (auto *U : Users) {
8414     SDValue Dividend = U->getOperand(0);
8415     if (Dividend != FPOne) {
8416       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8417                                     Reciprocal, Flags);
8418       CombineTo(U, NewNode);
8419     } else if (U != Reciprocal.getNode()) {
8420       // In the absence of fast-math-flags, this user node is always the
8421       // same node as Reciprocal, but with FMF they may be different nodes.
8422       CombineTo(U, Reciprocal);
8423     }
8424   }
8425   return SDValue(N, 0);  // N was replaced.
8426 }
8427
8428 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8429   SDValue N0 = N->getOperand(0);
8430   SDValue N1 = N->getOperand(1);
8431   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8432   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8433   EVT VT = N->getValueType(0);
8434   SDLoc DL(N);
8435   const TargetOptions &Options = DAG.getTarget().Options;
8436   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8437
8438   // fold vector ops
8439   if (VT.isVector())
8440     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8441       return FoldedVOp;
8442
8443   // fold (fdiv c1, c2) -> c1/c2
8444   if (N0CFP && N1CFP)
8445     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8446
8447   if (Options.UnsafeFPMath) {
8448     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8449     if (N1CFP) {
8450       // Compute the reciprocal 1.0 / c2.
8451       APFloat N1APF = N1CFP->getValueAPF();
8452       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8453       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8454       // Only do the transform if the reciprocal is a legal fp immediate that
8455       // isn't too nasty (eg NaN, denormal, ...).
8456       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8457           (!LegalOperations ||
8458            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8459            // backend)... we should handle this gracefully after Legalize.
8460            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8461            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8462            TLI.isFPImmLegal(Recip, VT)))
8463         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8464                            DAG.getConstantFP(Recip, DL, VT), Flags);
8465     }
8466
8467     // If this FDIV is part of a reciprocal square root, it may be folded
8468     // into a target-specific square root estimate instruction.
8469     if (N1.getOpcode() == ISD::FSQRT) {
8470       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8471         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8472       }
8473     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8474                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8475       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8476                                           Flags)) {
8477         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8478         AddToWorklist(RV.getNode());
8479         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8480       }
8481     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8482                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8483       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8484                                           Flags)) {
8485         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8486         AddToWorklist(RV.getNode());
8487         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8488       }
8489     } else if (N1.getOpcode() == ISD::FMUL) {
8490       // Look through an FMUL. Even though this won't remove the FDIV directly,
8491       // it's still worthwhile to get rid of the FSQRT if possible.
8492       SDValue SqrtOp;
8493       SDValue OtherOp;
8494       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8495         SqrtOp = N1.getOperand(0);
8496         OtherOp = N1.getOperand(1);
8497       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8498         SqrtOp = N1.getOperand(1);
8499         OtherOp = N1.getOperand(0);
8500       }
8501       if (SqrtOp.getNode()) {
8502         // We found a FSQRT, so try to make this fold:
8503         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8504         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8505           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8506           AddToWorklist(RV.getNode());
8507           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8508         }
8509       }
8510     }
8511
8512     // Fold into a reciprocal estimate and multiply instead of a real divide.
8513     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8514       AddToWorklist(RV.getNode());
8515       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8516     }
8517   }
8518
8519   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8520   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8521     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8522       // Both can be negated for free, check to see if at least one is cheaper
8523       // negated.
8524       if (LHSNeg == 2 || RHSNeg == 2)
8525         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8526                            GetNegatedExpression(N0, DAG, LegalOperations),
8527                            GetNegatedExpression(N1, DAG, LegalOperations),
8528                            Flags);
8529     }
8530   }
8531
8532   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8533     return CombineRepeatedDivisors;
8534
8535   return SDValue();
8536 }
8537
8538 SDValue DAGCombiner::visitFREM(SDNode *N) {
8539   SDValue N0 = N->getOperand(0);
8540   SDValue N1 = N->getOperand(1);
8541   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8542   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8543   EVT VT = N->getValueType(0);
8544
8545   // fold (frem c1, c2) -> fmod(c1,c2)
8546   if (N0CFP && N1CFP)
8547     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8548                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8549
8550   return SDValue();
8551 }
8552
8553 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8554   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8555     return SDValue();
8556
8557   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8558   // For now, create a Flags object for use with all unsafe math transforms.
8559   SDNodeFlags Flags;
8560   Flags.setUnsafeAlgebra(true);
8561
8562   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8563   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8564   if (!RV)
8565     return SDValue();
8566
8567   EVT VT = RV.getValueType();
8568   SDLoc DL(N);
8569   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8570   AddToWorklist(RV.getNode());
8571
8572   // Unfortunately, RV is now NaN if the input was exactly 0.
8573   // Select out this case and force the answer to 0.
8574   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8575   EVT CCVT = getSetCCResultType(VT);
8576   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8577   AddToWorklist(ZeroCmp.getNode());
8578   AddToWorklist(RV.getNode());
8579
8580   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8581                      ZeroCmp, Zero, RV);
8582 }
8583
8584 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8585   SDValue N0 = N->getOperand(0);
8586   SDValue N1 = N->getOperand(1);
8587   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8588   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8589   EVT VT = N->getValueType(0);
8590
8591   if (N0CFP && N1CFP)  // Constant fold
8592     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8593
8594   if (N1CFP) {
8595     const APFloat& V = N1CFP->getValueAPF();
8596     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8597     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8598     if (!V.isNegative()) {
8599       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8600         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8601     } else {
8602       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8603         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8604                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8605     }
8606   }
8607
8608   // copysign(fabs(x), y) -> copysign(x, y)
8609   // copysign(fneg(x), y) -> copysign(x, y)
8610   // copysign(copysign(x,z), y) -> copysign(x, y)
8611   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8612       N0.getOpcode() == ISD::FCOPYSIGN)
8613     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8614                        N0.getOperand(0), N1);
8615
8616   // copysign(x, abs(y)) -> abs(x)
8617   if (N1.getOpcode() == ISD::FABS)
8618     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8619
8620   // copysign(x, copysign(y,z)) -> copysign(x, z)
8621   if (N1.getOpcode() == ISD::FCOPYSIGN)
8622     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8623                        N0, N1.getOperand(1));
8624
8625   // copysign(x, fp_extend(y)) -> copysign(x, y)
8626   // copysign(x, fp_round(y)) -> copysign(x, y)
8627   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8628     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8629                        N0, N1.getOperand(0));
8630
8631   return SDValue();
8632 }
8633
8634 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8635   SDValue N0 = N->getOperand(0);
8636   EVT VT = N->getValueType(0);
8637   EVT OpVT = N0.getValueType();
8638
8639   // fold (sint_to_fp c1) -> c1fp
8640   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8641       // ...but only if the target supports immediate floating-point values
8642       (!LegalOperations ||
8643        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8644     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8645
8646   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8647   // but UINT_TO_FP is legal on this target, try to convert.
8648   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8649       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8650     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8651     if (DAG.SignBitIsZero(N0))
8652       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8653   }
8654
8655   // The next optimizations are desirable only if SELECT_CC can be lowered.
8656   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8657     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8658     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8659         !VT.isVector() &&
8660         (!LegalOperations ||
8661          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8662       SDLoc DL(N);
8663       SDValue Ops[] =
8664         { N0.getOperand(0), N0.getOperand(1),
8665           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8666           N0.getOperand(2) };
8667       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8668     }
8669
8670     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8671     //      (select_cc x, y, 1.0, 0.0,, cc)
8672     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8673         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8674         (!LegalOperations ||
8675          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8676       SDLoc DL(N);
8677       SDValue Ops[] =
8678         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8679           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8680           N0.getOperand(0).getOperand(2) };
8681       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8682     }
8683   }
8684
8685   return SDValue();
8686 }
8687
8688 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8689   SDValue N0 = N->getOperand(0);
8690   EVT VT = N->getValueType(0);
8691   EVT OpVT = N0.getValueType();
8692
8693   // fold (uint_to_fp c1) -> c1fp
8694   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8695       // ...but only if the target supports immediate floating-point values
8696       (!LegalOperations ||
8697        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8698     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8699
8700   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8701   // but SINT_TO_FP is legal on this target, try to convert.
8702   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8703       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8704     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8705     if (DAG.SignBitIsZero(N0))
8706       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8707   }
8708
8709   // The next optimizations are desirable only if SELECT_CC can be lowered.
8710   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8711     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8712
8713     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8714         (!LegalOperations ||
8715          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8716       SDLoc DL(N);
8717       SDValue Ops[] =
8718         { N0.getOperand(0), N0.getOperand(1),
8719           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8720           N0.getOperand(2) };
8721       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8722     }
8723   }
8724
8725   return SDValue();
8726 }
8727
8728 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8729 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8730   SDValue N0 = N->getOperand(0);
8731   EVT VT = N->getValueType(0);
8732
8733   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8734     return SDValue();
8735
8736   SDValue Src = N0.getOperand(0);
8737   EVT SrcVT = Src.getValueType();
8738   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8739   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8740
8741   // We can safely assume the conversion won't overflow the output range,
8742   // because (for example) (uint8_t)18293.f is undefined behavior.
8743
8744   // Since we can assume the conversion won't overflow, our decision as to
8745   // whether the input will fit in the float should depend on the minimum
8746   // of the input range and output range.
8747
8748   // This means this is also safe for a signed input and unsigned output, since
8749   // a negative input would lead to undefined behavior.
8750   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8751   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8752   unsigned ActualSize = std::min(InputSize, OutputSize);
8753   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8754
8755   // We can only fold away the float conversion if the input range can be
8756   // represented exactly in the float range.
8757   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8758     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8759       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8760                                                        : ISD::ZERO_EXTEND;
8761       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8762     }
8763     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8764       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8765     if (SrcVT == VT)
8766       return Src;
8767     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8768   }
8769   return SDValue();
8770 }
8771
8772 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8773   SDValue N0 = N->getOperand(0);
8774   EVT VT = N->getValueType(0);
8775
8776   // fold (fp_to_sint c1fp) -> c1
8777   if (isConstantFPBuildVectorOrConstantFP(N0))
8778     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8779
8780   return FoldIntToFPToInt(N, DAG);
8781 }
8782
8783 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8784   SDValue N0 = N->getOperand(0);
8785   EVT VT = N->getValueType(0);
8786
8787   // fold (fp_to_uint c1fp) -> c1
8788   if (isConstantFPBuildVectorOrConstantFP(N0))
8789     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8790
8791   return FoldIntToFPToInt(N, DAG);
8792 }
8793
8794 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8795   SDValue N0 = N->getOperand(0);
8796   SDValue N1 = N->getOperand(1);
8797   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8798   EVT VT = N->getValueType(0);
8799
8800   // fold (fp_round c1fp) -> c1fp
8801   if (N0CFP)
8802     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8803
8804   // fold (fp_round (fp_extend x)) -> x
8805   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8806     return N0.getOperand(0);
8807
8808   // fold (fp_round (fp_round x)) -> (fp_round x)
8809   if (N0.getOpcode() == ISD::FP_ROUND) {
8810     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8811     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8812     // If the first fp_round isn't a value preserving truncation, it might
8813     // introduce a tie in the second fp_round, that wouldn't occur in the
8814     // single-step fp_round we want to fold to.
8815     // In other words, double rounding isn't the same as rounding.
8816     // Also, this is a value preserving truncation iff both fp_round's are.
8817     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8818       SDLoc DL(N);
8819       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8820                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8821     }
8822   }
8823
8824   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8825   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8826     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8827                               N0.getOperand(0), N1);
8828     AddToWorklist(Tmp.getNode());
8829     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8830                        Tmp, N0.getOperand(1));
8831   }
8832
8833   return SDValue();
8834 }
8835
8836 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8837   SDValue N0 = N->getOperand(0);
8838   EVT VT = N->getValueType(0);
8839   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8840   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8841
8842   // fold (fp_round_inreg c1fp) -> c1fp
8843   if (N0CFP && isTypeLegal(EVT)) {
8844     SDLoc DL(N);
8845     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8846     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8847   }
8848
8849   return SDValue();
8850 }
8851
8852 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8853   SDValue N0 = N->getOperand(0);
8854   EVT VT = N->getValueType(0);
8855
8856   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8857   if (N->hasOneUse() &&
8858       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8859     return SDValue();
8860
8861   // fold (fp_extend c1fp) -> c1fp
8862   if (isConstantFPBuildVectorOrConstantFP(N0))
8863     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8864
8865   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8866   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8867       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8868     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8869
8870   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8871   // value of X.
8872   if (N0.getOpcode() == ISD::FP_ROUND
8873       && N0.getNode()->getConstantOperandVal(1) == 1) {
8874     SDValue In = N0.getOperand(0);
8875     if (In.getValueType() == VT) return In;
8876     if (VT.bitsLT(In.getValueType()))
8877       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8878                          In, N0.getOperand(1));
8879     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8880   }
8881
8882   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8883   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8884        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8885     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8886     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8887                                      LN0->getChain(),
8888                                      LN0->getBasePtr(), N0.getValueType(),
8889                                      LN0->getMemOperand());
8890     CombineTo(N, ExtLoad);
8891     CombineTo(N0.getNode(),
8892               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8893                           N0.getValueType(), ExtLoad,
8894                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8895               ExtLoad.getValue(1));
8896     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8897   }
8898
8899   return SDValue();
8900 }
8901
8902 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8903   SDValue N0 = N->getOperand(0);
8904   EVT VT = N->getValueType(0);
8905
8906   // fold (fceil c1) -> fceil(c1)
8907   if (isConstantFPBuildVectorOrConstantFP(N0))
8908     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8909
8910   return SDValue();
8911 }
8912
8913 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8914   SDValue N0 = N->getOperand(0);
8915   EVT VT = N->getValueType(0);
8916
8917   // fold (ftrunc c1) -> ftrunc(c1)
8918   if (isConstantFPBuildVectorOrConstantFP(N0))
8919     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8920
8921   return SDValue();
8922 }
8923
8924 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8925   SDValue N0 = N->getOperand(0);
8926   EVT VT = N->getValueType(0);
8927
8928   // fold (ffloor c1) -> ffloor(c1)
8929   if (isConstantFPBuildVectorOrConstantFP(N0))
8930     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8931
8932   return SDValue();
8933 }
8934
8935 // FIXME: FNEG and FABS have a lot in common; refactor.
8936 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8937   SDValue N0 = N->getOperand(0);
8938   EVT VT = N->getValueType(0);
8939
8940   // Constant fold FNEG.
8941   if (isConstantFPBuildVectorOrConstantFP(N0))
8942     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8943
8944   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8945                          &DAG.getTarget().Options))
8946     return GetNegatedExpression(N0, DAG, LegalOperations);
8947
8948   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8949   // constant pool values.
8950   if (!TLI.isFNegFree(VT) &&
8951       N0.getOpcode() == ISD::BITCAST &&
8952       N0.getNode()->hasOneUse()) {
8953     SDValue Int = N0.getOperand(0);
8954     EVT IntVT = Int.getValueType();
8955     if (IntVT.isInteger() && !IntVT.isVector()) {
8956       APInt SignMask;
8957       if (N0.getValueType().isVector()) {
8958         // For a vector, get a mask such as 0x80... per scalar element
8959         // and splat it.
8960         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8961         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8962       } else {
8963         // For a scalar, just generate 0x80...
8964         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8965       }
8966       SDLoc DL0(N0);
8967       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8968                         DAG.getConstant(SignMask, DL0, IntVT));
8969       AddToWorklist(Int.getNode());
8970       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8971     }
8972   }
8973
8974   // (fneg (fmul c, x)) -> (fmul -c, x)
8975   if (N0.getOpcode() == ISD::FMUL &&
8976       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8977     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8978     if (CFP1) {
8979       APFloat CVal = CFP1->getValueAPF();
8980       CVal.changeSign();
8981       if (Level >= AfterLegalizeDAG &&
8982           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8983            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8984         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8985                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8986                                        N0.getOperand(1)),
8987                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
8988     }
8989   }
8990
8991   return SDValue();
8992 }
8993
8994 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8995   SDValue N0 = N->getOperand(0);
8996   SDValue N1 = N->getOperand(1);
8997   EVT VT = N->getValueType(0);
8998   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8999   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9000
9001   if (N0CFP && N1CFP) {
9002     const APFloat &C0 = N0CFP->getValueAPF();
9003     const APFloat &C1 = N1CFP->getValueAPF();
9004     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9005   }
9006
9007   // Canonicalize to constant on RHS.
9008   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9009      !isConstantFPBuildVectorOrConstantFP(N1))
9010     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9011
9012   return SDValue();
9013 }
9014
9015 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9016   SDValue N0 = N->getOperand(0);
9017   SDValue N1 = N->getOperand(1);
9018   EVT VT = N->getValueType(0);
9019   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9020   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9021
9022   if (N0CFP && N1CFP) {
9023     const APFloat &C0 = N0CFP->getValueAPF();
9024     const APFloat &C1 = N1CFP->getValueAPF();
9025     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9026   }
9027
9028   // Canonicalize to constant on RHS.
9029   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9030      !isConstantFPBuildVectorOrConstantFP(N1))
9031     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9032
9033   return SDValue();
9034 }
9035
9036 SDValue DAGCombiner::visitFABS(SDNode *N) {
9037   SDValue N0 = N->getOperand(0);
9038   EVT VT = N->getValueType(0);
9039
9040   // fold (fabs c1) -> fabs(c1)
9041   if (isConstantFPBuildVectorOrConstantFP(N0))
9042     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9043
9044   // fold (fabs (fabs x)) -> (fabs x)
9045   if (N0.getOpcode() == ISD::FABS)
9046     return N->getOperand(0);
9047
9048   // fold (fabs (fneg x)) -> (fabs x)
9049   // fold (fabs (fcopysign x, y)) -> (fabs x)
9050   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9051     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9052
9053   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9054   // constant pool values.
9055   if (!TLI.isFAbsFree(VT) &&
9056       N0.getOpcode() == ISD::BITCAST &&
9057       N0.getNode()->hasOneUse()) {
9058     SDValue Int = N0.getOperand(0);
9059     EVT IntVT = Int.getValueType();
9060     if (IntVT.isInteger() && !IntVT.isVector()) {
9061       APInt SignMask;
9062       if (N0.getValueType().isVector()) {
9063         // For a vector, get a mask such as 0x7f... per scalar element
9064         // and splat it.
9065         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9066         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9067       } else {
9068         // For a scalar, just generate 0x7f...
9069         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9070       }
9071       SDLoc DL(N0);
9072       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9073                         DAG.getConstant(SignMask, DL, IntVT));
9074       AddToWorklist(Int.getNode());
9075       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9076     }
9077   }
9078
9079   return SDValue();
9080 }
9081
9082 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9083   SDValue Chain = N->getOperand(0);
9084   SDValue N1 = N->getOperand(1);
9085   SDValue N2 = N->getOperand(2);
9086
9087   // If N is a constant we could fold this into a fallthrough or unconditional
9088   // branch. However that doesn't happen very often in normal code, because
9089   // Instcombine/SimplifyCFG should have handled the available opportunities.
9090   // If we did this folding here, it would be necessary to update the
9091   // MachineBasicBlock CFG, which is awkward.
9092
9093   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9094   // on the target.
9095   if (N1.getOpcode() == ISD::SETCC &&
9096       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9097                                    N1.getOperand(0).getValueType())) {
9098     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9099                        Chain, N1.getOperand(2),
9100                        N1.getOperand(0), N1.getOperand(1), N2);
9101   }
9102
9103   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9104       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9105        (N1.getOperand(0).hasOneUse() &&
9106         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9107     SDNode *Trunc = nullptr;
9108     if (N1.getOpcode() == ISD::TRUNCATE) {
9109       // Look pass the truncate.
9110       Trunc = N1.getNode();
9111       N1 = N1.getOperand(0);
9112     }
9113
9114     // Match this pattern so that we can generate simpler code:
9115     //
9116     //   %a = ...
9117     //   %b = and i32 %a, 2
9118     //   %c = srl i32 %b, 1
9119     //   brcond i32 %c ...
9120     //
9121     // into
9122     //
9123     //   %a = ...
9124     //   %b = and i32 %a, 2
9125     //   %c = setcc eq %b, 0
9126     //   brcond %c ...
9127     //
9128     // This applies only when the AND constant value has one bit set and the
9129     // SRL constant is equal to the log2 of the AND constant. The back-end is
9130     // smart enough to convert the result into a TEST/JMP sequence.
9131     SDValue Op0 = N1.getOperand(0);
9132     SDValue Op1 = N1.getOperand(1);
9133
9134     if (Op0.getOpcode() == ISD::AND &&
9135         Op1.getOpcode() == ISD::Constant) {
9136       SDValue AndOp1 = Op0.getOperand(1);
9137
9138       if (AndOp1.getOpcode() == ISD::Constant) {
9139         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9140
9141         if (AndConst.isPowerOf2() &&
9142             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9143           SDLoc DL(N);
9144           SDValue SetCC =
9145             DAG.getSetCC(DL,
9146                          getSetCCResultType(Op0.getValueType()),
9147                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9148                          ISD::SETNE);
9149
9150           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9151                                           MVT::Other, Chain, SetCC, N2);
9152           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9153           // will convert it back to (X & C1) >> C2.
9154           CombineTo(N, NewBRCond, false);
9155           // Truncate is dead.
9156           if (Trunc)
9157             deleteAndRecombine(Trunc);
9158           // Replace the uses of SRL with SETCC
9159           WorklistRemover DeadNodes(*this);
9160           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9161           deleteAndRecombine(N1.getNode());
9162           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9163         }
9164       }
9165     }
9166
9167     if (Trunc)
9168       // Restore N1 if the above transformation doesn't match.
9169       N1 = N->getOperand(1);
9170   }
9171
9172   // Transform br(xor(x, y)) -> br(x != y)
9173   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9174   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9175     SDNode *TheXor = N1.getNode();
9176     SDValue Op0 = TheXor->getOperand(0);
9177     SDValue Op1 = TheXor->getOperand(1);
9178     if (Op0.getOpcode() == Op1.getOpcode()) {
9179       // Avoid missing important xor optimizations.
9180       if (SDValue Tmp = visitXOR(TheXor)) {
9181         if (Tmp.getNode() != TheXor) {
9182           DEBUG(dbgs() << "\nReplacing.8 ";
9183                 TheXor->dump(&DAG);
9184                 dbgs() << "\nWith: ";
9185                 Tmp.getNode()->dump(&DAG);
9186                 dbgs() << '\n');
9187           WorklistRemover DeadNodes(*this);
9188           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9189           deleteAndRecombine(TheXor);
9190           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9191                              MVT::Other, Chain, Tmp, N2);
9192         }
9193
9194         // visitXOR has changed XOR's operands or replaced the XOR completely,
9195         // bail out.
9196         return SDValue(N, 0);
9197       }
9198     }
9199
9200     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9201       bool Equal = false;
9202       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9203           Op0.getOpcode() == ISD::XOR) {
9204         TheXor = Op0.getNode();
9205         Equal = true;
9206       }
9207
9208       EVT SetCCVT = N1.getValueType();
9209       if (LegalTypes)
9210         SetCCVT = getSetCCResultType(SetCCVT);
9211       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9212                                    SetCCVT,
9213                                    Op0, Op1,
9214                                    Equal ? ISD::SETEQ : ISD::SETNE);
9215       // Replace the uses of XOR with SETCC
9216       WorklistRemover DeadNodes(*this);
9217       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9218       deleteAndRecombine(N1.getNode());
9219       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9220                          MVT::Other, Chain, SetCC, N2);
9221     }
9222   }
9223
9224   return SDValue();
9225 }
9226
9227 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9228 //
9229 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9230   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9231   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9232
9233   // If N is a constant we could fold this into a fallthrough or unconditional
9234   // branch. However that doesn't happen very often in normal code, because
9235   // Instcombine/SimplifyCFG should have handled the available opportunities.
9236   // If we did this folding here, it would be necessary to update the
9237   // MachineBasicBlock CFG, which is awkward.
9238
9239   // Use SimplifySetCC to simplify SETCC's.
9240   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9241                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9242                                false);
9243   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9244
9245   // fold to a simpler setcc
9246   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9247     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9248                        N->getOperand(0), Simp.getOperand(2),
9249                        Simp.getOperand(0), Simp.getOperand(1),
9250                        N->getOperand(4));
9251
9252   return SDValue();
9253 }
9254
9255 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9256 /// and that N may be folded in the load / store addressing mode.
9257 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9258                                     SelectionDAG &DAG,
9259                                     const TargetLowering &TLI) {
9260   EVT VT;
9261   unsigned AS;
9262
9263   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9264     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9265       return false;
9266     VT = LD->getMemoryVT();
9267     AS = LD->getAddressSpace();
9268   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9269     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9270       return false;
9271     VT = ST->getMemoryVT();
9272     AS = ST->getAddressSpace();
9273   } else
9274     return false;
9275
9276   TargetLowering::AddrMode AM;
9277   if (N->getOpcode() == ISD::ADD) {
9278     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9279     if (Offset)
9280       // [reg +/- imm]
9281       AM.BaseOffs = Offset->getSExtValue();
9282     else
9283       // [reg +/- reg]
9284       AM.Scale = 1;
9285   } else if (N->getOpcode() == ISD::SUB) {
9286     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9287     if (Offset)
9288       // [reg +/- imm]
9289       AM.BaseOffs = -Offset->getSExtValue();
9290     else
9291       // [reg +/- reg]
9292       AM.Scale = 1;
9293   } else
9294     return false;
9295
9296   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9297                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9298 }
9299
9300 /// Try turning a load/store into a pre-indexed load/store when the base
9301 /// pointer is an add or subtract and it has other uses besides the load/store.
9302 /// After the transformation, the new indexed load/store has effectively folded
9303 /// the add/subtract in and all of its other uses are redirected to the
9304 /// new load/store.
9305 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9306   if (Level < AfterLegalizeDAG)
9307     return false;
9308
9309   bool isLoad = true;
9310   SDValue Ptr;
9311   EVT VT;
9312   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9313     if (LD->isIndexed())
9314       return false;
9315     VT = LD->getMemoryVT();
9316     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9317         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9318       return false;
9319     Ptr = LD->getBasePtr();
9320   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9321     if (ST->isIndexed())
9322       return false;
9323     VT = ST->getMemoryVT();
9324     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9325         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9326       return false;
9327     Ptr = ST->getBasePtr();
9328     isLoad = false;
9329   } else {
9330     return false;
9331   }
9332
9333   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9334   // out.  There is no reason to make this a preinc/predec.
9335   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9336       Ptr.getNode()->hasOneUse())
9337     return false;
9338
9339   // Ask the target to do addressing mode selection.
9340   SDValue BasePtr;
9341   SDValue Offset;
9342   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9343   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9344     return false;
9345
9346   // Backends without true r+i pre-indexed forms may need to pass a
9347   // constant base with a variable offset so that constant coercion
9348   // will work with the patterns in canonical form.
9349   bool Swapped = false;
9350   if (isa<ConstantSDNode>(BasePtr)) {
9351     std::swap(BasePtr, Offset);
9352     Swapped = true;
9353   }
9354
9355   // Don't create a indexed load / store with zero offset.
9356   if (isNullConstant(Offset))
9357     return false;
9358
9359   // Try turning it into a pre-indexed load / store except when:
9360   // 1) The new base ptr is a frame index.
9361   // 2) If N is a store and the new base ptr is either the same as or is a
9362   //    predecessor of the value being stored.
9363   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9364   //    that would create a cycle.
9365   // 4) All uses are load / store ops that use it as old base ptr.
9366
9367   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9368   // (plus the implicit offset) to a register to preinc anyway.
9369   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9370     return false;
9371
9372   // Check #2.
9373   if (!isLoad) {
9374     SDValue Val = cast<StoreSDNode>(N)->getValue();
9375     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9376       return false;
9377   }
9378
9379   // If the offset is a constant, there may be other adds of constants that
9380   // can be folded with this one. We should do this to avoid having to keep
9381   // a copy of the original base pointer.
9382   SmallVector<SDNode *, 16> OtherUses;
9383   if (isa<ConstantSDNode>(Offset))
9384     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9385                               UE = BasePtr.getNode()->use_end();
9386          UI != UE; ++UI) {
9387       SDUse &Use = UI.getUse();
9388       // Skip the use that is Ptr and uses of other results from BasePtr's
9389       // node (important for nodes that return multiple results).
9390       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9391         continue;
9392
9393       if (Use.getUser()->isPredecessorOf(N))
9394         continue;
9395
9396       if (Use.getUser()->getOpcode() != ISD::ADD &&
9397           Use.getUser()->getOpcode() != ISD::SUB) {
9398         OtherUses.clear();
9399         break;
9400       }
9401
9402       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9403       if (!isa<ConstantSDNode>(Op1)) {
9404         OtherUses.clear();
9405         break;
9406       }
9407
9408       // FIXME: In some cases, we can be smarter about this.
9409       if (Op1.getValueType() != Offset.getValueType()) {
9410         OtherUses.clear();
9411         break;
9412       }
9413
9414       OtherUses.push_back(Use.getUser());
9415     }
9416
9417   if (Swapped)
9418     std::swap(BasePtr, Offset);
9419
9420   // Now check for #3 and #4.
9421   bool RealUse = false;
9422
9423   // Caches for hasPredecessorHelper
9424   SmallPtrSet<const SDNode *, 32> Visited;
9425   SmallVector<const SDNode *, 16> Worklist;
9426
9427   for (SDNode *Use : Ptr.getNode()->uses()) {
9428     if (Use == N)
9429       continue;
9430     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9431       return false;
9432
9433     // If Ptr may be folded in addressing mode of other use, then it's
9434     // not profitable to do this transformation.
9435     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9436       RealUse = true;
9437   }
9438
9439   if (!RealUse)
9440     return false;
9441
9442   SDValue Result;
9443   if (isLoad)
9444     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9445                                 BasePtr, Offset, AM);
9446   else
9447     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9448                                  BasePtr, Offset, AM);
9449   ++PreIndexedNodes;
9450   ++NodesCombined;
9451   DEBUG(dbgs() << "\nReplacing.4 ";
9452         N->dump(&DAG);
9453         dbgs() << "\nWith: ";
9454         Result.getNode()->dump(&DAG);
9455         dbgs() << '\n');
9456   WorklistRemover DeadNodes(*this);
9457   if (isLoad) {
9458     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9459     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9460   } else {
9461     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9462   }
9463
9464   // Finally, since the node is now dead, remove it from the graph.
9465   deleteAndRecombine(N);
9466
9467   if (Swapped)
9468     std::swap(BasePtr, Offset);
9469
9470   // Replace other uses of BasePtr that can be updated to use Ptr
9471   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9472     unsigned OffsetIdx = 1;
9473     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9474       OffsetIdx = 0;
9475     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9476            BasePtr.getNode() && "Expected BasePtr operand");
9477
9478     // We need to replace ptr0 in the following expression:
9479     //   x0 * offset0 + y0 * ptr0 = t0
9480     // knowing that
9481     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9482     //
9483     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9484     // indexed load/store and the expresion that needs to be re-written.
9485     //
9486     // Therefore, we have:
9487     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9488
9489     ConstantSDNode *CN =
9490       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9491     int X0, X1, Y0, Y1;
9492     APInt Offset0 = CN->getAPIntValue();
9493     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9494
9495     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9496     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9497     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9498     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9499
9500     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9501
9502     APInt CNV = Offset0;
9503     if (X0 < 0) CNV = -CNV;
9504     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9505     else CNV = CNV - Offset1;
9506
9507     SDLoc DL(OtherUses[i]);
9508
9509     // We can now generate the new expression.
9510     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9511     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9512
9513     SDValue NewUse = DAG.getNode(Opcode,
9514                                  DL,
9515                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9516     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9517     deleteAndRecombine(OtherUses[i]);
9518   }
9519
9520   // Replace the uses of Ptr with uses of the updated base value.
9521   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9522   deleteAndRecombine(Ptr.getNode());
9523
9524   return true;
9525 }
9526
9527 /// Try to combine a load/store with a add/sub of the base pointer node into a
9528 /// post-indexed load/store. The transformation folded the add/subtract into the
9529 /// new indexed load/store effectively and all of its uses are redirected to the
9530 /// new load/store.
9531 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9532   if (Level < AfterLegalizeDAG)
9533     return false;
9534
9535   bool isLoad = true;
9536   SDValue Ptr;
9537   EVT VT;
9538   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9539     if (LD->isIndexed())
9540       return false;
9541     VT = LD->getMemoryVT();
9542     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9543         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9544       return false;
9545     Ptr = LD->getBasePtr();
9546   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9547     if (ST->isIndexed())
9548       return false;
9549     VT = ST->getMemoryVT();
9550     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9551         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9552       return false;
9553     Ptr = ST->getBasePtr();
9554     isLoad = false;
9555   } else {
9556     return false;
9557   }
9558
9559   if (Ptr.getNode()->hasOneUse())
9560     return false;
9561
9562   for (SDNode *Op : Ptr.getNode()->uses()) {
9563     if (Op == N ||
9564         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9565       continue;
9566
9567     SDValue BasePtr;
9568     SDValue Offset;
9569     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9570     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9571       // Don't create a indexed load / store with zero offset.
9572       if (isNullConstant(Offset))
9573         continue;
9574
9575       // Try turning it into a post-indexed load / store except when
9576       // 1) All uses are load / store ops that use it as base ptr (and
9577       //    it may be folded as addressing mmode).
9578       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9579       //    nor a successor of N. Otherwise, if Op is folded that would
9580       //    create a cycle.
9581
9582       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9583         continue;
9584
9585       // Check for #1.
9586       bool TryNext = false;
9587       for (SDNode *Use : BasePtr.getNode()->uses()) {
9588         if (Use == Ptr.getNode())
9589           continue;
9590
9591         // If all the uses are load / store addresses, then don't do the
9592         // transformation.
9593         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9594           bool RealUse = false;
9595           for (SDNode *UseUse : Use->uses()) {
9596             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9597               RealUse = true;
9598           }
9599
9600           if (!RealUse) {
9601             TryNext = true;
9602             break;
9603           }
9604         }
9605       }
9606
9607       if (TryNext)
9608         continue;
9609
9610       // Check for #2
9611       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9612         SDValue Result = isLoad
9613           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9614                                BasePtr, Offset, AM)
9615           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9616                                 BasePtr, Offset, AM);
9617         ++PostIndexedNodes;
9618         ++NodesCombined;
9619         DEBUG(dbgs() << "\nReplacing.5 ";
9620               N->dump(&DAG);
9621               dbgs() << "\nWith: ";
9622               Result.getNode()->dump(&DAG);
9623               dbgs() << '\n');
9624         WorklistRemover DeadNodes(*this);
9625         if (isLoad) {
9626           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9627           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9628         } else {
9629           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9630         }
9631
9632         // Finally, since the node is now dead, remove it from the graph.
9633         deleteAndRecombine(N);
9634
9635         // Replace the uses of Use with uses of the updated base value.
9636         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9637                                       Result.getValue(isLoad ? 1 : 0));
9638         deleteAndRecombine(Op);
9639         return true;
9640       }
9641     }
9642   }
9643
9644   return false;
9645 }
9646
9647 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9648 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9649   ISD::MemIndexedMode AM = LD->getAddressingMode();
9650   assert(AM != ISD::UNINDEXED);
9651   SDValue BP = LD->getOperand(1);
9652   SDValue Inc = LD->getOperand(2);
9653
9654   // Some backends use TargetConstants for load offsets, but don't expect
9655   // TargetConstants in general ADD nodes. We can convert these constants into
9656   // regular Constants (if the constant is not opaque).
9657   assert((Inc.getOpcode() != ISD::TargetConstant ||
9658           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9659          "Cannot split out indexing using opaque target constants");
9660   if (Inc.getOpcode() == ISD::TargetConstant) {
9661     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9662     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9663                           ConstInc->getValueType(0));
9664   }
9665
9666   unsigned Opc =
9667       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9668   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9669 }
9670
9671 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9672   LoadSDNode *LD  = cast<LoadSDNode>(N);
9673   SDValue Chain = LD->getChain();
9674   SDValue Ptr   = LD->getBasePtr();
9675
9676   // If load is not volatile and there are no uses of the loaded value (and
9677   // the updated indexed value in case of indexed loads), change uses of the
9678   // chain value into uses of the chain input (i.e. delete the dead load).
9679   if (!LD->isVolatile()) {
9680     if (N->getValueType(1) == MVT::Other) {
9681       // Unindexed loads.
9682       if (!N->hasAnyUseOfValue(0)) {
9683         // It's not safe to use the two value CombineTo variant here. e.g.
9684         // v1, chain2 = load chain1, loc
9685         // v2, chain3 = load chain2, loc
9686         // v3         = add v2, c
9687         // Now we replace use of chain2 with chain1.  This makes the second load
9688         // isomorphic to the one we are deleting, and thus makes this load live.
9689         DEBUG(dbgs() << "\nReplacing.6 ";
9690               N->dump(&DAG);
9691               dbgs() << "\nWith chain: ";
9692               Chain.getNode()->dump(&DAG);
9693               dbgs() << "\n");
9694         WorklistRemover DeadNodes(*this);
9695         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9696
9697         if (N->use_empty())
9698           deleteAndRecombine(N);
9699
9700         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9701       }
9702     } else {
9703       // Indexed loads.
9704       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9705
9706       // If this load has an opaque TargetConstant offset, then we cannot split
9707       // the indexing into an add/sub directly (that TargetConstant may not be
9708       // valid for a different type of node, and we cannot convert an opaque
9709       // target constant into a regular constant).
9710       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9711                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9712
9713       if (!N->hasAnyUseOfValue(0) &&
9714           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9715         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9716         SDValue Index;
9717         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9718           Index = SplitIndexingFromLoad(LD);
9719           // Try to fold the base pointer arithmetic into subsequent loads and
9720           // stores.
9721           AddUsersToWorklist(N);
9722         } else
9723           Index = DAG.getUNDEF(N->getValueType(1));
9724         DEBUG(dbgs() << "\nReplacing.7 ";
9725               N->dump(&DAG);
9726               dbgs() << "\nWith: ";
9727               Undef.getNode()->dump(&DAG);
9728               dbgs() << " and 2 other values\n");
9729         WorklistRemover DeadNodes(*this);
9730         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9731         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9732         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9733         deleteAndRecombine(N);
9734         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9735       }
9736     }
9737   }
9738
9739   // If this load is directly stored, replace the load value with the stored
9740   // value.
9741   // TODO: Handle store large -> read small portion.
9742   // TODO: Handle TRUNCSTORE/LOADEXT
9743   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9744     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9745       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9746       if (PrevST->getBasePtr() == Ptr &&
9747           PrevST->getValue().getValueType() == N->getValueType(0))
9748       return CombineTo(N, Chain.getOperand(1), Chain);
9749     }
9750   }
9751
9752   // Try to infer better alignment information than the load already has.
9753   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9754     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9755       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9756         SDValue NewLoad =
9757                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9758                               LD->getValueType(0),
9759                               Chain, Ptr, LD->getPointerInfo(),
9760                               LD->getMemoryVT(),
9761                               LD->isVolatile(), LD->isNonTemporal(),
9762                               LD->isInvariant(), Align, LD->getAAInfo());
9763         if (NewLoad.getNode() != N)
9764           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9765       }
9766     }
9767   }
9768
9769   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9770                                                   : DAG.getSubtarget().useAA();
9771 #ifndef NDEBUG
9772   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9773       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9774     UseAA = false;
9775 #endif
9776   if (UseAA && LD->isUnindexed()) {
9777     // Walk up chain skipping non-aliasing memory nodes.
9778     SDValue BetterChain = FindBetterChain(N, Chain);
9779
9780     // If there is a better chain.
9781     if (Chain != BetterChain) {
9782       SDValue ReplLoad;
9783
9784       // Replace the chain to void dependency.
9785       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9786         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9787                                BetterChain, Ptr, LD->getMemOperand());
9788       } else {
9789         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9790                                   LD->getValueType(0),
9791                                   BetterChain, Ptr, LD->getMemoryVT(),
9792                                   LD->getMemOperand());
9793       }
9794
9795       // Create token factor to keep old chain connected.
9796       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9797                                   MVT::Other, Chain, ReplLoad.getValue(1));
9798
9799       // Make sure the new and old chains are cleaned up.
9800       AddToWorklist(Token.getNode());
9801
9802       // Replace uses with load result and token factor. Don't add users
9803       // to work list.
9804       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9805     }
9806   }
9807
9808   // Try transforming N to an indexed load.
9809   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9810     return SDValue(N, 0);
9811
9812   // Try to slice up N to more direct loads if the slices are mapped to
9813   // different register banks or pairing can take place.
9814   if (SliceUpLoad(N))
9815     return SDValue(N, 0);
9816
9817   return SDValue();
9818 }
9819
9820 namespace {
9821 /// \brief Helper structure used to slice a load in smaller loads.
9822 /// Basically a slice is obtained from the following sequence:
9823 /// Origin = load Ty1, Base
9824 /// Shift = srl Ty1 Origin, CstTy Amount
9825 /// Inst = trunc Shift to Ty2
9826 ///
9827 /// Then, it will be rewriten into:
9828 /// Slice = load SliceTy, Base + SliceOffset
9829 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9830 ///
9831 /// SliceTy is deduced from the number of bits that are actually used to
9832 /// build Inst.
9833 struct LoadedSlice {
9834   /// \brief Helper structure used to compute the cost of a slice.
9835   struct Cost {
9836     /// Are we optimizing for code size.
9837     bool ForCodeSize;
9838     /// Various cost.
9839     unsigned Loads;
9840     unsigned Truncates;
9841     unsigned CrossRegisterBanksCopies;
9842     unsigned ZExts;
9843     unsigned Shift;
9844
9845     Cost(bool ForCodeSize = false)
9846         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9847           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9848
9849     /// \brief Get the cost of one isolated slice.
9850     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9851         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9852           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9853       EVT TruncType = LS.Inst->getValueType(0);
9854       EVT LoadedType = LS.getLoadedType();
9855       if (TruncType != LoadedType &&
9856           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9857         ZExts = 1;
9858     }
9859
9860     /// \brief Account for slicing gain in the current cost.
9861     /// Slicing provide a few gains like removing a shift or a
9862     /// truncate. This method allows to grow the cost of the original
9863     /// load with the gain from this slice.
9864     void addSliceGain(const LoadedSlice &LS) {
9865       // Each slice saves a truncate.
9866       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9867       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9868                               LS.Inst->getValueType(0)))
9869         ++Truncates;
9870       // If there is a shift amount, this slice gets rid of it.
9871       if (LS.Shift)
9872         ++Shift;
9873       // If this slice can merge a cross register bank copy, account for it.
9874       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9875         ++CrossRegisterBanksCopies;
9876     }
9877
9878     Cost &operator+=(const Cost &RHS) {
9879       Loads += RHS.Loads;
9880       Truncates += RHS.Truncates;
9881       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9882       ZExts += RHS.ZExts;
9883       Shift += RHS.Shift;
9884       return *this;
9885     }
9886
9887     bool operator==(const Cost &RHS) const {
9888       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9889              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9890              ZExts == RHS.ZExts && Shift == RHS.Shift;
9891     }
9892
9893     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9894
9895     bool operator<(const Cost &RHS) const {
9896       // Assume cross register banks copies are as expensive as loads.
9897       // FIXME: Do we want some more target hooks?
9898       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9899       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9900       // Unless we are optimizing for code size, consider the
9901       // expensive operation first.
9902       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9903         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9904       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9905              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9906     }
9907
9908     bool operator>(const Cost &RHS) const { return RHS < *this; }
9909
9910     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9911
9912     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9913   };
9914   // The last instruction that represent the slice. This should be a
9915   // truncate instruction.
9916   SDNode *Inst;
9917   // The original load instruction.
9918   LoadSDNode *Origin;
9919   // The right shift amount in bits from the original load.
9920   unsigned Shift;
9921   // The DAG from which Origin came from.
9922   // This is used to get some contextual information about legal types, etc.
9923   SelectionDAG *DAG;
9924
9925   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9926               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9927       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9928
9929   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9930   /// \return Result is \p BitWidth and has used bits set to 1 and
9931   ///         not used bits set to 0.
9932   APInt getUsedBits() const {
9933     // Reproduce the trunc(lshr) sequence:
9934     // - Start from the truncated value.
9935     // - Zero extend to the desired bit width.
9936     // - Shift left.
9937     assert(Origin && "No original load to compare against.");
9938     unsigned BitWidth = Origin->getValueSizeInBits(0);
9939     assert(Inst && "This slice is not bound to an instruction");
9940     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9941            "Extracted slice is bigger than the whole type!");
9942     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9943     UsedBits.setAllBits();
9944     UsedBits = UsedBits.zext(BitWidth);
9945     UsedBits <<= Shift;
9946     return UsedBits;
9947   }
9948
9949   /// \brief Get the size of the slice to be loaded in bytes.
9950   unsigned getLoadedSize() const {
9951     unsigned SliceSize = getUsedBits().countPopulation();
9952     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9953     return SliceSize / 8;
9954   }
9955
9956   /// \brief Get the type that will be loaded for this slice.
9957   /// Note: This may not be the final type for the slice.
9958   EVT getLoadedType() const {
9959     assert(DAG && "Missing context");
9960     LLVMContext &Ctxt = *DAG->getContext();
9961     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9962   }
9963
9964   /// \brief Get the alignment of the load used for this slice.
9965   unsigned getAlignment() const {
9966     unsigned Alignment = Origin->getAlignment();
9967     unsigned Offset = getOffsetFromBase();
9968     if (Offset != 0)
9969       Alignment = MinAlign(Alignment, Alignment + Offset);
9970     return Alignment;
9971   }
9972
9973   /// \brief Check if this slice can be rewritten with legal operations.
9974   bool isLegal() const {
9975     // An invalid slice is not legal.
9976     if (!Origin || !Inst || !DAG)
9977       return false;
9978
9979     // Offsets are for indexed load only, we do not handle that.
9980     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9981       return false;
9982
9983     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9984
9985     // Check that the type is legal.
9986     EVT SliceType = getLoadedType();
9987     if (!TLI.isTypeLegal(SliceType))
9988       return false;
9989
9990     // Check that the load is legal for this type.
9991     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9992       return false;
9993
9994     // Check that the offset can be computed.
9995     // 1. Check its type.
9996     EVT PtrType = Origin->getBasePtr().getValueType();
9997     if (PtrType == MVT::Untyped || PtrType.isExtended())
9998       return false;
9999
10000     // 2. Check that it fits in the immediate.
10001     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10002       return false;
10003
10004     // 3. Check that the computation is legal.
10005     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10006       return false;
10007
10008     // Check that the zext is legal if it needs one.
10009     EVT TruncateType = Inst->getValueType(0);
10010     if (TruncateType != SliceType &&
10011         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10012       return false;
10013
10014     return true;
10015   }
10016
10017   /// \brief Get the offset in bytes of this slice in the original chunk of
10018   /// bits.
10019   /// \pre DAG != nullptr.
10020   uint64_t getOffsetFromBase() const {
10021     assert(DAG && "Missing context.");
10022     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10023     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10024     uint64_t Offset = Shift / 8;
10025     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10026     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10027            "The size of the original loaded type is not a multiple of a"
10028            " byte.");
10029     // If Offset is bigger than TySizeInBytes, it means we are loading all
10030     // zeros. This should have been optimized before in the process.
10031     assert(TySizeInBytes > Offset &&
10032            "Invalid shift amount for given loaded size");
10033     if (IsBigEndian)
10034       Offset = TySizeInBytes - Offset - getLoadedSize();
10035     return Offset;
10036   }
10037
10038   /// \brief Generate the sequence of instructions to load the slice
10039   /// represented by this object and redirect the uses of this slice to
10040   /// this new sequence of instructions.
10041   /// \pre this->Inst && this->Origin are valid Instructions and this
10042   /// object passed the legal check: LoadedSlice::isLegal returned true.
10043   /// \return The last instruction of the sequence used to load the slice.
10044   SDValue loadSlice() const {
10045     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10046     const SDValue &OldBaseAddr = Origin->getBasePtr();
10047     SDValue BaseAddr = OldBaseAddr;
10048     // Get the offset in that chunk of bytes w.r.t. the endianess.
10049     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10050     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10051     if (Offset) {
10052       // BaseAddr = BaseAddr + Offset.
10053       EVT ArithType = BaseAddr.getValueType();
10054       SDLoc DL(Origin);
10055       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10056                               DAG->getConstant(Offset, DL, ArithType));
10057     }
10058
10059     // Create the type of the loaded slice according to its size.
10060     EVT SliceType = getLoadedType();
10061
10062     // Create the load for the slice.
10063     SDValue LastInst = DAG->getLoad(
10064         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10065         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10066         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10067     // If the final type is not the same as the loaded type, this means that
10068     // we have to pad with zero. Create a zero extend for that.
10069     EVT FinalType = Inst->getValueType(0);
10070     if (SliceType != FinalType)
10071       LastInst =
10072           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10073     return LastInst;
10074   }
10075
10076   /// \brief Check if this slice can be merged with an expensive cross register
10077   /// bank copy. E.g.,
10078   /// i = load i32
10079   /// f = bitcast i32 i to float
10080   bool canMergeExpensiveCrossRegisterBankCopy() const {
10081     if (!Inst || !Inst->hasOneUse())
10082       return false;
10083     SDNode *Use = *Inst->use_begin();
10084     if (Use->getOpcode() != ISD::BITCAST)
10085       return false;
10086     assert(DAG && "Missing context");
10087     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10088     EVT ResVT = Use->getValueType(0);
10089     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10090     const TargetRegisterClass *ArgRC =
10091         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10092     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10093       return false;
10094
10095     // At this point, we know that we perform a cross-register-bank copy.
10096     // Check if it is expensive.
10097     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10098     // Assume bitcasts are cheap, unless both register classes do not
10099     // explicitly share a common sub class.
10100     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10101       return false;
10102
10103     // Check if it will be merged with the load.
10104     // 1. Check the alignment constraint.
10105     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10106         ResVT.getTypeForEVT(*DAG->getContext()));
10107
10108     if (RequiredAlignment > getAlignment())
10109       return false;
10110
10111     // 2. Check that the load is a legal operation for that type.
10112     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10113       return false;
10114
10115     // 3. Check that we do not have a zext in the way.
10116     if (Inst->getValueType(0) != getLoadedType())
10117       return false;
10118
10119     return true;
10120   }
10121 };
10122 }
10123
10124 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10125 /// \p UsedBits looks like 0..0 1..1 0..0.
10126 static bool areUsedBitsDense(const APInt &UsedBits) {
10127   // If all the bits are one, this is dense!
10128   if (UsedBits.isAllOnesValue())
10129     return true;
10130
10131   // Get rid of the unused bits on the right.
10132   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10133   // Get rid of the unused bits on the left.
10134   if (NarrowedUsedBits.countLeadingZeros())
10135     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10136   // Check that the chunk of bits is completely used.
10137   return NarrowedUsedBits.isAllOnesValue();
10138 }
10139
10140 /// \brief Check whether or not \p First and \p Second are next to each other
10141 /// in memory. This means that there is no hole between the bits loaded
10142 /// by \p First and the bits loaded by \p Second.
10143 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10144                                      const LoadedSlice &Second) {
10145   assert(First.Origin == Second.Origin && First.Origin &&
10146          "Unable to match different memory origins.");
10147   APInt UsedBits = First.getUsedBits();
10148   assert((UsedBits & Second.getUsedBits()) == 0 &&
10149          "Slices are not supposed to overlap.");
10150   UsedBits |= Second.getUsedBits();
10151   return areUsedBitsDense(UsedBits);
10152 }
10153
10154 /// \brief Adjust the \p GlobalLSCost according to the target
10155 /// paring capabilities and the layout of the slices.
10156 /// \pre \p GlobalLSCost should account for at least as many loads as
10157 /// there is in the slices in \p LoadedSlices.
10158 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10159                                  LoadedSlice::Cost &GlobalLSCost) {
10160   unsigned NumberOfSlices = LoadedSlices.size();
10161   // If there is less than 2 elements, no pairing is possible.
10162   if (NumberOfSlices < 2)
10163     return;
10164
10165   // Sort the slices so that elements that are likely to be next to each
10166   // other in memory are next to each other in the list.
10167   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10168             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10169     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10170     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10171   });
10172   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10173   // First (resp. Second) is the first (resp. Second) potentially candidate
10174   // to be placed in a paired load.
10175   const LoadedSlice *First = nullptr;
10176   const LoadedSlice *Second = nullptr;
10177   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10178                 // Set the beginning of the pair.
10179                                                            First = Second) {
10180
10181     Second = &LoadedSlices[CurrSlice];
10182
10183     // If First is NULL, it means we start a new pair.
10184     // Get to the next slice.
10185     if (!First)
10186       continue;
10187
10188     EVT LoadedType = First->getLoadedType();
10189
10190     // If the types of the slices are different, we cannot pair them.
10191     if (LoadedType != Second->getLoadedType())
10192       continue;
10193
10194     // Check if the target supplies paired loads for this type.
10195     unsigned RequiredAlignment = 0;
10196     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10197       // move to the next pair, this type is hopeless.
10198       Second = nullptr;
10199       continue;
10200     }
10201     // Check if we meet the alignment requirement.
10202     if (RequiredAlignment > First->getAlignment())
10203       continue;
10204
10205     // Check that both loads are next to each other in memory.
10206     if (!areSlicesNextToEachOther(*First, *Second))
10207       continue;
10208
10209     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10210     --GlobalLSCost.Loads;
10211     // Move to the next pair.
10212     Second = nullptr;
10213   }
10214 }
10215
10216 /// \brief Check the profitability of all involved LoadedSlice.
10217 /// Currently, it is considered profitable if there is exactly two
10218 /// involved slices (1) which are (2) next to each other in memory, and
10219 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10220 ///
10221 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10222 /// the elements themselves.
10223 ///
10224 /// FIXME: When the cost model will be mature enough, we can relax
10225 /// constraints (1) and (2).
10226 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10227                                 const APInt &UsedBits, bool ForCodeSize) {
10228   unsigned NumberOfSlices = LoadedSlices.size();
10229   if (StressLoadSlicing)
10230     return NumberOfSlices > 1;
10231
10232   // Check (1).
10233   if (NumberOfSlices != 2)
10234     return false;
10235
10236   // Check (2).
10237   if (!areUsedBitsDense(UsedBits))
10238     return false;
10239
10240   // Check (3).
10241   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10242   // The original code has one big load.
10243   OrigCost.Loads = 1;
10244   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10245     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10246     // Accumulate the cost of all the slices.
10247     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10248     GlobalSlicingCost += SliceCost;
10249
10250     // Account as cost in the original configuration the gain obtained
10251     // with the current slices.
10252     OrigCost.addSliceGain(LS);
10253   }
10254
10255   // If the target supports paired load, adjust the cost accordingly.
10256   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10257   return OrigCost > GlobalSlicingCost;
10258 }
10259
10260 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10261 /// operations, split it in the various pieces being extracted.
10262 ///
10263 /// This sort of thing is introduced by SROA.
10264 /// This slicing takes care not to insert overlapping loads.
10265 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10266 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10267   if (Level < AfterLegalizeDAG)
10268     return false;
10269
10270   LoadSDNode *LD = cast<LoadSDNode>(N);
10271   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10272       !LD->getValueType(0).isInteger())
10273     return false;
10274
10275   // Keep track of already used bits to detect overlapping values.
10276   // In that case, we will just abort the transformation.
10277   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10278
10279   SmallVector<LoadedSlice, 4> LoadedSlices;
10280
10281   // Check if this load is used as several smaller chunks of bits.
10282   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10283   // of computation for each trunc.
10284   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10285        UI != UIEnd; ++UI) {
10286     // Skip the uses of the chain.
10287     if (UI.getUse().getResNo() != 0)
10288       continue;
10289
10290     SDNode *User = *UI;
10291     unsigned Shift = 0;
10292
10293     // Check if this is a trunc(lshr).
10294     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10295         isa<ConstantSDNode>(User->getOperand(1))) {
10296       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10297       User = *User->use_begin();
10298     }
10299
10300     // At this point, User is a Truncate, iff we encountered, trunc or
10301     // trunc(lshr).
10302     if (User->getOpcode() != ISD::TRUNCATE)
10303       return false;
10304
10305     // The width of the type must be a power of 2 and greater than 8-bits.
10306     // Otherwise the load cannot be represented in LLVM IR.
10307     // Moreover, if we shifted with a non-8-bits multiple, the slice
10308     // will be across several bytes. We do not support that.
10309     unsigned Width = User->getValueSizeInBits(0);
10310     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10311       return 0;
10312
10313     // Build the slice for this chain of computations.
10314     LoadedSlice LS(User, LD, Shift, &DAG);
10315     APInt CurrentUsedBits = LS.getUsedBits();
10316
10317     // Check if this slice overlaps with another.
10318     if ((CurrentUsedBits & UsedBits) != 0)
10319       return false;
10320     // Update the bits used globally.
10321     UsedBits |= CurrentUsedBits;
10322
10323     // Check if the new slice would be legal.
10324     if (!LS.isLegal())
10325       return false;
10326
10327     // Record the slice.
10328     LoadedSlices.push_back(LS);
10329   }
10330
10331   // Abort slicing if it does not seem to be profitable.
10332   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10333     return false;
10334
10335   ++SlicedLoads;
10336
10337   // Rewrite each chain to use an independent load.
10338   // By construction, each chain can be represented by a unique load.
10339
10340   // Prepare the argument for the new token factor for all the slices.
10341   SmallVector<SDValue, 8> ArgChains;
10342   for (SmallVectorImpl<LoadedSlice>::const_iterator
10343            LSIt = LoadedSlices.begin(),
10344            LSItEnd = LoadedSlices.end();
10345        LSIt != LSItEnd; ++LSIt) {
10346     SDValue SliceInst = LSIt->loadSlice();
10347     CombineTo(LSIt->Inst, SliceInst, true);
10348     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10349       SliceInst = SliceInst.getOperand(0);
10350     assert(SliceInst->getOpcode() == ISD::LOAD &&
10351            "It takes more than a zext to get to the loaded slice!!");
10352     ArgChains.push_back(SliceInst.getValue(1));
10353   }
10354
10355   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10356                               ArgChains);
10357   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10358   return true;
10359 }
10360
10361 /// Check to see if V is (and load (ptr), imm), where the load is having
10362 /// specific bytes cleared out.  If so, return the byte size being masked out
10363 /// and the shift amount.
10364 static std::pair<unsigned, unsigned>
10365 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10366   std::pair<unsigned, unsigned> Result(0, 0);
10367
10368   // Check for the structure we're looking for.
10369   if (V->getOpcode() != ISD::AND ||
10370       !isa<ConstantSDNode>(V->getOperand(1)) ||
10371       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10372     return Result;
10373
10374   // Check the chain and pointer.
10375   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10376   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10377
10378   // The store should be chained directly to the load or be an operand of a
10379   // tokenfactor.
10380   if (LD == Chain.getNode())
10381     ; // ok.
10382   else if (Chain->getOpcode() != ISD::TokenFactor)
10383     return Result; // Fail.
10384   else {
10385     bool isOk = false;
10386     for (const SDValue &ChainOp : Chain->op_values())
10387       if (ChainOp.getNode() == LD) {
10388         isOk = true;
10389         break;
10390       }
10391     if (!isOk) return Result;
10392   }
10393
10394   // This only handles simple types.
10395   if (V.getValueType() != MVT::i16 &&
10396       V.getValueType() != MVT::i32 &&
10397       V.getValueType() != MVT::i64)
10398     return Result;
10399
10400   // Check the constant mask.  Invert it so that the bits being masked out are
10401   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10402   // follow the sign bit for uniformity.
10403   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10404   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10405   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10406   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10407   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10408   if (NotMaskLZ == 64) return Result;  // All zero mask.
10409
10410   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10411   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10412     return Result;
10413
10414   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10415   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10416     NotMaskLZ -= 64-V.getValueSizeInBits();
10417
10418   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10419   switch (MaskedBytes) {
10420   case 1:
10421   case 2:
10422   case 4: break;
10423   default: return Result; // All one mask, or 5-byte mask.
10424   }
10425
10426   // Verify that the first bit starts at a multiple of mask so that the access
10427   // is aligned the same as the access width.
10428   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10429
10430   Result.first = MaskedBytes;
10431   Result.second = NotMaskTZ/8;
10432   return Result;
10433 }
10434
10435
10436 /// Check to see if IVal is something that provides a value as specified by
10437 /// MaskInfo. If so, replace the specified store with a narrower store of
10438 /// truncated IVal.
10439 static SDNode *
10440 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10441                                 SDValue IVal, StoreSDNode *St,
10442                                 DAGCombiner *DC) {
10443   unsigned NumBytes = MaskInfo.first;
10444   unsigned ByteShift = MaskInfo.second;
10445   SelectionDAG &DAG = DC->getDAG();
10446
10447   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10448   // that uses this.  If not, this is not a replacement.
10449   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10450                                   ByteShift*8, (ByteShift+NumBytes)*8);
10451   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10452
10453   // Check that it is legal on the target to do this.  It is legal if the new
10454   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10455   // legalization.
10456   MVT VT = MVT::getIntegerVT(NumBytes*8);
10457   if (!DC->isTypeLegal(VT))
10458     return nullptr;
10459
10460   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10461   // shifted by ByteShift and truncated down to NumBytes.
10462   if (ByteShift) {
10463     SDLoc DL(IVal);
10464     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10465                        DAG.getConstant(ByteShift*8, DL,
10466                                     DC->getShiftAmountTy(IVal.getValueType())));
10467   }
10468
10469   // Figure out the offset for the store and the alignment of the access.
10470   unsigned StOffset;
10471   unsigned NewAlign = St->getAlignment();
10472
10473   if (DAG.getDataLayout().isLittleEndian())
10474     StOffset = ByteShift;
10475   else
10476     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10477
10478   SDValue Ptr = St->getBasePtr();
10479   if (StOffset) {
10480     SDLoc DL(IVal);
10481     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10482                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10483     NewAlign = MinAlign(NewAlign, StOffset);
10484   }
10485
10486   // Truncate down to the new size.
10487   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10488
10489   ++OpsNarrowed;
10490   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10491                       St->getPointerInfo().getWithOffset(StOffset),
10492                       false, false, NewAlign).getNode();
10493 }
10494
10495
10496 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10497 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10498 /// narrowing the load and store if it would end up being a win for performance
10499 /// or code size.
10500 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10501   StoreSDNode *ST  = cast<StoreSDNode>(N);
10502   if (ST->isVolatile())
10503     return SDValue();
10504
10505   SDValue Chain = ST->getChain();
10506   SDValue Value = ST->getValue();
10507   SDValue Ptr   = ST->getBasePtr();
10508   EVT VT = Value.getValueType();
10509
10510   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10511     return SDValue();
10512
10513   unsigned Opc = Value.getOpcode();
10514
10515   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10516   // is a byte mask indicating a consecutive number of bytes, check to see if
10517   // Y is known to provide just those bytes.  If so, we try to replace the
10518   // load + replace + store sequence with a single (narrower) store, which makes
10519   // the load dead.
10520   if (Opc == ISD::OR) {
10521     std::pair<unsigned, unsigned> MaskedLoad;
10522     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10523     if (MaskedLoad.first)
10524       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10525                                                   Value.getOperand(1), ST,this))
10526         return SDValue(NewST, 0);
10527
10528     // Or is commutative, so try swapping X and Y.
10529     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10530     if (MaskedLoad.first)
10531       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10532                                                   Value.getOperand(0), ST,this))
10533         return SDValue(NewST, 0);
10534   }
10535
10536   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10537       Value.getOperand(1).getOpcode() != ISD::Constant)
10538     return SDValue();
10539
10540   SDValue N0 = Value.getOperand(0);
10541   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10542       Chain == SDValue(N0.getNode(), 1)) {
10543     LoadSDNode *LD = cast<LoadSDNode>(N0);
10544     if (LD->getBasePtr() != Ptr ||
10545         LD->getPointerInfo().getAddrSpace() !=
10546         ST->getPointerInfo().getAddrSpace())
10547       return SDValue();
10548
10549     // Find the type to narrow it the load / op / store to.
10550     SDValue N1 = Value.getOperand(1);
10551     unsigned BitWidth = N1.getValueSizeInBits();
10552     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10553     if (Opc == ISD::AND)
10554       Imm ^= APInt::getAllOnesValue(BitWidth);
10555     if (Imm == 0 || Imm.isAllOnesValue())
10556       return SDValue();
10557     unsigned ShAmt = Imm.countTrailingZeros();
10558     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10559     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10560     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10561     // The narrowing should be profitable, the load/store operation should be
10562     // legal (or custom) and the store size should be equal to the NewVT width.
10563     while (NewBW < BitWidth &&
10564            (NewVT.getStoreSizeInBits() != NewBW ||
10565             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10566             !TLI.isNarrowingProfitable(VT, NewVT))) {
10567       NewBW = NextPowerOf2(NewBW);
10568       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10569     }
10570     if (NewBW >= BitWidth)
10571       return SDValue();
10572
10573     // If the lsb changed does not start at the type bitwidth boundary,
10574     // start at the previous one.
10575     if (ShAmt % NewBW)
10576       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10577     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10578                                    std::min(BitWidth, ShAmt + NewBW));
10579     if ((Imm & Mask) == Imm) {
10580       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10581       if (Opc == ISD::AND)
10582         NewImm ^= APInt::getAllOnesValue(NewBW);
10583       uint64_t PtrOff = ShAmt / 8;
10584       // For big endian targets, we need to adjust the offset to the pointer to
10585       // load the correct bytes.
10586       if (DAG.getDataLayout().isBigEndian())
10587         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10588
10589       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10590       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10591       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10592         return SDValue();
10593
10594       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10595                                    Ptr.getValueType(), Ptr,
10596                                    DAG.getConstant(PtrOff, SDLoc(LD),
10597                                                    Ptr.getValueType()));
10598       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10599                                   LD->getChain(), NewPtr,
10600                                   LD->getPointerInfo().getWithOffset(PtrOff),
10601                                   LD->isVolatile(), LD->isNonTemporal(),
10602                                   LD->isInvariant(), NewAlign,
10603                                   LD->getAAInfo());
10604       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10605                                    DAG.getConstant(NewImm, SDLoc(Value),
10606                                                    NewVT));
10607       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10608                                    NewVal, NewPtr,
10609                                    ST->getPointerInfo().getWithOffset(PtrOff),
10610                                    false, false, NewAlign);
10611
10612       AddToWorklist(NewPtr.getNode());
10613       AddToWorklist(NewLD.getNode());
10614       AddToWorklist(NewVal.getNode());
10615       WorklistRemover DeadNodes(*this);
10616       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10617       ++OpsNarrowed;
10618       return NewST;
10619     }
10620   }
10621
10622   return SDValue();
10623 }
10624
10625 /// For a given floating point load / store pair, if the load value isn't used
10626 /// by any other operations, then consider transforming the pair to integer
10627 /// load / store operations if the target deems the transformation profitable.
10628 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10629   StoreSDNode *ST  = cast<StoreSDNode>(N);
10630   SDValue Chain = ST->getChain();
10631   SDValue Value = ST->getValue();
10632   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10633       Value.hasOneUse() &&
10634       Chain == SDValue(Value.getNode(), 1)) {
10635     LoadSDNode *LD = cast<LoadSDNode>(Value);
10636     EVT VT = LD->getMemoryVT();
10637     if (!VT.isFloatingPoint() ||
10638         VT != ST->getMemoryVT() ||
10639         LD->isNonTemporal() ||
10640         ST->isNonTemporal() ||
10641         LD->getPointerInfo().getAddrSpace() != 0 ||
10642         ST->getPointerInfo().getAddrSpace() != 0)
10643       return SDValue();
10644
10645     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10646     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10647         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10648         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10649         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10650       return SDValue();
10651
10652     unsigned LDAlign = LD->getAlignment();
10653     unsigned STAlign = ST->getAlignment();
10654     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10655     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10656     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10657       return SDValue();
10658
10659     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10660                                 LD->getChain(), LD->getBasePtr(),
10661                                 LD->getPointerInfo(),
10662                                 false, false, false, LDAlign);
10663
10664     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10665                                  NewLD, ST->getBasePtr(),
10666                                  ST->getPointerInfo(),
10667                                  false, false, STAlign);
10668
10669     AddToWorklist(NewLD.getNode());
10670     AddToWorklist(NewST.getNode());
10671     WorklistRemover DeadNodes(*this);
10672     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10673     ++LdStFP2Int;
10674     return NewST;
10675   }
10676
10677   return SDValue();
10678 }
10679
10680 namespace {
10681 /// Helper struct to parse and store a memory address as base + index + offset.
10682 /// We ignore sign extensions when it is safe to do so.
10683 /// The following two expressions are not equivalent. To differentiate we need
10684 /// to store whether there was a sign extension involved in the index
10685 /// computation.
10686 ///  (load (i64 add (i64 copyfromreg %c)
10687 ///                 (i64 signextend (add (i8 load %index)
10688 ///                                      (i8 1))))
10689 /// vs
10690 ///
10691 /// (load (i64 add (i64 copyfromreg %c)
10692 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10693 ///                                         (i32 1)))))
10694 struct BaseIndexOffset {
10695   SDValue Base;
10696   SDValue Index;
10697   int64_t Offset;
10698   bool IsIndexSignExt;
10699
10700   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10701
10702   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10703                   bool IsIndexSignExt) :
10704     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10705
10706   bool equalBaseIndex(const BaseIndexOffset &Other) {
10707     return Other.Base == Base && Other.Index == Index &&
10708       Other.IsIndexSignExt == IsIndexSignExt;
10709   }
10710
10711   /// Parses tree in Ptr for base, index, offset addresses.
10712   static BaseIndexOffset match(SDValue Ptr) {
10713     bool IsIndexSignExt = false;
10714
10715     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10716     // instruction, then it could be just the BASE or everything else we don't
10717     // know how to handle. Just use Ptr as BASE and give up.
10718     if (Ptr->getOpcode() != ISD::ADD)
10719       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10720
10721     // We know that we have at least an ADD instruction. Try to pattern match
10722     // the simple case of BASE + OFFSET.
10723     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10724       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10725       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10726                               IsIndexSignExt);
10727     }
10728
10729     // Inside a loop the current BASE pointer is calculated using an ADD and a
10730     // MUL instruction. In this case Ptr is the actual BASE pointer.
10731     // (i64 add (i64 %array_ptr)
10732     //          (i64 mul (i64 %induction_var)
10733     //                   (i64 %element_size)))
10734     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10735       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10736
10737     // Look at Base + Index + Offset cases.
10738     SDValue Base = Ptr->getOperand(0);
10739     SDValue IndexOffset = Ptr->getOperand(1);
10740
10741     // Skip signextends.
10742     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10743       IndexOffset = IndexOffset->getOperand(0);
10744       IsIndexSignExt = true;
10745     }
10746
10747     // Either the case of Base + Index (no offset) or something else.
10748     if (IndexOffset->getOpcode() != ISD::ADD)
10749       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10750
10751     // Now we have the case of Base + Index + offset.
10752     SDValue Index = IndexOffset->getOperand(0);
10753     SDValue Offset = IndexOffset->getOperand(1);
10754
10755     if (!isa<ConstantSDNode>(Offset))
10756       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10757
10758     // Ignore signextends.
10759     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10760       Index = Index->getOperand(0);
10761       IsIndexSignExt = true;
10762     } else IsIndexSignExt = false;
10763
10764     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10765     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10766   }
10767 };
10768 } // namespace
10769
10770 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10771                                                   SDLoc SL,
10772                                                   ArrayRef<MemOpLink> Stores,
10773                                                   SmallVectorImpl<SDValue> &Chains,
10774                                                   EVT Ty) const {
10775   SmallVector<SDValue, 8> BuildVector;
10776
10777   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10778     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10779     Chains.push_back(St->getChain());
10780     BuildVector.push_back(St->getValue());
10781   }
10782
10783   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10784 }
10785
10786 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10787                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10788                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10789   // Make sure we have something to merge.
10790   if (NumStores < 2)
10791     return false;
10792
10793   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10794   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10795   unsigned LatestNodeUsed = 0;
10796
10797   for (unsigned i=0; i < NumStores; ++i) {
10798     // Find a chain for the new wide-store operand. Notice that some
10799     // of the store nodes that we found may not be selected for inclusion
10800     // in the wide store. The chain we use needs to be the chain of the
10801     // latest store node which is *used* and replaced by the wide store.
10802     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10803       LatestNodeUsed = i;
10804   }
10805
10806   SmallVector<SDValue, 8> Chains;
10807
10808   // The latest Node in the DAG.
10809   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10810   SDLoc DL(StoreNodes[0].MemNode);
10811
10812   SDValue StoredVal;
10813   if (UseVector) {
10814     bool IsVec = MemVT.isVector();
10815     unsigned Elts = NumStores;
10816     if (IsVec) {
10817       // When merging vector stores, get the total number of elements.
10818       Elts *= MemVT.getVectorNumElements();
10819     }
10820     // Get the type for the merged vector store.
10821     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10822     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10823
10824     if (IsConstantSrc) {
10825       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10826     } else {
10827       SmallVector<SDValue, 8> Ops;
10828       for (unsigned i = 0; i < NumStores; ++i) {
10829         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10830         SDValue Val = St->getValue();
10831         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10832         if (Val.getValueType() != MemVT)
10833           return false;
10834         Ops.push_back(Val);
10835         Chains.push_back(St->getChain());
10836       }
10837
10838       // Build the extracted vector elements back into a vector.
10839       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10840                               DL, Ty, Ops);    }
10841   } else {
10842     // We should always use a vector store when merging extracted vector
10843     // elements, so this path implies a store of constants.
10844     assert(IsConstantSrc && "Merged vector elements should use vector store");
10845
10846     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10847     APInt StoreInt(SizeInBits, 0);
10848
10849     // Construct a single integer constant which is made of the smaller
10850     // constant inputs.
10851     bool IsLE = DAG.getDataLayout().isLittleEndian();
10852     for (unsigned i = 0; i < NumStores; ++i) {
10853       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10854       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10855       Chains.push_back(St->getChain());
10856
10857       SDValue Val = St->getValue();
10858       StoreInt <<= ElementSizeBytes * 8;
10859       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10860         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10861       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10862         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10863       } else {
10864         llvm_unreachable("Invalid constant element type");
10865       }
10866     }
10867
10868     // Create the new Load and Store operations.
10869     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10870     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10871   }
10872
10873   assert(!Chains.empty());
10874
10875   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10876   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
10877                                   FirstInChain->getBasePtr(),
10878                                   FirstInChain->getPointerInfo(),
10879                                   false, false,
10880                                   FirstInChain->getAlignment());
10881
10882   // Replace the last store with the new store
10883   CombineTo(LatestOp, NewStore);
10884   // Erase all other stores.
10885   for (unsigned i = 0; i < NumStores; ++i) {
10886     if (StoreNodes[i].MemNode == LatestOp)
10887       continue;
10888     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10889     // ReplaceAllUsesWith will replace all uses that existed when it was
10890     // called, but graph optimizations may cause new ones to appear. For
10891     // example, the case in pr14333 looks like
10892     //
10893     //  St's chain -> St -> another store -> X
10894     //
10895     // And the only difference from St to the other store is the chain.
10896     // When we change it's chain to be St's chain they become identical,
10897     // get CSEed and the net result is that X is now a use of St.
10898     // Since we know that St is redundant, just iterate.
10899     while (!St->use_empty())
10900       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10901     deleteAndRecombine(St);
10902   }
10903
10904   return true;
10905 }
10906
10907 void DAGCombiner::getStoreMergeAndAliasCandidates(
10908     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10909     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10910   // This holds the base pointer, index, and the offset in bytes from the base
10911   // pointer.
10912   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10913
10914   // We must have a base and an offset.
10915   if (!BasePtr.Base.getNode())
10916     return;
10917
10918   // Do not handle stores to undef base pointers.
10919   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10920     return;
10921
10922   // Walk up the chain and look for nodes with offsets from the same
10923   // base pointer. Stop when reaching an instruction with a different kind
10924   // or instruction which has a different base pointer.
10925   EVT MemVT = St->getMemoryVT();
10926   unsigned Seq = 0;
10927   StoreSDNode *Index = St;
10928
10929
10930   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10931                                                   : DAG.getSubtarget().useAA();
10932
10933   if (UseAA) {
10934     // Look at other users of the same chain. Stores on the same chain do not
10935     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10936     // to be on the same chain, so don't bother looking at adjacent chains.
10937
10938     SDValue Chain = St->getChain();
10939     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10940       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10941         if (I.getOperandNo() != 0)
10942           continue;
10943
10944         if (OtherST->isVolatile() || OtherST->isIndexed())
10945           continue;
10946
10947         if (OtherST->getMemoryVT() != MemVT)
10948           continue;
10949
10950         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10951
10952         if (Ptr.equalBaseIndex(BasePtr))
10953           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
10954       }
10955     }
10956
10957     return;
10958   }
10959
10960   while (Index) {
10961     // If the chain has more than one use, then we can't reorder the mem ops.
10962     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10963       break;
10964
10965     // Find the base pointer and offset for this memory node.
10966     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10967
10968     // Check that the base pointer is the same as the original one.
10969     if (!Ptr.equalBaseIndex(BasePtr))
10970       break;
10971
10972     // The memory operands must not be volatile.
10973     if (Index->isVolatile() || Index->isIndexed())
10974       break;
10975
10976     // No truncation.
10977     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10978       if (St->isTruncatingStore())
10979         break;
10980
10981     // The stored memory type must be the same.
10982     if (Index->getMemoryVT() != MemVT)
10983       break;
10984
10985     // We found a potential memory operand to merge.
10986     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10987
10988     // Find the next memory operand in the chain. If the next operand in the
10989     // chain is a store then move up and continue the scan with the next
10990     // memory operand. If the next operand is a load save it and use alias
10991     // information to check if it interferes with anything.
10992     SDNode *NextInChain = Index->getChain().getNode();
10993     while (1) {
10994       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10995         // We found a store node. Use it for the next iteration.
10996         Index = STn;
10997         break;
10998       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10999         if (Ldn->isVolatile()) {
11000           Index = nullptr;
11001           break;
11002         }
11003
11004         // Save the load node for later. Continue the scan.
11005         AliasLoadNodes.push_back(Ldn);
11006         NextInChain = Ldn->getChain().getNode();
11007         continue;
11008       } else {
11009         Index = nullptr;
11010         break;
11011       }
11012     }
11013   }
11014 }
11015
11016 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11017   if (OptLevel == CodeGenOpt::None)
11018     return false;
11019
11020   EVT MemVT = St->getMemoryVT();
11021   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11022   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11023       Attribute::NoImplicitFloat);
11024
11025   // This function cannot currently deal with non-byte-sized memory sizes.
11026   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11027     return false;
11028
11029   if (!MemVT.isSimple())
11030     return false;
11031
11032   // Perform an early exit check. Do not bother looking at stored values that
11033   // are not constants, loads, or extracted vector elements.
11034   SDValue StoredVal = St->getValue();
11035   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11036   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11037                        isa<ConstantFPSDNode>(StoredVal);
11038   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11039                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11040
11041   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11042     return false;
11043
11044   // Don't merge vectors into wider vectors if the source data comes from loads.
11045   // TODO: This restriction can be lifted by using logic similar to the
11046   // ExtractVecSrc case.
11047   if (MemVT.isVector() && IsLoadSrc)
11048     return false;
11049
11050   // Only look at ends of store sequences.
11051   SDValue Chain = SDValue(St, 0);
11052   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11053     return false;
11054
11055   // Save the LoadSDNodes that we find in the chain.
11056   // We need to make sure that these nodes do not interfere with
11057   // any of the store nodes.
11058   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11059
11060   // Save the StoreSDNodes that we find in the chain.
11061   SmallVector<MemOpLink, 8> StoreNodes;
11062
11063   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11064
11065   // Check if there is anything to merge.
11066   if (StoreNodes.size() < 2)
11067     return false;
11068
11069   // Sort the memory operands according to their distance from the base pointer.
11070   std::sort(StoreNodes.begin(), StoreNodes.end(),
11071             [](MemOpLink LHS, MemOpLink RHS) {
11072     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11073            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11074             LHS.SequenceNum > RHS.SequenceNum);
11075   });
11076
11077   // Scan the memory operations on the chain and find the first non-consecutive
11078   // store memory address.
11079   unsigned LastConsecutiveStore = 0;
11080   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11081   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11082
11083     // Check that the addresses are consecutive starting from the second
11084     // element in the list of stores.
11085     if (i > 0) {
11086       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11087       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11088         break;
11089     }
11090
11091     bool Alias = false;
11092     // Check if this store interferes with any of the loads that we found.
11093     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11094       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11095         Alias = true;
11096         break;
11097       }
11098     // We found a load that alias with this store. Stop the sequence.
11099     if (Alias)
11100       break;
11101
11102     // Mark this node as useful.
11103     LastConsecutiveStore = i;
11104   }
11105
11106   // The node with the lowest store address.
11107   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11108   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11109   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11110   LLVMContext &Context = *DAG.getContext();
11111   const DataLayout &DL = DAG.getDataLayout();
11112
11113   // Store the constants into memory as one consecutive store.
11114   if (IsConstantSrc) {
11115     unsigned LastLegalType = 0;
11116     unsigned LastLegalVectorType = 0;
11117     bool NonZero = false;
11118     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11119       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11120       SDValue StoredVal = St->getValue();
11121
11122       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11123         NonZero |= !C->isNullValue();
11124       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11125         NonZero |= !C->getConstantFPValue()->isNullValue();
11126       } else {
11127         // Non-constant.
11128         break;
11129       }
11130
11131       // Find a legal type for the constant store.
11132       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11133       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11134       bool IsFast;
11135       if (TLI.isTypeLegal(StoreTy) &&
11136           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11137                                  FirstStoreAlign, &IsFast) && IsFast) {
11138         LastLegalType = i+1;
11139       // Or check whether a truncstore is legal.
11140       } else if (TLI.getTypeAction(Context, StoreTy) ==
11141                  TargetLowering::TypePromoteInteger) {
11142         EVT LegalizedStoredValueTy =
11143           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11144         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11145             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11146                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11147             IsFast) {
11148           LastLegalType = i + 1;
11149         }
11150       }
11151
11152       // We only use vectors if the constant is known to be zero or the target
11153       // allows it and the function is not marked with the noimplicitfloat
11154       // attribute.
11155       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11156                                                         FirstStoreAS)) &&
11157           !NoVectors) {
11158         // Find a legal type for the vector store.
11159         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11160         if (TLI.isTypeLegal(Ty) &&
11161             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11162                                    FirstStoreAlign, &IsFast) && IsFast)
11163           LastLegalVectorType = i + 1;
11164       }
11165     }
11166
11167     // Check if we found a legal integer type to store.
11168     if (LastLegalType == 0 && LastLegalVectorType == 0)
11169       return false;
11170
11171     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11172     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11173
11174     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11175                                            true, UseVector);
11176   }
11177
11178   // When extracting multiple vector elements, try to store them
11179   // in one vector store rather than a sequence of scalar stores.
11180   if (IsExtractVecSrc) {
11181     unsigned NumStoresToMerge = 0;
11182     bool IsVec = MemVT.isVector();
11183     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11184       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11185       unsigned StoreValOpcode = St->getValue().getOpcode();
11186       // This restriction could be loosened.
11187       // Bail out if any stored values are not elements extracted from a vector.
11188       // It should be possible to handle mixed sources, but load sources need
11189       // more careful handling (see the block of code below that handles
11190       // consecutive loads).
11191       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11192           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11193         return false;
11194
11195       // Find a legal type for the vector store.
11196       unsigned Elts = i + 1;
11197       if (IsVec) {
11198         // When merging vector stores, get the total number of elements.
11199         Elts *= MemVT.getVectorNumElements();
11200       }
11201       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11202       bool IsFast;
11203       if (TLI.isTypeLegal(Ty) &&
11204           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11205                                  FirstStoreAlign, &IsFast) && IsFast)
11206         NumStoresToMerge = i + 1;
11207     }
11208
11209     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11210                                            false, true);
11211   }
11212
11213   // Below we handle the case of multiple consecutive stores that
11214   // come from multiple consecutive loads. We merge them into a single
11215   // wide load and a single wide store.
11216
11217   // Look for load nodes which are used by the stored values.
11218   SmallVector<MemOpLink, 8> LoadNodes;
11219
11220   // Find acceptable loads. Loads need to have the same chain (token factor),
11221   // must not be zext, volatile, indexed, and they must be consecutive.
11222   BaseIndexOffset LdBasePtr;
11223   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11224     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11225     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11226     if (!Ld) break;
11227
11228     // Loads must only have one use.
11229     if (!Ld->hasNUsesOfValue(1, 0))
11230       break;
11231
11232     // The memory operands must not be volatile.
11233     if (Ld->isVolatile() || Ld->isIndexed())
11234       break;
11235
11236     // We do not accept ext loads.
11237     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11238       break;
11239
11240     // The stored memory type must be the same.
11241     if (Ld->getMemoryVT() != MemVT)
11242       break;
11243
11244     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11245     // If this is not the first ptr that we check.
11246     if (LdBasePtr.Base.getNode()) {
11247       // The base ptr must be the same.
11248       if (!LdPtr.equalBaseIndex(LdBasePtr))
11249         break;
11250     } else {
11251       // Check that all other base pointers are the same as this one.
11252       LdBasePtr = LdPtr;
11253     }
11254
11255     // We found a potential memory operand to merge.
11256     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11257   }
11258
11259   if (LoadNodes.size() < 2)
11260     return false;
11261
11262   // If we have load/store pair instructions and we only have two values,
11263   // don't bother.
11264   unsigned RequiredAlignment;
11265   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11266       St->getAlignment() >= RequiredAlignment)
11267     return false;
11268
11269   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11270   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11271   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11272
11273   // Scan the memory operations on the chain and find the first non-consecutive
11274   // load memory address. These variables hold the index in the store node
11275   // array.
11276   unsigned LastConsecutiveLoad = 0;
11277   // This variable refers to the size and not index in the array.
11278   unsigned LastLegalVectorType = 0;
11279   unsigned LastLegalIntegerType = 0;
11280   StartAddress = LoadNodes[0].OffsetFromBase;
11281   SDValue FirstChain = FirstLoad->getChain();
11282   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11283     // All loads much share the same chain.
11284     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11285       break;
11286
11287     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11288     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11289       break;
11290     LastConsecutiveLoad = i;
11291     // Find a legal type for the vector store.
11292     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11293     bool IsFastSt, IsFastLd;
11294     if (TLI.isTypeLegal(StoreTy) &&
11295         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11296                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11297         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11298                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11299       LastLegalVectorType = i + 1;
11300     }
11301
11302     // Find a legal type for the integer store.
11303     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11304     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11305     if (TLI.isTypeLegal(StoreTy) &&
11306         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11307                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11308         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11309                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11310       LastLegalIntegerType = i + 1;
11311     // Or check whether a truncstore and extload is legal.
11312     else if (TLI.getTypeAction(Context, StoreTy) ==
11313              TargetLowering::TypePromoteInteger) {
11314       EVT LegalizedStoredValueTy =
11315         TLI.getTypeToTransformTo(Context, StoreTy);
11316       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11317           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11318           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11319           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11320           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11321                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11322           IsFastSt &&
11323           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11324                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11325           IsFastLd)
11326         LastLegalIntegerType = i+1;
11327     }
11328   }
11329
11330   // Only use vector types if the vector type is larger than the integer type.
11331   // If they are the same, use integers.
11332   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11333   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11334
11335   // We add +1 here because the LastXXX variables refer to location while
11336   // the NumElem refers to array/index size.
11337   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11338   NumElem = std::min(LastLegalType, NumElem);
11339
11340   if (NumElem < 2)
11341     return false;
11342
11343   // Collect the chains from all merged stores.
11344   SmallVector<SDValue, 8> MergeStoreChains;
11345   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11346
11347   // The latest Node in the DAG.
11348   unsigned LatestNodeUsed = 0;
11349   for (unsigned i=1; i<NumElem; ++i) {
11350     // Find a chain for the new wide-store operand. Notice that some
11351     // of the store nodes that we found may not be selected for inclusion
11352     // in the wide store. The chain we use needs to be the chain of the
11353     // latest store node which is *used* and replaced by the wide store.
11354     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11355       LatestNodeUsed = i;
11356
11357     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11358   }
11359
11360   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11361
11362   // Find if it is better to use vectors or integers to load and store
11363   // to memory.
11364   EVT JointMemOpVT;
11365   if (UseVectorTy) {
11366     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11367   } else {
11368     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11369     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11370   }
11371
11372   SDLoc LoadDL(LoadNodes[0].MemNode);
11373   SDLoc StoreDL(StoreNodes[0].MemNode);
11374
11375   // The merged loads are required to have the same chain, so using the first's
11376   // chain is acceptable.
11377   SDValue NewLoad = DAG.getLoad(
11378       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11379       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11380
11381   SDValue NewStoreChain =
11382     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11383
11384   SDValue NewStore = DAG.getStore(
11385     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11386       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11387
11388   // Replace one of the loads with the new load.
11389   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11390   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11391                                 SDValue(NewLoad.getNode(), 1));
11392
11393   // Remove the rest of the load chains.
11394   for (unsigned i = 1; i < NumElem ; ++i) {
11395     // Replace all chain users of the old load nodes with the chain of the new
11396     // load node.
11397     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11398     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11399   }
11400
11401   // Replace the last store with the new store.
11402   CombineTo(LatestOp, NewStore);
11403   // Erase all other stores.
11404   for (unsigned i = 0; i < NumElem ; ++i) {
11405     // Remove all Store nodes.
11406     if (StoreNodes[i].MemNode == LatestOp)
11407       continue;
11408     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11409     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11410     deleteAndRecombine(St);
11411   }
11412
11413   return true;
11414 }
11415
11416 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11417   SDLoc SL(ST);
11418   SDValue ReplStore;
11419
11420   // Replace the chain to avoid dependency.
11421   if (ST->isTruncatingStore()) {
11422     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11423                                   ST->getBasePtr(), ST->getMemoryVT(),
11424                                   ST->getMemOperand());
11425   } else {
11426     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11427                              ST->getMemOperand());
11428   }
11429
11430   // Create token to keep both nodes around.
11431   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11432                               MVT::Other, ST->getChain(), ReplStore);
11433
11434   // Make sure the new and old chains are cleaned up.
11435   AddToWorklist(Token.getNode());
11436
11437   // Don't add users to work list.
11438   return CombineTo(ST, Token, false);
11439 }
11440
11441 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11442   SDValue Value = ST->getValue();
11443   if (Value.getOpcode() == ISD::TargetConstantFP)
11444     return SDValue();
11445
11446   SDLoc DL(ST);
11447
11448   SDValue Chain = ST->getChain();
11449   SDValue Ptr = ST->getBasePtr();
11450
11451   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11452
11453   // NOTE: If the original store is volatile, this transform must not increase
11454   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11455   // processor operation but an i64 (which is not legal) requires two.  So the
11456   // transform should not be done in this case.
11457
11458   SDValue Tmp;
11459   switch (CFP->getSimpleValueType(0).SimpleTy) {
11460   default:
11461     llvm_unreachable("Unknown FP type");
11462   case MVT::f16:    // We don't do this for these yet.
11463   case MVT::f80:
11464   case MVT::f128:
11465   case MVT::ppcf128:
11466     return SDValue();
11467   case MVT::f32:
11468     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11469         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11470       ;
11471       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11472                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11473                             MVT::i32);
11474       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11475     }
11476
11477     return SDValue();
11478   case MVT::f64:
11479     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11480          !ST->isVolatile()) ||
11481         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11482       ;
11483       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11484                             getZExtValue(), SDLoc(CFP), MVT::i64);
11485       return DAG.getStore(Chain, DL, Tmp,
11486                           Ptr, ST->getMemOperand());
11487     }
11488
11489     if (!ST->isVolatile() &&
11490         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11491       // Many FP stores are not made apparent until after legalize, e.g. for
11492       // argument passing.  Since this is so common, custom legalize the
11493       // 64-bit integer store into two 32-bit stores.
11494       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11495       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11496       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11497       if (DAG.getDataLayout().isBigEndian())
11498         std::swap(Lo, Hi);
11499
11500       unsigned Alignment = ST->getAlignment();
11501       bool isVolatile = ST->isVolatile();
11502       bool isNonTemporal = ST->isNonTemporal();
11503       AAMDNodes AAInfo = ST->getAAInfo();
11504
11505       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11506                                  Ptr, ST->getPointerInfo(),
11507                                  isVolatile, isNonTemporal,
11508                                  ST->getAlignment(), AAInfo);
11509       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11510                         DAG.getConstant(4, DL, Ptr.getValueType()));
11511       Alignment = MinAlign(Alignment, 4U);
11512       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11513                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11514                                  isVolatile, isNonTemporal,
11515                                  Alignment, AAInfo);
11516       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11517                          St0, St1);
11518     }
11519
11520     return SDValue();
11521   }
11522 }
11523
11524 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11525   StoreSDNode *ST  = cast<StoreSDNode>(N);
11526   SDValue Chain = ST->getChain();
11527   SDValue Value = ST->getValue();
11528   SDValue Ptr   = ST->getBasePtr();
11529
11530   // If this is a store of a bit convert, store the input value if the
11531   // resultant store does not need a higher alignment than the original.
11532   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11533       ST->isUnindexed()) {
11534     unsigned OrigAlign = ST->getAlignment();
11535     EVT SVT = Value.getOperand(0).getValueType();
11536     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11537         SVT.getTypeForEVT(*DAG.getContext()));
11538     if (Align <= OrigAlign &&
11539         ((!LegalOperations && !ST->isVolatile()) ||
11540          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11541       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11542                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11543                           ST->isNonTemporal(), OrigAlign,
11544                           ST->getAAInfo());
11545   }
11546
11547   // Turn 'store undef, Ptr' -> nothing.
11548   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11549     return Chain;
11550
11551   // Try to infer better alignment information than the store already has.
11552   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11553     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11554       if (Align > ST->getAlignment()) {
11555         SDValue NewStore =
11556                DAG.getTruncStore(Chain, SDLoc(N), Value,
11557                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11558                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11559                                  ST->getAAInfo());
11560         if (NewStore.getNode() != N)
11561           return CombineTo(ST, NewStore, true);
11562       }
11563     }
11564   }
11565
11566   // Try transforming a pair floating point load / store ops to integer
11567   // load / store ops.
11568   if (SDValue NewST = TransformFPLoadStorePair(N))
11569     return NewST;
11570
11571   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11572                                                   : DAG.getSubtarget().useAA();
11573 #ifndef NDEBUG
11574   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11575       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11576     UseAA = false;
11577 #endif
11578   if (UseAA && ST->isUnindexed()) {
11579     // FIXME: We should do this even without AA enabled. AA will just allow
11580     // FindBetterChain to work in more situations. The problem with this is that
11581     // any combine that expects memory operations to be on consecutive chains
11582     // first needs to be updated to look for users of the same chain.
11583
11584     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11585     // adjacent stores.
11586     if (findBetterNeighborChains(ST)) {
11587       // replaceStoreChain uses CombineTo, which handled all of the worklist
11588       // manipulation. Return the original node to not do anything else.
11589       return SDValue(ST, 0);
11590     }
11591   }
11592
11593   // Try transforming N to an indexed store.
11594   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11595     return SDValue(N, 0);
11596
11597   // FIXME: is there such a thing as a truncating indexed store?
11598   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11599       Value.getValueType().isInteger()) {
11600     // See if we can simplify the input to this truncstore with knowledge that
11601     // only the low bits are being used.  For example:
11602     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11603     SDValue Shorter =
11604       GetDemandedBits(Value,
11605                       APInt::getLowBitsSet(
11606                         Value.getValueType().getScalarType().getSizeInBits(),
11607                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11608     AddToWorklist(Value.getNode());
11609     if (Shorter.getNode())
11610       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11611                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11612
11613     // Otherwise, see if we can simplify the operation with
11614     // SimplifyDemandedBits, which only works if the value has a single use.
11615     if (SimplifyDemandedBits(Value,
11616                         APInt::getLowBitsSet(
11617                           Value.getValueType().getScalarType().getSizeInBits(),
11618                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11619       return SDValue(N, 0);
11620   }
11621
11622   // If this is a load followed by a store to the same location, then the store
11623   // is dead/noop.
11624   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11625     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11626         ST->isUnindexed() && !ST->isVolatile() &&
11627         // There can't be any side effects between the load and store, such as
11628         // a call or store.
11629         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11630       // The store is dead, remove it.
11631       return Chain;
11632     }
11633   }
11634
11635   // If this is a store followed by a store with the same value to the same
11636   // location, then the store is dead/noop.
11637   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11638     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11639         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11640         ST1->isUnindexed() && !ST1->isVolatile()) {
11641       // The store is dead, remove it.
11642       return Chain;
11643     }
11644   }
11645
11646   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11647   // truncating store.  We can do this even if this is already a truncstore.
11648   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11649       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11650       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11651                             ST->getMemoryVT())) {
11652     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11653                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11654   }
11655
11656   // Only perform this optimization before the types are legal, because we
11657   // don't want to perform this optimization on every DAGCombine invocation.
11658   if (!LegalTypes) {
11659     bool EverChanged = false;
11660
11661     do {
11662       // There can be multiple store sequences on the same chain.
11663       // Keep trying to merge store sequences until we are unable to do so
11664       // or until we merge the last store on the chain.
11665       bool Changed = MergeConsecutiveStores(ST);
11666       EverChanged |= Changed;
11667       if (!Changed) break;
11668     } while (ST->getOpcode() != ISD::DELETED_NODE);
11669
11670     if (EverChanged)
11671       return SDValue(N, 0);
11672   }
11673
11674   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11675   //
11676   // Make sure to do this only after attempting to merge stores in order to
11677   //  avoid changing the types of some subset of stores due to visit order,
11678   //  preventing their merging.
11679   if (isa<ConstantFPSDNode>(Value)) {
11680     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11681       return NewSt;
11682   }
11683
11684   return ReduceLoadOpStoreWidth(N);
11685 }
11686
11687 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11688   SDValue InVec = N->getOperand(0);
11689   SDValue InVal = N->getOperand(1);
11690   SDValue EltNo = N->getOperand(2);
11691   SDLoc dl(N);
11692
11693   // If the inserted element is an UNDEF, just use the input vector.
11694   if (InVal.getOpcode() == ISD::UNDEF)
11695     return InVec;
11696
11697   EVT VT = InVec.getValueType();
11698
11699   // If we can't generate a legal BUILD_VECTOR, exit
11700   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11701     return SDValue();
11702
11703   // Check that we know which element is being inserted
11704   if (!isa<ConstantSDNode>(EltNo))
11705     return SDValue();
11706   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11707
11708   // Canonicalize insert_vector_elt dag nodes.
11709   // Example:
11710   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11711   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11712   //
11713   // Do this only if the child insert_vector node has one use; also
11714   // do this only if indices are both constants and Idx1 < Idx0.
11715   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11716       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11717     unsigned OtherElt =
11718       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11719     if (Elt < OtherElt) {
11720       // Swap nodes.
11721       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11722                                   InVec.getOperand(0), InVal, EltNo);
11723       AddToWorklist(NewOp.getNode());
11724       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11725                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11726     }
11727   }
11728
11729   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11730   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11731   // vector elements.
11732   SmallVector<SDValue, 8> Ops;
11733   // Do not combine these two vectors if the output vector will not replace
11734   // the input vector.
11735   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11736     Ops.append(InVec.getNode()->op_begin(),
11737                InVec.getNode()->op_end());
11738   } else if (InVec.getOpcode() == ISD::UNDEF) {
11739     unsigned NElts = VT.getVectorNumElements();
11740     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11741   } else {
11742     return SDValue();
11743   }
11744
11745   // Insert the element
11746   if (Elt < Ops.size()) {
11747     // All the operands of BUILD_VECTOR must have the same type;
11748     // we enforce that here.
11749     EVT OpVT = Ops[0].getValueType();
11750     if (InVal.getValueType() != OpVT)
11751       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11752                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11753                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11754     Ops[Elt] = InVal;
11755   }
11756
11757   // Return the new vector
11758   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11759 }
11760
11761 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11762     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11763   EVT ResultVT = EVE->getValueType(0);
11764   EVT VecEltVT = InVecVT.getVectorElementType();
11765   unsigned Align = OriginalLoad->getAlignment();
11766   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11767       VecEltVT.getTypeForEVT(*DAG.getContext()));
11768
11769   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11770     return SDValue();
11771
11772   Align = NewAlign;
11773
11774   SDValue NewPtr = OriginalLoad->getBasePtr();
11775   SDValue Offset;
11776   EVT PtrType = NewPtr.getValueType();
11777   MachinePointerInfo MPI;
11778   SDLoc DL(EVE);
11779   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11780     int Elt = ConstEltNo->getZExtValue();
11781     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11782     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11783     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11784   } else {
11785     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11786     Offset = DAG.getNode(
11787         ISD::MUL, DL, PtrType, Offset,
11788         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11789     MPI = OriginalLoad->getPointerInfo();
11790   }
11791   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11792
11793   // The replacement we need to do here is a little tricky: we need to
11794   // replace an extractelement of a load with a load.
11795   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11796   // Note that this replacement assumes that the extractvalue is the only
11797   // use of the load; that's okay because we don't want to perform this
11798   // transformation in other cases anyway.
11799   SDValue Load;
11800   SDValue Chain;
11801   if (ResultVT.bitsGT(VecEltVT)) {
11802     // If the result type of vextract is wider than the load, then issue an
11803     // extending load instead.
11804     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11805                                                   VecEltVT)
11806                                    ? ISD::ZEXTLOAD
11807                                    : ISD::EXTLOAD;
11808     Load = DAG.getExtLoad(
11809         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11810         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11811         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11812     Chain = Load.getValue(1);
11813   } else {
11814     Load = DAG.getLoad(
11815         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11816         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11817         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11818     Chain = Load.getValue(1);
11819     if (ResultVT.bitsLT(VecEltVT))
11820       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11821     else
11822       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11823   }
11824   WorklistRemover DeadNodes(*this);
11825   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11826   SDValue To[] = { Load, Chain };
11827   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11828   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11829   // worklist explicitly as well.
11830   AddToWorklist(Load.getNode());
11831   AddUsersToWorklist(Load.getNode()); // Add users too
11832   // Make sure to revisit this node to clean it up; it will usually be dead.
11833   AddToWorklist(EVE);
11834   ++OpsNarrowed;
11835   return SDValue(EVE, 0);
11836 }
11837
11838 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11839   // (vextract (scalar_to_vector val, 0) -> val
11840   SDValue InVec = N->getOperand(0);
11841   EVT VT = InVec.getValueType();
11842   EVT NVT = N->getValueType(0);
11843
11844   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11845     // Check if the result type doesn't match the inserted element type. A
11846     // SCALAR_TO_VECTOR may truncate the inserted element and the
11847     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11848     SDValue InOp = InVec.getOperand(0);
11849     if (InOp.getValueType() != NVT) {
11850       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11851       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11852     }
11853     return InOp;
11854   }
11855
11856   SDValue EltNo = N->getOperand(1);
11857   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
11858
11859   // extract_vector_elt (build_vector x, y), 1 -> y
11860   if (ConstEltNo &&
11861       InVec.getOpcode() == ISD::BUILD_VECTOR &&
11862       TLI.isTypeLegal(VT) &&
11863       (InVec.hasOneUse() ||
11864        TLI.aggressivelyPreferBuildVectorSources(VT))) {
11865     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
11866     EVT InEltVT = Elt.getValueType();
11867
11868     // Sometimes build_vector's scalar input types do not match result type.
11869     if (NVT == InEltVT)
11870       return Elt;
11871
11872     // TODO: It may be useful to truncate if free if the build_vector implicitly
11873     // converts.
11874   }
11875
11876   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11877   // We only perform this optimization before the op legalization phase because
11878   // we may introduce new vector instructions which are not backed by TD
11879   // patterns. For example on AVX, extracting elements from a wide vector
11880   // without using extract_subvector. However, if we can find an underlying
11881   // scalar value, then we can always use that.
11882   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
11883     int NumElem = VT.getVectorNumElements();
11884     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11885     // Find the new index to extract from.
11886     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
11887
11888     // Extracting an undef index is undef.
11889     if (OrigElt == -1)
11890       return DAG.getUNDEF(NVT);
11891
11892     // Select the right vector half to extract from.
11893     SDValue SVInVec;
11894     if (OrigElt < NumElem) {
11895       SVInVec = InVec->getOperand(0);
11896     } else {
11897       SVInVec = InVec->getOperand(1);
11898       OrigElt -= NumElem;
11899     }
11900
11901     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11902       SDValue InOp = SVInVec.getOperand(OrigElt);
11903       if (InOp.getValueType() != NVT) {
11904         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11905         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11906       }
11907
11908       return InOp;
11909     }
11910
11911     // FIXME: We should handle recursing on other vector shuffles and
11912     // scalar_to_vector here as well.
11913
11914     if (!LegalOperations) {
11915       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11916       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11917                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11918     }
11919   }
11920
11921   bool BCNumEltsChanged = false;
11922   EVT ExtVT = VT.getVectorElementType();
11923   EVT LVT = ExtVT;
11924
11925   // If the result of load has to be truncated, then it's not necessarily
11926   // profitable.
11927   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11928     return SDValue();
11929
11930   if (InVec.getOpcode() == ISD::BITCAST) {
11931     // Don't duplicate a load with other uses.
11932     if (!InVec.hasOneUse())
11933       return SDValue();
11934
11935     EVT BCVT = InVec.getOperand(0).getValueType();
11936     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11937       return SDValue();
11938     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11939       BCNumEltsChanged = true;
11940     InVec = InVec.getOperand(0);
11941     ExtVT = BCVT.getVectorElementType();
11942   }
11943
11944   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11945   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11946       ISD::isNormalLoad(InVec.getNode()) &&
11947       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11948     SDValue Index = N->getOperand(1);
11949     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11950       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11951                                                            OrigLoad);
11952   }
11953
11954   // Perform only after legalization to ensure build_vector / vector_shuffle
11955   // optimizations have already been done.
11956   if (!LegalOperations) return SDValue();
11957
11958   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11959   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11960   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11961
11962   if (ConstEltNo) {
11963     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11964
11965     LoadSDNode *LN0 = nullptr;
11966     const ShuffleVectorSDNode *SVN = nullptr;
11967     if (ISD::isNormalLoad(InVec.getNode())) {
11968       LN0 = cast<LoadSDNode>(InVec);
11969     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11970                InVec.getOperand(0).getValueType() == ExtVT &&
11971                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11972       // Don't duplicate a load with other uses.
11973       if (!InVec.hasOneUse())
11974         return SDValue();
11975
11976       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11977     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11978       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11979       // =>
11980       // (load $addr+1*size)
11981
11982       // Don't duplicate a load with other uses.
11983       if (!InVec.hasOneUse())
11984         return SDValue();
11985
11986       // If the bit convert changed the number of elements, it is unsafe
11987       // to examine the mask.
11988       if (BCNumEltsChanged)
11989         return SDValue();
11990
11991       // Select the input vector, guarding against out of range extract vector.
11992       unsigned NumElems = VT.getVectorNumElements();
11993       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11994       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11995
11996       if (InVec.getOpcode() == ISD::BITCAST) {
11997         // Don't duplicate a load with other uses.
11998         if (!InVec.hasOneUse())
11999           return SDValue();
12000
12001         InVec = InVec.getOperand(0);
12002       }
12003       if (ISD::isNormalLoad(InVec.getNode())) {
12004         LN0 = cast<LoadSDNode>(InVec);
12005         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12006         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12007       }
12008     }
12009
12010     // Make sure we found a non-volatile load and the extractelement is
12011     // the only use.
12012     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12013       return SDValue();
12014
12015     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12016     if (Elt == -1)
12017       return DAG.getUNDEF(LVT);
12018
12019     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12020   }
12021
12022   return SDValue();
12023 }
12024
12025 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12026 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12027   // We perform this optimization post type-legalization because
12028   // the type-legalizer often scalarizes integer-promoted vectors.
12029   // Performing this optimization before may create bit-casts which
12030   // will be type-legalized to complex code sequences.
12031   // We perform this optimization only before the operation legalizer because we
12032   // may introduce illegal operations.
12033   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12034     return SDValue();
12035
12036   unsigned NumInScalars = N->getNumOperands();
12037   SDLoc dl(N);
12038   EVT VT = N->getValueType(0);
12039
12040   // Check to see if this is a BUILD_VECTOR of a bunch of values
12041   // which come from any_extend or zero_extend nodes. If so, we can create
12042   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12043   // optimizations. We do not handle sign-extend because we can't fill the sign
12044   // using shuffles.
12045   EVT SourceType = MVT::Other;
12046   bool AllAnyExt = true;
12047
12048   for (unsigned i = 0; i != NumInScalars; ++i) {
12049     SDValue In = N->getOperand(i);
12050     // Ignore undef inputs.
12051     if (In.getOpcode() == ISD::UNDEF) continue;
12052
12053     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12054     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12055
12056     // Abort if the element is not an extension.
12057     if (!ZeroExt && !AnyExt) {
12058       SourceType = MVT::Other;
12059       break;
12060     }
12061
12062     // The input is a ZeroExt or AnyExt. Check the original type.
12063     EVT InTy = In.getOperand(0).getValueType();
12064
12065     // Check that all of the widened source types are the same.
12066     if (SourceType == MVT::Other)
12067       // First time.
12068       SourceType = InTy;
12069     else if (InTy != SourceType) {
12070       // Multiple income types. Abort.
12071       SourceType = MVT::Other;
12072       break;
12073     }
12074
12075     // Check if all of the extends are ANY_EXTENDs.
12076     AllAnyExt &= AnyExt;
12077   }
12078
12079   // In order to have valid types, all of the inputs must be extended from the
12080   // same source type and all of the inputs must be any or zero extend.
12081   // Scalar sizes must be a power of two.
12082   EVT OutScalarTy = VT.getScalarType();
12083   bool ValidTypes = SourceType != MVT::Other &&
12084                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12085                  isPowerOf2_32(SourceType.getSizeInBits());
12086
12087   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12088   // turn into a single shuffle instruction.
12089   if (!ValidTypes)
12090     return SDValue();
12091
12092   bool isLE = DAG.getDataLayout().isLittleEndian();
12093   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12094   assert(ElemRatio > 1 && "Invalid element size ratio");
12095   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12096                                DAG.getConstant(0, SDLoc(N), SourceType);
12097
12098   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12099   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12100
12101   // Populate the new build_vector
12102   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12103     SDValue Cast = N->getOperand(i);
12104     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12105             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12106             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12107     SDValue In;
12108     if (Cast.getOpcode() == ISD::UNDEF)
12109       In = DAG.getUNDEF(SourceType);
12110     else
12111       In = Cast->getOperand(0);
12112     unsigned Index = isLE ? (i * ElemRatio) :
12113                             (i * ElemRatio + (ElemRatio - 1));
12114
12115     assert(Index < Ops.size() && "Invalid index");
12116     Ops[Index] = In;
12117   }
12118
12119   // The type of the new BUILD_VECTOR node.
12120   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12121   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12122          "Invalid vector size");
12123   // Check if the new vector type is legal.
12124   if (!isTypeLegal(VecVT)) return SDValue();
12125
12126   // Make the new BUILD_VECTOR.
12127   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12128
12129   // The new BUILD_VECTOR node has the potential to be further optimized.
12130   AddToWorklist(BV.getNode());
12131   // Bitcast to the desired type.
12132   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12133 }
12134
12135 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12136   EVT VT = N->getValueType(0);
12137
12138   unsigned NumInScalars = N->getNumOperands();
12139   SDLoc dl(N);
12140
12141   EVT SrcVT = MVT::Other;
12142   unsigned Opcode = ISD::DELETED_NODE;
12143   unsigned NumDefs = 0;
12144
12145   for (unsigned i = 0; i != NumInScalars; ++i) {
12146     SDValue In = N->getOperand(i);
12147     unsigned Opc = In.getOpcode();
12148
12149     if (Opc == ISD::UNDEF)
12150       continue;
12151
12152     // If all scalar values are floats and converted from integers.
12153     if (Opcode == ISD::DELETED_NODE &&
12154         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12155       Opcode = Opc;
12156     }
12157
12158     if (Opc != Opcode)
12159       return SDValue();
12160
12161     EVT InVT = In.getOperand(0).getValueType();
12162
12163     // If all scalar values are typed differently, bail out. It's chosen to
12164     // simplify BUILD_VECTOR of integer types.
12165     if (SrcVT == MVT::Other)
12166       SrcVT = InVT;
12167     if (SrcVT != InVT)
12168       return SDValue();
12169     NumDefs++;
12170   }
12171
12172   // If the vector has just one element defined, it's not worth to fold it into
12173   // a vectorized one.
12174   if (NumDefs < 2)
12175     return SDValue();
12176
12177   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12178          && "Should only handle conversion from integer to float.");
12179   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12180
12181   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12182
12183   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12184     return SDValue();
12185
12186   // Just because the floating-point vector type is legal does not necessarily
12187   // mean that the corresponding integer vector type is.
12188   if (!isTypeLegal(NVT))
12189     return SDValue();
12190
12191   SmallVector<SDValue, 8> Opnds;
12192   for (unsigned i = 0; i != NumInScalars; ++i) {
12193     SDValue In = N->getOperand(i);
12194
12195     if (In.getOpcode() == ISD::UNDEF)
12196       Opnds.push_back(DAG.getUNDEF(SrcVT));
12197     else
12198       Opnds.push_back(In.getOperand(0));
12199   }
12200   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12201   AddToWorklist(BV.getNode());
12202
12203   return DAG.getNode(Opcode, dl, VT, BV);
12204 }
12205
12206 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12207   unsigned NumInScalars = N->getNumOperands();
12208   SDLoc dl(N);
12209   EVT VT = N->getValueType(0);
12210
12211   // A vector built entirely of undefs is undef.
12212   if (ISD::allOperandsUndef(N))
12213     return DAG.getUNDEF(VT);
12214
12215   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12216     return V;
12217
12218   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12219     return V;
12220
12221   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12222   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12223   // at most two distinct vectors, turn this into a shuffle node.
12224
12225   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12226   if (!isTypeLegal(VT))
12227     return SDValue();
12228
12229   // May only combine to shuffle after legalize if shuffle is legal.
12230   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12231     return SDValue();
12232
12233   SDValue VecIn1, VecIn2;
12234   bool UsesZeroVector = false;
12235   for (unsigned i = 0; i != NumInScalars; ++i) {
12236     SDValue Op = N->getOperand(i);
12237     // Ignore undef inputs.
12238     if (Op.getOpcode() == ISD::UNDEF) continue;
12239
12240     // See if we can combine this build_vector into a blend with a zero vector.
12241     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12242       UsesZeroVector = true;
12243       continue;
12244     }
12245
12246     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12247     // constant index, bail out.
12248     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12249         !isa<ConstantSDNode>(Op.getOperand(1))) {
12250       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12251       break;
12252     }
12253
12254     // We allow up to two distinct input vectors.
12255     SDValue ExtractedFromVec = Op.getOperand(0);
12256     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12257       continue;
12258
12259     if (!VecIn1.getNode()) {
12260       VecIn1 = ExtractedFromVec;
12261     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12262       VecIn2 = ExtractedFromVec;
12263     } else {
12264       // Too many inputs.
12265       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12266       break;
12267     }
12268   }
12269
12270   // If everything is good, we can make a shuffle operation.
12271   if (VecIn1.getNode()) {
12272     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12273     SmallVector<int, 8> Mask;
12274     for (unsigned i = 0; i != NumInScalars; ++i) {
12275       unsigned Opcode = N->getOperand(i).getOpcode();
12276       if (Opcode == ISD::UNDEF) {
12277         Mask.push_back(-1);
12278         continue;
12279       }
12280
12281       // Operands can also be zero.
12282       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12283         assert(UsesZeroVector &&
12284                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12285                "Unexpected node found!");
12286         Mask.push_back(NumInScalars+i);
12287         continue;
12288       }
12289
12290       // If extracting from the first vector, just use the index directly.
12291       SDValue Extract = N->getOperand(i);
12292       SDValue ExtVal = Extract.getOperand(1);
12293       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12294       if (Extract.getOperand(0) == VecIn1) {
12295         Mask.push_back(ExtIndex);
12296         continue;
12297       }
12298
12299       // Otherwise, use InIdx + InputVecSize
12300       Mask.push_back(InNumElements + ExtIndex);
12301     }
12302
12303     // Avoid introducing illegal shuffles with zero.
12304     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12305       return SDValue();
12306
12307     // We can't generate a shuffle node with mismatched input and output types.
12308     // Attempt to transform a single input vector to the correct type.
12309     if ((VT != VecIn1.getValueType())) {
12310       // If the input vector type has a different base type to the output
12311       // vector type, bail out.
12312       EVT VTElemType = VT.getVectorElementType();
12313       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12314           (VecIn2.getNode() &&
12315            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12316         return SDValue();
12317
12318       // If the input vector is too small, widen it.
12319       // We only support widening of vectors which are half the size of the
12320       // output registers. For example XMM->YMM widening on X86 with AVX.
12321       EVT VecInT = VecIn1.getValueType();
12322       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12323         // If we only have one small input, widen it by adding undef values.
12324         if (!VecIn2.getNode())
12325           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12326                                DAG.getUNDEF(VecIn1.getValueType()));
12327         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12328           // If we have two small inputs of the same type, try to concat them.
12329           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12330           VecIn2 = SDValue(nullptr, 0);
12331         } else
12332           return SDValue();
12333       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12334         // If the input vector is too large, try to split it.
12335         // We don't support having two input vectors that are too large.
12336         // If the zero vector was used, we can not split the vector,
12337         // since we'd need 3 inputs.
12338         if (UsesZeroVector || VecIn2.getNode())
12339           return SDValue();
12340
12341         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12342           return SDValue();
12343
12344         // Try to replace VecIn1 with two extract_subvectors
12345         // No need to update the masks, they should still be correct.
12346         VecIn2 = DAG.getNode(
12347             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12348             DAG.getConstant(VT.getVectorNumElements(), dl,
12349                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12350         VecIn1 = DAG.getNode(
12351             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12352             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12353       } else
12354         return SDValue();
12355     }
12356
12357     if (UsesZeroVector)
12358       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12359                                 DAG.getConstantFP(0.0, dl, VT);
12360     else
12361       // If VecIn2 is unused then change it to undef.
12362       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12363
12364     // Check that we were able to transform all incoming values to the same
12365     // type.
12366     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12367         VecIn1.getValueType() != VT)
12368           return SDValue();
12369
12370     // Return the new VECTOR_SHUFFLE node.
12371     SDValue Ops[2];
12372     Ops[0] = VecIn1;
12373     Ops[1] = VecIn2;
12374     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12375   }
12376
12377   return SDValue();
12378 }
12379
12380 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12381   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12382   EVT OpVT = N->getOperand(0).getValueType();
12383
12384   // If the operands are legal vectors, leave them alone.
12385   if (TLI.isTypeLegal(OpVT))
12386     return SDValue();
12387
12388   SDLoc DL(N);
12389   EVT VT = N->getValueType(0);
12390   SmallVector<SDValue, 8> Ops;
12391
12392   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12393   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12394
12395   // Keep track of what we encounter.
12396   bool AnyInteger = false;
12397   bool AnyFP = false;
12398   for (const SDValue &Op : N->ops()) {
12399     if (ISD::BITCAST == Op.getOpcode() &&
12400         !Op.getOperand(0).getValueType().isVector())
12401       Ops.push_back(Op.getOperand(0));
12402     else if (ISD::UNDEF == Op.getOpcode())
12403       Ops.push_back(ScalarUndef);
12404     else
12405       return SDValue();
12406
12407     // Note whether we encounter an integer or floating point scalar.
12408     // If it's neither, bail out, it could be something weird like x86mmx.
12409     EVT LastOpVT = Ops.back().getValueType();
12410     if (LastOpVT.isFloatingPoint())
12411       AnyFP = true;
12412     else if (LastOpVT.isInteger())
12413       AnyInteger = true;
12414     else
12415       return SDValue();
12416   }
12417
12418   // If any of the operands is a floating point scalar bitcast to a vector,
12419   // use floating point types throughout, and bitcast everything.
12420   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12421   if (AnyFP) {
12422     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12423     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12424     if (AnyInteger) {
12425       for (SDValue &Op : Ops) {
12426         if (Op.getValueType() == SVT)
12427           continue;
12428         if (Op.getOpcode() == ISD::UNDEF)
12429           Op = ScalarUndef;
12430         else
12431           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12432       }
12433     }
12434   }
12435
12436   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12437                                VT.getSizeInBits() / SVT.getSizeInBits());
12438   return DAG.getNode(ISD::BITCAST, DL, VT,
12439                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12440 }
12441
12442 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12443 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12444 // most two distinct vectors the same size as the result, attempt to turn this
12445 // into a legal shuffle.
12446 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12447   EVT VT = N->getValueType(0);
12448   EVT OpVT = N->getOperand(0).getValueType();
12449   int NumElts = VT.getVectorNumElements();
12450   int NumOpElts = OpVT.getVectorNumElements();
12451
12452   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12453   SmallVector<int, 8> Mask;
12454
12455   for (SDValue Op : N->ops()) {
12456     // Peek through any bitcast.
12457     while (Op.getOpcode() == ISD::BITCAST)
12458       Op = Op.getOperand(0);
12459
12460     // UNDEF nodes convert to UNDEF shuffle mask values.
12461     if (Op.getOpcode() == ISD::UNDEF) {
12462       Mask.append((unsigned)NumOpElts, -1);
12463       continue;
12464     }
12465
12466     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12467       return SDValue();
12468
12469     // What vector are we extracting the subvector from and at what index?
12470     SDValue ExtVec = Op.getOperand(0);
12471
12472     // We want the EVT of the original extraction to correctly scale the
12473     // extraction index.
12474     EVT ExtVT = ExtVec.getValueType();
12475
12476     // Peek through any bitcast.
12477     while (ExtVec.getOpcode() == ISD::BITCAST)
12478       ExtVec = ExtVec.getOperand(0);
12479
12480     // UNDEF nodes convert to UNDEF shuffle mask values.
12481     if (ExtVec.getOpcode() == ISD::UNDEF) {
12482       Mask.append((unsigned)NumOpElts, -1);
12483       continue;
12484     }
12485
12486     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12487       return SDValue();
12488     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12489
12490     // Ensure that we are extracting a subvector from a vector the same
12491     // size as the result.
12492     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12493       return SDValue();
12494
12495     // Scale the subvector index to account for any bitcast.
12496     int NumExtElts = ExtVT.getVectorNumElements();
12497     if (0 == (NumExtElts % NumElts))
12498       ExtIdx /= (NumExtElts / NumElts);
12499     else if (0 == (NumElts % NumExtElts))
12500       ExtIdx *= (NumElts / NumExtElts);
12501     else
12502       return SDValue();
12503
12504     // At most we can reference 2 inputs in the final shuffle.
12505     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12506       SV0 = ExtVec;
12507       for (int i = 0; i != NumOpElts; ++i)
12508         Mask.push_back(i + ExtIdx);
12509     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12510       SV1 = ExtVec;
12511       for (int i = 0; i != NumOpElts; ++i)
12512         Mask.push_back(i + ExtIdx + NumElts);
12513     } else {
12514       return SDValue();
12515     }
12516   }
12517
12518   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12519     return SDValue();
12520
12521   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12522                               DAG.getBitcast(VT, SV1), Mask);
12523 }
12524
12525 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12526   // If we only have one input vector, we don't need to do any concatenation.
12527   if (N->getNumOperands() == 1)
12528     return N->getOperand(0);
12529
12530   // Check if all of the operands are undefs.
12531   EVT VT = N->getValueType(0);
12532   if (ISD::allOperandsUndef(N))
12533     return DAG.getUNDEF(VT);
12534
12535   // Optimize concat_vectors where all but the first of the vectors are undef.
12536   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12537         return Op.getOpcode() == ISD::UNDEF;
12538       })) {
12539     SDValue In = N->getOperand(0);
12540     assert(In.getValueType().isVector() && "Must concat vectors");
12541
12542     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12543     if (In->getOpcode() == ISD::BITCAST &&
12544         !In->getOperand(0)->getValueType(0).isVector()) {
12545       SDValue Scalar = In->getOperand(0);
12546
12547       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12548       // look through the trunc so we can still do the transform:
12549       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12550       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12551           !TLI.isTypeLegal(Scalar.getValueType()) &&
12552           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12553         Scalar = Scalar->getOperand(0);
12554
12555       EVT SclTy = Scalar->getValueType(0);
12556
12557       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12558         return SDValue();
12559
12560       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12561                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12562       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12563         return SDValue();
12564
12565       SDLoc dl = SDLoc(N);
12566       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12567       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12568     }
12569   }
12570
12571   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12572   // We have already tested above for an UNDEF only concatenation.
12573   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12574   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12575   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12576     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12577   };
12578   bool AllBuildVectorsOrUndefs =
12579       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12580   if (AllBuildVectorsOrUndefs) {
12581     SmallVector<SDValue, 8> Opnds;
12582     EVT SVT = VT.getScalarType();
12583
12584     EVT MinVT = SVT;
12585     if (!SVT.isFloatingPoint()) {
12586       // If BUILD_VECTOR are from built from integer, they may have different
12587       // operand types. Get the smallest type and truncate all operands to it.
12588       bool FoundMinVT = false;
12589       for (const SDValue &Op : N->ops())
12590         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12591           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12592           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12593           FoundMinVT = true;
12594         }
12595       assert(FoundMinVT && "Concat vector type mismatch");
12596     }
12597
12598     for (const SDValue &Op : N->ops()) {
12599       EVT OpVT = Op.getValueType();
12600       unsigned NumElts = OpVT.getVectorNumElements();
12601
12602       if (ISD::UNDEF == Op.getOpcode())
12603         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12604
12605       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12606         if (SVT.isFloatingPoint()) {
12607           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12608           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12609         } else {
12610           for (unsigned i = 0; i != NumElts; ++i)
12611             Opnds.push_back(
12612                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12613         }
12614       }
12615     }
12616
12617     assert(VT.getVectorNumElements() == Opnds.size() &&
12618            "Concat vector type mismatch");
12619     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12620   }
12621
12622   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12623   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12624     return V;
12625
12626   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12627   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12628     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12629       return V;
12630
12631   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12632   // nodes often generate nop CONCAT_VECTOR nodes.
12633   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12634   // place the incoming vectors at the exact same location.
12635   SDValue SingleSource = SDValue();
12636   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12637
12638   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12639     SDValue Op = N->getOperand(i);
12640
12641     if (Op.getOpcode() == ISD::UNDEF)
12642       continue;
12643
12644     // Check if this is the identity extract:
12645     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12646       return SDValue();
12647
12648     // Find the single incoming vector for the extract_subvector.
12649     if (SingleSource.getNode()) {
12650       if (Op.getOperand(0) != SingleSource)
12651         return SDValue();
12652     } else {
12653       SingleSource = Op.getOperand(0);
12654
12655       // Check the source type is the same as the type of the result.
12656       // If not, this concat may extend the vector, so we can not
12657       // optimize it away.
12658       if (SingleSource.getValueType() != N->getValueType(0))
12659         return SDValue();
12660     }
12661
12662     unsigned IdentityIndex = i * PartNumElem;
12663     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12664     // The extract index must be constant.
12665     if (!CS)
12666       return SDValue();
12667
12668     // Check that we are reading from the identity index.
12669     if (CS->getZExtValue() != IdentityIndex)
12670       return SDValue();
12671   }
12672
12673   if (SingleSource.getNode())
12674     return SingleSource;
12675
12676   return SDValue();
12677 }
12678
12679 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12680   EVT NVT = N->getValueType(0);
12681   SDValue V = N->getOperand(0);
12682
12683   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12684     // Combine:
12685     //    (extract_subvec (concat V1, V2, ...), i)
12686     // Into:
12687     //    Vi if possible
12688     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12689     // type.
12690     if (V->getOperand(0).getValueType() != NVT)
12691       return SDValue();
12692     unsigned Idx = N->getConstantOperandVal(1);
12693     unsigned NumElems = NVT.getVectorNumElements();
12694     assert((Idx % NumElems) == 0 &&
12695            "IDX in concat is not a multiple of the result vector length.");
12696     return V->getOperand(Idx / NumElems);
12697   }
12698
12699   // Skip bitcasting
12700   if (V->getOpcode() == ISD::BITCAST)
12701     V = V.getOperand(0);
12702
12703   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12704     SDLoc dl(N);
12705     // Handle only simple case where vector being inserted and vector
12706     // being extracted are of same type, and are half size of larger vectors.
12707     EVT BigVT = V->getOperand(0).getValueType();
12708     EVT SmallVT = V->getOperand(1).getValueType();
12709     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12710       return SDValue();
12711
12712     // Only handle cases where both indexes are constants with the same type.
12713     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12714     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12715
12716     if (InsIdx && ExtIdx &&
12717         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12718         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12719       // Combine:
12720       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12721       // Into:
12722       //    indices are equal or bit offsets are equal => V1
12723       //    otherwise => (extract_subvec V1, ExtIdx)
12724       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12725           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12726         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12727       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12728                          DAG.getNode(ISD::BITCAST, dl,
12729                                      N->getOperand(0).getValueType(),
12730                                      V->getOperand(0)), N->getOperand(1));
12731     }
12732   }
12733
12734   return SDValue();
12735 }
12736
12737 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12738                                                  SDValue V, SelectionDAG &DAG) {
12739   SDLoc DL(V);
12740   EVT VT = V.getValueType();
12741
12742   switch (V.getOpcode()) {
12743   default:
12744     return V;
12745
12746   case ISD::CONCAT_VECTORS: {
12747     EVT OpVT = V->getOperand(0).getValueType();
12748     int OpSize = OpVT.getVectorNumElements();
12749     SmallBitVector OpUsedElements(OpSize, false);
12750     bool FoundSimplification = false;
12751     SmallVector<SDValue, 4> NewOps;
12752     NewOps.reserve(V->getNumOperands());
12753     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12754       SDValue Op = V->getOperand(i);
12755       bool OpUsed = false;
12756       for (int j = 0; j < OpSize; ++j)
12757         if (UsedElements[i * OpSize + j]) {
12758           OpUsedElements[j] = true;
12759           OpUsed = true;
12760         }
12761       NewOps.push_back(
12762           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12763                  : DAG.getUNDEF(OpVT));
12764       FoundSimplification |= Op == NewOps.back();
12765       OpUsedElements.reset();
12766     }
12767     if (FoundSimplification)
12768       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12769     return V;
12770   }
12771
12772   case ISD::INSERT_SUBVECTOR: {
12773     SDValue BaseV = V->getOperand(0);
12774     SDValue SubV = V->getOperand(1);
12775     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12776     if (!IdxN)
12777       return V;
12778
12779     int SubSize = SubV.getValueType().getVectorNumElements();
12780     int Idx = IdxN->getZExtValue();
12781     bool SubVectorUsed = false;
12782     SmallBitVector SubUsedElements(SubSize, false);
12783     for (int i = 0; i < SubSize; ++i)
12784       if (UsedElements[i + Idx]) {
12785         SubVectorUsed = true;
12786         SubUsedElements[i] = true;
12787         UsedElements[i + Idx] = false;
12788       }
12789
12790     // Now recurse on both the base and sub vectors.
12791     SDValue SimplifiedSubV =
12792         SubVectorUsed
12793             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12794             : DAG.getUNDEF(SubV.getValueType());
12795     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12796     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12797       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12798                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12799     return V;
12800   }
12801   }
12802 }
12803
12804 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12805                                        SDValue N1, SelectionDAG &DAG) {
12806   EVT VT = SVN->getValueType(0);
12807   int NumElts = VT.getVectorNumElements();
12808   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12809   for (int M : SVN->getMask())
12810     if (M >= 0 && M < NumElts)
12811       N0UsedElements[M] = true;
12812     else if (M >= NumElts)
12813       N1UsedElements[M - NumElts] = true;
12814
12815   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12816   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12817   if (S0 == N0 && S1 == N1)
12818     return SDValue();
12819
12820   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12821 }
12822
12823 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12824 // or turn a shuffle of a single concat into simpler shuffle then concat.
12825 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12826   EVT VT = N->getValueType(0);
12827   unsigned NumElts = VT.getVectorNumElements();
12828
12829   SDValue N0 = N->getOperand(0);
12830   SDValue N1 = N->getOperand(1);
12831   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12832
12833   SmallVector<SDValue, 4> Ops;
12834   EVT ConcatVT = N0.getOperand(0).getValueType();
12835   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12836   unsigned NumConcats = NumElts / NumElemsPerConcat;
12837
12838   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12839   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12840   // half vector elements.
12841   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12842       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12843                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12844     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12845                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
12846     N1 = DAG.getUNDEF(ConcatVT);
12847     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12848   }
12849
12850   // Look at every vector that's inserted. We're looking for exact
12851   // subvector-sized copies from a concatenated vector
12852   for (unsigned I = 0; I != NumConcats; ++I) {
12853     // Make sure we're dealing with a copy.
12854     unsigned Begin = I * NumElemsPerConcat;
12855     bool AllUndef = true, NoUndef = true;
12856     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12857       if (SVN->getMaskElt(J) >= 0)
12858         AllUndef = false;
12859       else
12860         NoUndef = false;
12861     }
12862
12863     if (NoUndef) {
12864       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12865         return SDValue();
12866
12867       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12868         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12869           return SDValue();
12870
12871       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12872       if (FirstElt < N0.getNumOperands())
12873         Ops.push_back(N0.getOperand(FirstElt));
12874       else
12875         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12876
12877     } else if (AllUndef) {
12878       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12879     } else { // Mixed with general masks and undefs, can't do optimization.
12880       return SDValue();
12881     }
12882   }
12883
12884   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12885 }
12886
12887 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12888   EVT VT = N->getValueType(0);
12889   unsigned NumElts = VT.getVectorNumElements();
12890
12891   SDValue N0 = N->getOperand(0);
12892   SDValue N1 = N->getOperand(1);
12893
12894   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12895
12896   // Canonicalize shuffle undef, undef -> undef
12897   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12898     return DAG.getUNDEF(VT);
12899
12900   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12901
12902   // Canonicalize shuffle v, v -> v, undef
12903   if (N0 == N1) {
12904     SmallVector<int, 8> NewMask;
12905     for (unsigned i = 0; i != NumElts; ++i) {
12906       int Idx = SVN->getMaskElt(i);
12907       if (Idx >= (int)NumElts) Idx -= NumElts;
12908       NewMask.push_back(Idx);
12909     }
12910     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12911                                 &NewMask[0]);
12912   }
12913
12914   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12915   if (N0.getOpcode() == ISD::UNDEF) {
12916     SmallVector<int, 8> NewMask;
12917     for (unsigned i = 0; i != NumElts; ++i) {
12918       int Idx = SVN->getMaskElt(i);
12919       if (Idx >= 0) {
12920         if (Idx >= (int)NumElts)
12921           Idx -= NumElts;
12922         else
12923           Idx = -1; // remove reference to lhs
12924       }
12925       NewMask.push_back(Idx);
12926     }
12927     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12928                                 &NewMask[0]);
12929   }
12930
12931   // Remove references to rhs if it is undef
12932   if (N1.getOpcode() == ISD::UNDEF) {
12933     bool Changed = false;
12934     SmallVector<int, 8> NewMask;
12935     for (unsigned i = 0; i != NumElts; ++i) {
12936       int Idx = SVN->getMaskElt(i);
12937       if (Idx >= (int)NumElts) {
12938         Idx = -1;
12939         Changed = true;
12940       }
12941       NewMask.push_back(Idx);
12942     }
12943     if (Changed)
12944       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12945   }
12946
12947   // If it is a splat, check if the argument vector is another splat or a
12948   // build_vector.
12949   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12950     SDNode *V = N0.getNode();
12951
12952     // If this is a bit convert that changes the element type of the vector but
12953     // not the number of vector elements, look through it.  Be careful not to
12954     // look though conversions that change things like v4f32 to v2f64.
12955     if (V->getOpcode() == ISD::BITCAST) {
12956       SDValue ConvInput = V->getOperand(0);
12957       if (ConvInput.getValueType().isVector() &&
12958           ConvInput.getValueType().getVectorNumElements() == NumElts)
12959         V = ConvInput.getNode();
12960     }
12961
12962     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12963       assert(V->getNumOperands() == NumElts &&
12964              "BUILD_VECTOR has wrong number of operands");
12965       SDValue Base;
12966       bool AllSame = true;
12967       for (unsigned i = 0; i != NumElts; ++i) {
12968         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12969           Base = V->getOperand(i);
12970           break;
12971         }
12972       }
12973       // Splat of <u, u, u, u>, return <u, u, u, u>
12974       if (!Base.getNode())
12975         return N0;
12976       for (unsigned i = 0; i != NumElts; ++i) {
12977         if (V->getOperand(i) != Base) {
12978           AllSame = false;
12979           break;
12980         }
12981       }
12982       // Splat of <x, x, x, x>, return <x, x, x, x>
12983       if (AllSame)
12984         return N0;
12985
12986       // Canonicalize any other splat as a build_vector.
12987       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12988       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12989       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12990                                   V->getValueType(0), Ops);
12991
12992       // We may have jumped through bitcasts, so the type of the
12993       // BUILD_VECTOR may not match the type of the shuffle.
12994       if (V->getValueType(0) != VT)
12995         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12996       return NewBV;
12997     }
12998   }
12999
13000   // There are various patterns used to build up a vector from smaller vectors,
13001   // subvectors, or elements. Scan chains of these and replace unused insertions
13002   // or components with undef.
13003   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13004     return S;
13005
13006   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13007       Level < AfterLegalizeVectorOps &&
13008       (N1.getOpcode() == ISD::UNDEF ||
13009       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13010        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13011     SDValue V = partitionShuffleOfConcats(N, DAG);
13012
13013     if (V.getNode())
13014       return V;
13015   }
13016
13017   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13018   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13019   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13020     SmallVector<SDValue, 8> Ops;
13021     for (int M : SVN->getMask()) {
13022       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13023       if (M >= 0) {
13024         int Idx = M % NumElts;
13025         SDValue &S = (M < (int)NumElts ? N0 : N1);
13026         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13027           Op = S.getOperand(Idx);
13028         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13029           if (Idx == 0)
13030             Op = S.getOperand(0);
13031         } else {
13032           // Operand can't be combined - bail out.
13033           break;
13034         }
13035       }
13036       Ops.push_back(Op);
13037     }
13038     if (Ops.size() == VT.getVectorNumElements()) {
13039       // BUILD_VECTOR requires all inputs to be of the same type, find the
13040       // maximum type and extend them all.
13041       EVT SVT = VT.getScalarType();
13042       if (SVT.isInteger())
13043         for (SDValue &Op : Ops)
13044           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13045       if (SVT != VT.getScalarType())
13046         for (SDValue &Op : Ops)
13047           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13048                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13049                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13050       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13051     }
13052   }
13053
13054   // If this shuffle only has a single input that is a bitcasted shuffle,
13055   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13056   // back to their original types.
13057   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13058       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13059       TLI.isTypeLegal(VT)) {
13060
13061     // Peek through the bitcast only if there is one user.
13062     SDValue BC0 = N0;
13063     while (BC0.getOpcode() == ISD::BITCAST) {
13064       if (!BC0.hasOneUse())
13065         break;
13066       BC0 = BC0.getOperand(0);
13067     }
13068
13069     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13070       if (Scale == 1)
13071         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13072
13073       SmallVector<int, 8> NewMask;
13074       for (int M : Mask)
13075         for (int s = 0; s != Scale; ++s)
13076           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13077       return NewMask;
13078     };
13079
13080     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13081       EVT SVT = VT.getScalarType();
13082       EVT InnerVT = BC0->getValueType(0);
13083       EVT InnerSVT = InnerVT.getScalarType();
13084
13085       // Determine which shuffle works with the smaller scalar type.
13086       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13087       EVT ScaleSVT = ScaleVT.getScalarType();
13088
13089       if (TLI.isTypeLegal(ScaleVT) &&
13090           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13091           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13092
13093         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13094         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13095
13096         // Scale the shuffle masks to the smaller scalar type.
13097         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13098         SmallVector<int, 8> InnerMask =
13099             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13100         SmallVector<int, 8> OuterMask =
13101             ScaleShuffleMask(SVN->getMask(), OuterScale);
13102
13103         // Merge the shuffle masks.
13104         SmallVector<int, 8> NewMask;
13105         for (int M : OuterMask)
13106           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13107
13108         // Test for shuffle mask legality over both commutations.
13109         SDValue SV0 = BC0->getOperand(0);
13110         SDValue SV1 = BC0->getOperand(1);
13111         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13112         if (!LegalMask) {
13113           std::swap(SV0, SV1);
13114           ShuffleVectorSDNode::commuteMask(NewMask);
13115           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13116         }
13117
13118         if (LegalMask) {
13119           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13120           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13121           return DAG.getNode(
13122               ISD::BITCAST, SDLoc(N), VT,
13123               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13124         }
13125       }
13126     }
13127   }
13128
13129   // Canonicalize shuffles according to rules:
13130   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13131   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13132   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13133   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13134       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13135       TLI.isTypeLegal(VT)) {
13136     // The incoming shuffle must be of the same type as the result of the
13137     // current shuffle.
13138     assert(N1->getOperand(0).getValueType() == VT &&
13139            "Shuffle types don't match");
13140
13141     SDValue SV0 = N1->getOperand(0);
13142     SDValue SV1 = N1->getOperand(1);
13143     bool HasSameOp0 = N0 == SV0;
13144     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13145     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13146       // Commute the operands of this shuffle so that next rule
13147       // will trigger.
13148       return DAG.getCommutedVectorShuffle(*SVN);
13149   }
13150
13151   // Try to fold according to rules:
13152   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13153   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13154   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13155   // Don't try to fold shuffles with illegal type.
13156   // Only fold if this shuffle is the only user of the other shuffle.
13157   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13158       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13159     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13160
13161     // The incoming shuffle must be of the same type as the result of the
13162     // current shuffle.
13163     assert(OtherSV->getOperand(0).getValueType() == VT &&
13164            "Shuffle types don't match");
13165
13166     SDValue SV0, SV1;
13167     SmallVector<int, 4> Mask;
13168     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13169     // operand, and SV1 as the second operand.
13170     for (unsigned i = 0; i != NumElts; ++i) {
13171       int Idx = SVN->getMaskElt(i);
13172       if (Idx < 0) {
13173         // Propagate Undef.
13174         Mask.push_back(Idx);
13175         continue;
13176       }
13177
13178       SDValue CurrentVec;
13179       if (Idx < (int)NumElts) {
13180         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13181         // shuffle mask to identify which vector is actually referenced.
13182         Idx = OtherSV->getMaskElt(Idx);
13183         if (Idx < 0) {
13184           // Propagate Undef.
13185           Mask.push_back(Idx);
13186           continue;
13187         }
13188
13189         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13190                                            : OtherSV->getOperand(1);
13191       } else {
13192         // This shuffle index references an element within N1.
13193         CurrentVec = N1;
13194       }
13195
13196       // Simple case where 'CurrentVec' is UNDEF.
13197       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13198         Mask.push_back(-1);
13199         continue;
13200       }
13201
13202       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13203       // will be the first or second operand of the combined shuffle.
13204       Idx = Idx % NumElts;
13205       if (!SV0.getNode() || SV0 == CurrentVec) {
13206         // Ok. CurrentVec is the left hand side.
13207         // Update the mask accordingly.
13208         SV0 = CurrentVec;
13209         Mask.push_back(Idx);
13210         continue;
13211       }
13212
13213       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13214       if (SV1.getNode() && SV1 != CurrentVec)
13215         return SDValue();
13216
13217       // Ok. CurrentVec is the right hand side.
13218       // Update the mask accordingly.
13219       SV1 = CurrentVec;
13220       Mask.push_back(Idx + NumElts);
13221     }
13222
13223     // Check if all indices in Mask are Undef. In case, propagate Undef.
13224     bool isUndefMask = true;
13225     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13226       isUndefMask &= Mask[i] < 0;
13227
13228     if (isUndefMask)
13229       return DAG.getUNDEF(VT);
13230
13231     if (!SV0.getNode())
13232       SV0 = DAG.getUNDEF(VT);
13233     if (!SV1.getNode())
13234       SV1 = DAG.getUNDEF(VT);
13235
13236     // Avoid introducing shuffles with illegal mask.
13237     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13238       ShuffleVectorSDNode::commuteMask(Mask);
13239
13240       if (!TLI.isShuffleMaskLegal(Mask, VT))
13241         return SDValue();
13242
13243       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13244       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13245       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13246       std::swap(SV0, SV1);
13247     }
13248
13249     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13250     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13251     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13252     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13253   }
13254
13255   return SDValue();
13256 }
13257
13258 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13259   SDValue InVal = N->getOperand(0);
13260   EVT VT = N->getValueType(0);
13261
13262   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13263   // with a VECTOR_SHUFFLE.
13264   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13265     SDValue InVec = InVal->getOperand(0);
13266     SDValue EltNo = InVal->getOperand(1);
13267
13268     // FIXME: We could support implicit truncation if the shuffle can be
13269     // scaled to a smaller vector scalar type.
13270     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13271     if (C0 && VT == InVec.getValueType() &&
13272         VT.getScalarType() == InVal.getValueType()) {
13273       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13274       int Elt = C0->getZExtValue();
13275       NewMask[0] = Elt;
13276
13277       if (TLI.isShuffleMaskLegal(NewMask, VT))
13278         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13279                                     NewMask);
13280     }
13281   }
13282
13283   return SDValue();
13284 }
13285
13286 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13287   SDValue N0 = N->getOperand(0);
13288   SDValue N2 = N->getOperand(2);
13289
13290   // If the input vector is a concatenation, and the insert replaces
13291   // one of the halves, we can optimize into a single concat_vectors.
13292   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13293       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13294     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13295     EVT VT = N->getValueType(0);
13296
13297     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13298     // (concat_vectors Z, Y)
13299     if (InsIdx == 0)
13300       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13301                          N->getOperand(1), N0.getOperand(1));
13302
13303     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13304     // (concat_vectors X, Z)
13305     if (InsIdx == VT.getVectorNumElements()/2)
13306       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13307                          N0.getOperand(0), N->getOperand(1));
13308   }
13309
13310   return SDValue();
13311 }
13312
13313 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13314   SDValue N0 = N->getOperand(0);
13315
13316   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13317   if (N0->getOpcode() == ISD::FP16_TO_FP)
13318     return N0->getOperand(0);
13319
13320   return SDValue();
13321 }
13322
13323 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13324   SDValue N0 = N->getOperand(0);
13325
13326   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13327   if (N0->getOpcode() == ISD::AND) {
13328     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13329     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13330       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13331                          N0.getOperand(0));
13332     }
13333   }
13334
13335   return SDValue();
13336 }
13337
13338 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13339 /// with the destination vector and a zero vector.
13340 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13341 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13342 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13343   EVT VT = N->getValueType(0);
13344   SDValue LHS = N->getOperand(0);
13345   SDValue RHS = N->getOperand(1);
13346   SDLoc dl(N);
13347
13348   // Make sure we're not running after operation legalization where it
13349   // may have custom lowered the vector shuffles.
13350   if (LegalOperations)
13351     return SDValue();
13352
13353   if (N->getOpcode() != ISD::AND)
13354     return SDValue();
13355
13356   if (RHS.getOpcode() == ISD::BITCAST)
13357     RHS = RHS.getOperand(0);
13358
13359   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13360     return SDValue();
13361
13362   EVT RVT = RHS.getValueType();
13363   unsigned NumElts = RHS.getNumOperands();
13364
13365   // Attempt to create a valid clear mask, splitting the mask into
13366   // sub elements and checking to see if each is
13367   // all zeros or all ones - suitable for shuffle masking.
13368   auto BuildClearMask = [&](int Split) {
13369     int NumSubElts = NumElts * Split;
13370     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13371
13372     SmallVector<int, 8> Indices;
13373     for (int i = 0; i != NumSubElts; ++i) {
13374       int EltIdx = i / Split;
13375       int SubIdx = i % Split;
13376       SDValue Elt = RHS.getOperand(EltIdx);
13377       if (Elt.getOpcode() == ISD::UNDEF) {
13378         Indices.push_back(-1);
13379         continue;
13380       }
13381
13382       APInt Bits;
13383       if (isa<ConstantSDNode>(Elt))
13384         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13385       else if (isa<ConstantFPSDNode>(Elt))
13386         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13387       else
13388         return SDValue();
13389
13390       // Extract the sub element from the constant bit mask.
13391       if (DAG.getDataLayout().isBigEndian()) {
13392         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13393       } else {
13394         Bits = Bits.lshr(SubIdx * NumSubBits);
13395       }
13396
13397       if (Split > 1)
13398         Bits = Bits.trunc(NumSubBits);
13399
13400       if (Bits.isAllOnesValue())
13401         Indices.push_back(i);
13402       else if (Bits == 0)
13403         Indices.push_back(i + NumSubElts);
13404       else
13405         return SDValue();
13406     }
13407
13408     // Let's see if the target supports this vector_shuffle.
13409     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13410     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13411     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13412       return SDValue();
13413
13414     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13415     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13416                                                    DAG.getBitcast(ClearVT, LHS),
13417                                                    Zero, &Indices[0]));
13418   };
13419
13420   // Determine maximum split level (byte level masking).
13421   int MaxSplit = 1;
13422   if (RVT.getScalarSizeInBits() % 8 == 0)
13423     MaxSplit = RVT.getScalarSizeInBits() / 8;
13424
13425   for (int Split = 1; Split <= MaxSplit; ++Split)
13426     if (RVT.getScalarSizeInBits() % Split == 0)
13427       if (SDValue S = BuildClearMask(Split))
13428         return S;
13429
13430   return SDValue();
13431 }
13432
13433 /// Visit a binary vector operation, like ADD.
13434 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13435   assert(N->getValueType(0).isVector() &&
13436          "SimplifyVBinOp only works on vectors!");
13437
13438   SDValue LHS = N->getOperand(0);
13439   SDValue RHS = N->getOperand(1);
13440   SDValue Ops[] = {LHS, RHS};
13441
13442   // See if we can constant fold the vector operation.
13443   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13444           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13445     return Fold;
13446
13447   // Try to convert a constant mask AND into a shuffle clear mask.
13448   if (SDValue Shuffle = XformToShuffleWithZero(N))
13449     return Shuffle;
13450
13451   // Type legalization might introduce new shuffles in the DAG.
13452   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13453   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13454   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13455       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13456       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13457       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13458     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13459     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13460
13461     if (SVN0->getMask().equals(SVN1->getMask())) {
13462       EVT VT = N->getValueType(0);
13463       SDValue UndefVector = LHS.getOperand(1);
13464       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13465                                      LHS.getOperand(0), RHS.getOperand(0),
13466                                      N->getFlags());
13467       AddUsersToWorklist(N);
13468       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13469                                   &SVN0->getMask()[0]);
13470     }
13471   }
13472
13473   return SDValue();
13474 }
13475
13476 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13477                                     SDValue N1, SDValue N2){
13478   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13479
13480   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13481                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13482
13483   // If we got a simplified select_cc node back from SimplifySelectCC, then
13484   // break it down into a new SETCC node, and a new SELECT node, and then return
13485   // the SELECT node, since we were called with a SELECT node.
13486   if (SCC.getNode()) {
13487     // Check to see if we got a select_cc back (to turn into setcc/select).
13488     // Otherwise, just return whatever node we got back, like fabs.
13489     if (SCC.getOpcode() == ISD::SELECT_CC) {
13490       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13491                                   N0.getValueType(),
13492                                   SCC.getOperand(0), SCC.getOperand(1),
13493                                   SCC.getOperand(4));
13494       AddToWorklist(SETCC.getNode());
13495       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13496                            SCC.getOperand(2), SCC.getOperand(3));
13497     }
13498
13499     return SCC;
13500   }
13501   return SDValue();
13502 }
13503
13504 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13505 /// being selected between, see if we can simplify the select.  Callers of this
13506 /// should assume that TheSelect is deleted if this returns true.  As such, they
13507 /// should return the appropriate thing (e.g. the node) back to the top-level of
13508 /// the DAG combiner loop to avoid it being looked at.
13509 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13510                                     SDValue RHS) {
13511
13512   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13513   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13514   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13515     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13516       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13517       SDValue Sqrt = RHS;
13518       ISD::CondCode CC;
13519       SDValue CmpLHS;
13520       const ConstantFPSDNode *NegZero = nullptr;
13521
13522       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13523         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13524         CmpLHS = TheSelect->getOperand(0);
13525         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13526       } else {
13527         // SELECT or VSELECT
13528         SDValue Cmp = TheSelect->getOperand(0);
13529         if (Cmp.getOpcode() == ISD::SETCC) {
13530           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13531           CmpLHS = Cmp.getOperand(0);
13532           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13533         }
13534       }
13535       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13536           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13537           CC == ISD::SETULT || CC == ISD::SETLT)) {
13538         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13539         CombineTo(TheSelect, Sqrt);
13540         return true;
13541       }
13542     }
13543   }
13544   // Cannot simplify select with vector condition
13545   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13546
13547   // If this is a select from two identical things, try to pull the operation
13548   // through the select.
13549   if (LHS.getOpcode() != RHS.getOpcode() ||
13550       !LHS.hasOneUse() || !RHS.hasOneUse())
13551     return false;
13552
13553   // If this is a load and the token chain is identical, replace the select
13554   // of two loads with a load through a select of the address to load from.
13555   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13556   // constants have been dropped into the constant pool.
13557   if (LHS.getOpcode() == ISD::LOAD) {
13558     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13559     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13560
13561     // Token chains must be identical.
13562     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13563         // Do not let this transformation reduce the number of volatile loads.
13564         LLD->isVolatile() || RLD->isVolatile() ||
13565         // FIXME: If either is a pre/post inc/dec load,
13566         // we'd need to split out the address adjustment.
13567         LLD->isIndexed() || RLD->isIndexed() ||
13568         // If this is an EXTLOAD, the VT's must match.
13569         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13570         // If this is an EXTLOAD, the kind of extension must match.
13571         (LLD->getExtensionType() != RLD->getExtensionType() &&
13572          // The only exception is if one of the extensions is anyext.
13573          LLD->getExtensionType() != ISD::EXTLOAD &&
13574          RLD->getExtensionType() != ISD::EXTLOAD) ||
13575         // FIXME: this discards src value information.  This is
13576         // over-conservative. It would be beneficial to be able to remember
13577         // both potential memory locations.  Since we are discarding
13578         // src value info, don't do the transformation if the memory
13579         // locations are not in the default address space.
13580         LLD->getPointerInfo().getAddrSpace() != 0 ||
13581         RLD->getPointerInfo().getAddrSpace() != 0 ||
13582         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13583                                       LLD->getBasePtr().getValueType()))
13584       return false;
13585
13586     // Check that the select condition doesn't reach either load.  If so,
13587     // folding this will induce a cycle into the DAG.  If not, this is safe to
13588     // xform, so create a select of the addresses.
13589     SDValue Addr;
13590     if (TheSelect->getOpcode() == ISD::SELECT) {
13591       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13592       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13593           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13594         return false;
13595       // The loads must not depend on one another.
13596       if (LLD->isPredecessorOf(RLD) ||
13597           RLD->isPredecessorOf(LLD))
13598         return false;
13599       Addr = DAG.getSelect(SDLoc(TheSelect),
13600                            LLD->getBasePtr().getValueType(),
13601                            TheSelect->getOperand(0), LLD->getBasePtr(),
13602                            RLD->getBasePtr());
13603     } else {  // Otherwise SELECT_CC
13604       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13605       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13606
13607       if ((LLD->hasAnyUseOfValue(1) &&
13608            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13609           (RLD->hasAnyUseOfValue(1) &&
13610            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13611         return false;
13612
13613       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13614                          LLD->getBasePtr().getValueType(),
13615                          TheSelect->getOperand(0),
13616                          TheSelect->getOperand(1),
13617                          LLD->getBasePtr(), RLD->getBasePtr(),
13618                          TheSelect->getOperand(4));
13619     }
13620
13621     SDValue Load;
13622     // It is safe to replace the two loads if they have different alignments,
13623     // but the new load must be the minimum (most restrictive) alignment of the
13624     // inputs.
13625     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13626     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13627     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13628       Load = DAG.getLoad(TheSelect->getValueType(0),
13629                          SDLoc(TheSelect),
13630                          // FIXME: Discards pointer and AA info.
13631                          LLD->getChain(), Addr, MachinePointerInfo(),
13632                          LLD->isVolatile(), LLD->isNonTemporal(),
13633                          isInvariant, Alignment);
13634     } else {
13635       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13636                             RLD->getExtensionType() : LLD->getExtensionType(),
13637                             SDLoc(TheSelect),
13638                             TheSelect->getValueType(0),
13639                             // FIXME: Discards pointer and AA info.
13640                             LLD->getChain(), Addr, MachinePointerInfo(),
13641                             LLD->getMemoryVT(), LLD->isVolatile(),
13642                             LLD->isNonTemporal(), isInvariant, Alignment);
13643     }
13644
13645     // Users of the select now use the result of the load.
13646     CombineTo(TheSelect, Load);
13647
13648     // Users of the old loads now use the new load's chain.  We know the
13649     // old-load value is dead now.
13650     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13651     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13652     return true;
13653   }
13654
13655   return false;
13656 }
13657
13658 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13659 /// where 'cond' is the comparison specified by CC.
13660 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13661                                       SDValue N2, SDValue N3,
13662                                       ISD::CondCode CC, bool NotExtCompare) {
13663   // (x ? y : y) -> y.
13664   if (N2 == N3) return N2;
13665
13666   EVT VT = N2.getValueType();
13667   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13668   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13669
13670   // Determine if the condition we're dealing with is constant
13671   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13672                               N0, N1, CC, DL, false);
13673   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13674
13675   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13676     // fold select_cc true, x, y -> x
13677     // fold select_cc false, x, y -> y
13678     return !SCCC->isNullValue() ? N2 : N3;
13679   }
13680
13681   // Check to see if we can simplify the select into an fabs node
13682   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13683     // Allow either -0.0 or 0.0
13684     if (CFP->isZero()) {
13685       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13686       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13687           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13688           N2 == N3.getOperand(0))
13689         return DAG.getNode(ISD::FABS, DL, VT, N0);
13690
13691       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13692       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13693           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13694           N2.getOperand(0) == N3)
13695         return DAG.getNode(ISD::FABS, DL, VT, N3);
13696     }
13697   }
13698
13699   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13700   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13701   // in it.  This is a win when the constant is not otherwise available because
13702   // it replaces two constant pool loads with one.  We only do this if the FP
13703   // type is known to be legal, because if it isn't, then we are before legalize
13704   // types an we want the other legalization to happen first (e.g. to avoid
13705   // messing with soft float) and if the ConstantFP is not legal, because if
13706   // it is legal, we may not need to store the FP constant in a constant pool.
13707   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13708     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13709       if (TLI.isTypeLegal(N2.getValueType()) &&
13710           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13711                TargetLowering::Legal &&
13712            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13713            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13714           // If both constants have multiple uses, then we won't need to do an
13715           // extra load, they are likely around in registers for other users.
13716           (TV->hasOneUse() || FV->hasOneUse())) {
13717         Constant *Elts[] = {
13718           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13719           const_cast<ConstantFP*>(TV->getConstantFPValue())
13720         };
13721         Type *FPTy = Elts[0]->getType();
13722         const DataLayout &TD = DAG.getDataLayout();
13723
13724         // Create a ConstantArray of the two constants.
13725         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13726         SDValue CPIdx =
13727             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13728                                 TD.getPrefTypeAlignment(FPTy));
13729         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13730
13731         // Get the offsets to the 0 and 1 element of the array so that we can
13732         // select between them.
13733         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13734         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13735         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13736
13737         SDValue Cond = DAG.getSetCC(DL,
13738                                     getSetCCResultType(N0.getValueType()),
13739                                     N0, N1, CC);
13740         AddToWorklist(Cond.getNode());
13741         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13742                                           Cond, One, Zero);
13743         AddToWorklist(CstOffset.getNode());
13744         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13745                             CstOffset);
13746         AddToWorklist(CPIdx.getNode());
13747         return DAG.getLoad(
13748             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13749             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13750             false, false, false, Alignment);
13751       }
13752     }
13753
13754   // Check to see if we can perform the "gzip trick", transforming
13755   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13756   if (isNullConstant(N3) && CC == ISD::SETLT &&
13757       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13758        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13759     EVT XType = N0.getValueType();
13760     EVT AType = N2.getValueType();
13761     if (XType.bitsGE(AType)) {
13762       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13763       // single-bit constant.
13764       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13765         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13766         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13767         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13768                                        getShiftAmountTy(N0.getValueType()));
13769         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13770                                     XType, N0, ShCt);
13771         AddToWorklist(Shift.getNode());
13772
13773         if (XType.bitsGT(AType)) {
13774           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13775           AddToWorklist(Shift.getNode());
13776         }
13777
13778         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13779       }
13780
13781       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13782                                   XType, N0,
13783                                   DAG.getConstant(XType.getSizeInBits() - 1,
13784                                                   SDLoc(N0),
13785                                          getShiftAmountTy(N0.getValueType())));
13786       AddToWorklist(Shift.getNode());
13787
13788       if (XType.bitsGT(AType)) {
13789         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13790         AddToWorklist(Shift.getNode());
13791       }
13792
13793       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13794     }
13795   }
13796
13797   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13798   // where y is has a single bit set.
13799   // A plaintext description would be, we can turn the SELECT_CC into an AND
13800   // when the condition can be materialized as an all-ones register.  Any
13801   // single bit-test can be materialized as an all-ones register with
13802   // shift-left and shift-right-arith.
13803   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13804       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13805     SDValue AndLHS = N0->getOperand(0);
13806     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13807     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13808       // Shift the tested bit over the sign bit.
13809       APInt AndMask = ConstAndRHS->getAPIntValue();
13810       SDValue ShlAmt =
13811         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13812                         getShiftAmountTy(AndLHS.getValueType()));
13813       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13814
13815       // Now arithmetic right shift it all the way over, so the result is either
13816       // all-ones, or zero.
13817       SDValue ShrAmt =
13818         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13819                         getShiftAmountTy(Shl.getValueType()));
13820       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13821
13822       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13823     }
13824   }
13825
13826   // fold select C, 16, 0 -> shl C, 4
13827   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13828       TLI.getBooleanContents(N0.getValueType()) ==
13829           TargetLowering::ZeroOrOneBooleanContent) {
13830
13831     // If the caller doesn't want us to simplify this into a zext of a compare,
13832     // don't do it.
13833     if (NotExtCompare && N2C->isOne())
13834       return SDValue();
13835
13836     // Get a SetCC of the condition
13837     // NOTE: Don't create a SETCC if it's not legal on this target.
13838     if (!LegalOperations ||
13839         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13840       SDValue Temp, SCC;
13841       // cast from setcc result type to select result type
13842       if (LegalTypes) {
13843         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13844                             N0, N1, CC);
13845         if (N2.getValueType().bitsLT(SCC.getValueType()))
13846           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13847                                         N2.getValueType());
13848         else
13849           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13850                              N2.getValueType(), SCC);
13851       } else {
13852         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13853         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13854                            N2.getValueType(), SCC);
13855       }
13856
13857       AddToWorklist(SCC.getNode());
13858       AddToWorklist(Temp.getNode());
13859
13860       if (N2C->isOne())
13861         return Temp;
13862
13863       // shl setcc result by log2 n2c
13864       return DAG.getNode(
13865           ISD::SHL, DL, N2.getValueType(), Temp,
13866           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13867                           getShiftAmountTy(Temp.getValueType())));
13868     }
13869   }
13870
13871   // Check to see if this is an integer abs.
13872   // select_cc setg[te] X,  0,  X, -X ->
13873   // select_cc setgt    X, -1,  X, -X ->
13874   // select_cc setl[te] X,  0, -X,  X ->
13875   // select_cc setlt    X,  1, -X,  X ->
13876   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13877   if (N1C) {
13878     ConstantSDNode *SubC = nullptr;
13879     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13880          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13881         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13882       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13883     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13884               (N1C->isOne() && CC == ISD::SETLT)) &&
13885              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13886       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13887
13888     EVT XType = N0.getValueType();
13889     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13890       SDLoc DL(N0);
13891       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13892                                   N0,
13893                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13894                                          getShiftAmountTy(N0.getValueType())));
13895       SDValue Add = DAG.getNode(ISD::ADD, DL,
13896                                 XType, N0, Shift);
13897       AddToWorklist(Shift.getNode());
13898       AddToWorklist(Add.getNode());
13899       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13900     }
13901   }
13902
13903   return SDValue();
13904 }
13905
13906 /// This is a stub for TargetLowering::SimplifySetCC.
13907 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13908                                    SDValue N1, ISD::CondCode Cond,
13909                                    SDLoc DL, bool foldBooleans) {
13910   TargetLowering::DAGCombinerInfo
13911     DagCombineInfo(DAG, Level, false, this);
13912   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13913 }
13914
13915 /// Given an ISD::SDIV node expressing a divide by constant, return
13916 /// a DAG expression to select that will generate the same value by multiplying
13917 /// by a magic number.
13918 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13919 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13920   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13921   if (!C)
13922     return SDValue();
13923
13924   // Avoid division by zero.
13925   if (C->isNullValue())
13926     return SDValue();
13927
13928   std::vector<SDNode*> Built;
13929   SDValue S =
13930       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13931
13932   for (SDNode *N : Built)
13933     AddToWorklist(N);
13934   return S;
13935 }
13936
13937 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13938 /// DAG expression that will generate the same value by right shifting.
13939 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13940   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13941   if (!C)
13942     return SDValue();
13943
13944   // Avoid division by zero.
13945   if (C->isNullValue())
13946     return SDValue();
13947
13948   std::vector<SDNode *> Built;
13949   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13950
13951   for (SDNode *N : Built)
13952     AddToWorklist(N);
13953   return S;
13954 }
13955
13956 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13957 /// expression that will generate the same value by multiplying by a magic
13958 /// number.
13959 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13960 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13961   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13962   if (!C)
13963     return SDValue();
13964
13965   // Avoid division by zero.
13966   if (C->isNullValue())
13967     return SDValue();
13968
13969   std::vector<SDNode*> Built;
13970   SDValue S =
13971       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13972
13973   for (SDNode *N : Built)
13974     AddToWorklist(N);
13975   return S;
13976 }
13977
13978 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
13979   if (Level >= AfterLegalizeDAG)
13980     return SDValue();
13981
13982   // Expose the DAG combiner to the target combiner implementations.
13983   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13984
13985   unsigned Iterations = 0;
13986   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13987     if (Iterations) {
13988       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13989       // For the reciprocal, we need to find the zero of the function:
13990       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13991       //     =>
13992       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13993       //     does not require additional intermediate precision]
13994       EVT VT = Op.getValueType();
13995       SDLoc DL(Op);
13996       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13997
13998       AddToWorklist(Est.getNode());
13999
14000       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14001       for (unsigned i = 0; i < Iterations; ++i) {
14002         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14003         AddToWorklist(NewEst.getNode());
14004
14005         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14006         AddToWorklist(NewEst.getNode());
14007
14008         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14009         AddToWorklist(NewEst.getNode());
14010
14011         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14012         AddToWorklist(Est.getNode());
14013       }
14014     }
14015     return Est;
14016   }
14017
14018   return SDValue();
14019 }
14020
14021 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14022 /// For the reciprocal sqrt, we need to find the zero of the function:
14023 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14024 ///     =>
14025 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14026 /// As a result, we precompute A/2 prior to the iteration loop.
14027 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14028                                           unsigned Iterations,
14029                                           SDNodeFlags *Flags) {
14030   EVT VT = Arg.getValueType();
14031   SDLoc DL(Arg);
14032   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14033
14034   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14035   // this entire sequence requires only one FP constant.
14036   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14037   AddToWorklist(HalfArg.getNode());
14038
14039   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14040   AddToWorklist(HalfArg.getNode());
14041
14042   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14043   for (unsigned i = 0; i < Iterations; ++i) {
14044     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14045     AddToWorklist(NewEst.getNode());
14046
14047     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14048     AddToWorklist(NewEst.getNode());
14049
14050     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14051     AddToWorklist(NewEst.getNode());
14052
14053     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14054     AddToWorklist(Est.getNode());
14055   }
14056   return Est;
14057 }
14058
14059 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14060 /// For the reciprocal sqrt, we need to find the zero of the function:
14061 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14062 ///     =>
14063 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14064 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14065                                           unsigned Iterations,
14066                                           SDNodeFlags *Flags) {
14067   EVT VT = Arg.getValueType();
14068   SDLoc DL(Arg);
14069   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14070   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14071
14072   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14073   for (unsigned i = 0; i < Iterations; ++i) {
14074     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14075     AddToWorklist(HalfEst.getNode());
14076
14077     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14078     AddToWorklist(Est.getNode());
14079
14080     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14081     AddToWorklist(Est.getNode());
14082
14083     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14084     AddToWorklist(Est.getNode());
14085
14086     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14087     AddToWorklist(Est.getNode());
14088   }
14089   return Est;
14090 }
14091
14092 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14093   if (Level >= AfterLegalizeDAG)
14094     return SDValue();
14095
14096   // Expose the DAG combiner to the target combiner implementations.
14097   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14098   unsigned Iterations = 0;
14099   bool UseOneConstNR = false;
14100   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14101     AddToWorklist(Est.getNode());
14102     if (Iterations) {
14103       Est = UseOneConstNR ?
14104         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14105         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14106     }
14107     return Est;
14108   }
14109
14110   return SDValue();
14111 }
14112
14113 /// Return true if base is a frame index, which is known not to alias with
14114 /// anything but itself.  Provides base object and offset as results.
14115 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14116                            const GlobalValue *&GV, const void *&CV) {
14117   // Assume it is a primitive operation.
14118   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14119
14120   // If it's an adding a simple constant then integrate the offset.
14121   if (Base.getOpcode() == ISD::ADD) {
14122     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14123       Base = Base.getOperand(0);
14124       Offset += C->getZExtValue();
14125     }
14126   }
14127
14128   // Return the underlying GlobalValue, and update the Offset.  Return false
14129   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14130   // by multiple nodes with different offsets.
14131   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14132     GV = G->getGlobal();
14133     Offset += G->getOffset();
14134     return false;
14135   }
14136
14137   // Return the underlying Constant value, and update the Offset.  Return false
14138   // for ConstantSDNodes since the same constant pool entry may be represented
14139   // by multiple nodes with different offsets.
14140   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14141     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14142                                          : (const void *)C->getConstVal();
14143     Offset += C->getOffset();
14144     return false;
14145   }
14146   // If it's any of the following then it can't alias with anything but itself.
14147   return isa<FrameIndexSDNode>(Base);
14148 }
14149
14150 /// Return true if there is any possibility that the two addresses overlap.
14151 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14152   // If they are the same then they must be aliases.
14153   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14154
14155   // If they are both volatile then they cannot be reordered.
14156   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14157
14158   // If one operation reads from invariant memory, and the other may store, they
14159   // cannot alias. These should really be checking the equivalent of mayWrite,
14160   // but it only matters for memory nodes other than load /store.
14161   if (Op0->isInvariant() && Op1->writeMem())
14162     return false;
14163
14164   if (Op1->isInvariant() && Op0->writeMem())
14165     return false;
14166
14167   // Gather base node and offset information.
14168   SDValue Base1, Base2;
14169   int64_t Offset1, Offset2;
14170   const GlobalValue *GV1, *GV2;
14171   const void *CV1, *CV2;
14172   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14173                                       Base1, Offset1, GV1, CV1);
14174   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14175                                       Base2, Offset2, GV2, CV2);
14176
14177   // If they have a same base address then check to see if they overlap.
14178   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14179     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14180              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14181
14182   // It is possible for different frame indices to alias each other, mostly
14183   // when tail call optimization reuses return address slots for arguments.
14184   // To catch this case, look up the actual index of frame indices to compute
14185   // the real alias relationship.
14186   if (isFrameIndex1 && isFrameIndex2) {
14187     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14188     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14189     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14190     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14191              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14192   }
14193
14194   // Otherwise, if we know what the bases are, and they aren't identical, then
14195   // we know they cannot alias.
14196   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14197     return false;
14198
14199   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14200   // compared to the size and offset of the access, we may be able to prove they
14201   // do not alias.  This check is conservative for now to catch cases created by
14202   // splitting vector types.
14203   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14204       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14205       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14206        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14207       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14208     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14209     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14210
14211     // There is no overlap between these relatively aligned accesses of similar
14212     // size, return no alias.
14213     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14214         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14215       return false;
14216   }
14217
14218   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14219                    ? CombinerGlobalAA
14220                    : DAG.getSubtarget().useAA();
14221 #ifndef NDEBUG
14222   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14223       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14224     UseAA = false;
14225 #endif
14226   if (UseAA &&
14227       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14228     // Use alias analysis information.
14229     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14230                                  Op1->getSrcValueOffset());
14231     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14232         Op0->getSrcValueOffset() - MinOffset;
14233     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14234         Op1->getSrcValueOffset() - MinOffset;
14235     AliasResult AAResult =
14236         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14237                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14238                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14239                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14240     if (AAResult == NoAlias)
14241       return false;
14242   }
14243
14244   // Otherwise we have to assume they alias.
14245   return true;
14246 }
14247
14248 /// Walk up chain skipping non-aliasing memory nodes,
14249 /// looking for aliasing nodes and adding them to the Aliases vector.
14250 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14251                                    SmallVectorImpl<SDValue> &Aliases) {
14252   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14253   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14254
14255   // Get alias information for node.
14256   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14257
14258   // Starting off.
14259   Chains.push_back(OriginalChain);
14260   unsigned Depth = 0;
14261
14262   // Look at each chain and determine if it is an alias.  If so, add it to the
14263   // aliases list.  If not, then continue up the chain looking for the next
14264   // candidate.
14265   while (!Chains.empty()) {
14266     SDValue Chain = Chains.pop_back_val();
14267
14268     // For TokenFactor nodes, look at each operand and only continue up the
14269     // chain until we reach the depth limit.
14270     //
14271     // FIXME: The depth check could be made to return the last non-aliasing
14272     // chain we found before we hit a tokenfactor rather than the original
14273     // chain.
14274     if (Depth > 6) {
14275       Aliases.clear();
14276       Aliases.push_back(OriginalChain);
14277       return;
14278     }
14279
14280     // Don't bother if we've been before.
14281     if (!Visited.insert(Chain.getNode()).second)
14282       continue;
14283
14284     switch (Chain.getOpcode()) {
14285     case ISD::EntryToken:
14286       // Entry token is ideal chain operand, but handled in FindBetterChain.
14287       break;
14288
14289     case ISD::LOAD:
14290     case ISD::STORE: {
14291       // Get alias information for Chain.
14292       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14293           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14294
14295       // If chain is alias then stop here.
14296       if (!(IsLoad && IsOpLoad) &&
14297           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14298         Aliases.push_back(Chain);
14299       } else {
14300         // Look further up the chain.
14301         Chains.push_back(Chain.getOperand(0));
14302         ++Depth;
14303       }
14304       break;
14305     }
14306
14307     case ISD::TokenFactor:
14308       // We have to check each of the operands of the token factor for "small"
14309       // token factors, so we queue them up.  Adding the operands to the queue
14310       // (stack) in reverse order maintains the original order and increases the
14311       // likelihood that getNode will find a matching token factor (CSE.)
14312       if (Chain.getNumOperands() > 16) {
14313         Aliases.push_back(Chain);
14314         break;
14315       }
14316       for (unsigned n = Chain.getNumOperands(); n;)
14317         Chains.push_back(Chain.getOperand(--n));
14318       ++Depth;
14319       break;
14320
14321     default:
14322       // For all other instructions we will just have to take what we can get.
14323       Aliases.push_back(Chain);
14324       break;
14325     }
14326   }
14327
14328   // We need to be careful here to also search for aliases through the
14329   // value operand of a store, etc. Consider the following situation:
14330   //   Token1 = ...
14331   //   L1 = load Token1, %52
14332   //   S1 = store Token1, L1, %51
14333   //   L2 = load Token1, %52+8
14334   //   S2 = store Token1, L2, %51+8
14335   //   Token2 = Token(S1, S2)
14336   //   L3 = load Token2, %53
14337   //   S3 = store Token2, L3, %52
14338   //   L4 = load Token2, %53+8
14339   //   S4 = store Token2, L4, %52+8
14340   // If we search for aliases of S3 (which loads address %52), and we look
14341   // only through the chain, then we'll miss the trivial dependence on L1
14342   // (which also loads from %52). We then might change all loads and
14343   // stores to use Token1 as their chain operand, which could result in
14344   // copying %53 into %52 before copying %52 into %51 (which should
14345   // happen first).
14346   //
14347   // The problem is, however, that searching for such data dependencies
14348   // can become expensive, and the cost is not directly related to the
14349   // chain depth. Instead, we'll rule out such configurations here by
14350   // insisting that we've visited all chain users (except for users
14351   // of the original chain, which is not necessary). When doing this,
14352   // we need to look through nodes we don't care about (otherwise, things
14353   // like register copies will interfere with trivial cases).
14354
14355   SmallVector<const SDNode *, 16> Worklist;
14356   for (const SDNode *N : Visited)
14357     if (N != OriginalChain.getNode())
14358       Worklist.push_back(N);
14359
14360   while (!Worklist.empty()) {
14361     const SDNode *M = Worklist.pop_back_val();
14362
14363     // We have already visited M, and want to make sure we've visited any uses
14364     // of M that we care about. For uses that we've not visisted, and don't
14365     // care about, queue them to the worklist.
14366
14367     for (SDNode::use_iterator UI = M->use_begin(),
14368          UIE = M->use_end(); UI != UIE; ++UI)
14369       if (UI.getUse().getValueType() == MVT::Other &&
14370           Visited.insert(*UI).second) {
14371         if (isa<MemSDNode>(*UI)) {
14372           // We've not visited this use, and we care about it (it could have an
14373           // ordering dependency with the original node).
14374           Aliases.clear();
14375           Aliases.push_back(OriginalChain);
14376           return;
14377         }
14378
14379         // We've not visited this use, but we don't care about it. Mark it as
14380         // visited and enqueue it to the worklist.
14381         Worklist.push_back(*UI);
14382       }
14383   }
14384 }
14385
14386 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14387 /// (aliasing node.)
14388 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14389   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14390
14391   // Accumulate all the aliases to this node.
14392   GatherAllAliases(N, OldChain, Aliases);
14393
14394   // If no operands then chain to entry token.
14395   if (Aliases.size() == 0)
14396     return DAG.getEntryNode();
14397
14398   // If a single operand then chain to it.  We don't need to revisit it.
14399   if (Aliases.size() == 1)
14400     return Aliases[0];
14401
14402   // Construct a custom tailored token factor.
14403   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14404 }
14405
14406 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14407   // This holds the base pointer, index, and the offset in bytes from the base
14408   // pointer.
14409   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14410
14411   // We must have a base and an offset.
14412   if (!BasePtr.Base.getNode())
14413     return false;
14414
14415   // Do not handle stores to undef base pointers.
14416   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14417     return false;
14418
14419   SmallVector<StoreSDNode *, 8> ChainedStores;
14420   ChainedStores.push_back(St);
14421
14422   // Walk up the chain and look for nodes with offsets from the same
14423   // base pointer. Stop when reaching an instruction with a different kind
14424   // or instruction which has a different base pointer.
14425   StoreSDNode *Index = St;
14426   while (Index) {
14427     // If the chain has more than one use, then we can't reorder the mem ops.
14428     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14429       break;
14430
14431     if (Index->isVolatile() || Index->isIndexed())
14432       break;
14433
14434     // Find the base pointer and offset for this memory node.
14435     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14436
14437     // Check that the base pointer is the same as the original one.
14438     if (!Ptr.equalBaseIndex(BasePtr))
14439       break;
14440
14441     // Find the next memory operand in the chain. If the next operand in the
14442     // chain is a store then move up and continue the scan with the next
14443     // memory operand. If the next operand is a load save it and use alias
14444     // information to check if it interferes with anything.
14445     SDNode *NextInChain = Index->getChain().getNode();
14446     while (true) {
14447       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14448         // We found a store node. Use it for the next iteration.
14449         ChainedStores.push_back(STn);
14450         Index = STn;
14451         break;
14452       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14453         NextInChain = Ldn->getChain().getNode();
14454         continue;
14455       } else {
14456         Index = nullptr;
14457         break;
14458       }
14459     }
14460   }
14461
14462   bool MadeChange = false;
14463   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14464
14465   for (StoreSDNode *ChainedStore : ChainedStores) {
14466     SDValue Chain = ChainedStore->getChain();
14467     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14468
14469     if (Chain != BetterChain) {
14470       MadeChange = true;
14471       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14472     }
14473   }
14474
14475   // Do all replacements after finding the replacements to make to avoid making
14476   // the chains more complicated by introducing new TokenFactors.
14477   for (auto Replacement : BetterChains)
14478     replaceStoreChain(Replacement.first, Replacement.second);
14479
14480   return MadeChange;
14481 }
14482
14483 /// This is the entry point for the file.
14484 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14485                            CodeGenOpt::Level OptLevel) {
14486   /// This is the main entry point to this class.
14487   DAGCombiner(*this, AA, OptLevel).Run(Level);
14488 }