Factor replacement of stores of FP constants into new function
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitIMINMAX(SDNode *N);
249     SDValue visitAND(SDNode *N);
250     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
251     SDValue visitOR(SDNode *N);
252     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitXOR(SDNode *N);
254     SDValue SimplifyVBinOp(SDNode *N);
255     SDValue visitSHL(SDNode *N);
256     SDValue visitSRA(SDNode *N);
257     SDValue visitSRL(SDNode *N);
258     SDValue visitRotate(SDNode *N);
259     SDValue visitBSWAP(SDNode *N);
260     SDValue visitCTLZ(SDNode *N);
261     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTTZ(SDNode *N);
263     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
264     SDValue visitCTPOP(SDNode *N);
265     SDValue visitSELECT(SDNode *N);
266     SDValue visitVSELECT(SDNode *N);
267     SDValue visitSELECT_CC(SDNode *N);
268     SDValue visitSETCC(SDNode *N);
269     SDValue visitSIGN_EXTEND(SDNode *N);
270     SDValue visitZERO_EXTEND(SDNode *N);
271     SDValue visitANY_EXTEND(SDNode *N);
272     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
273     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
274     SDValue visitTRUNCATE(SDNode *N);
275     SDValue visitBITCAST(SDNode *N);
276     SDValue visitBUILD_PAIR(SDNode *N);
277     SDValue visitFADD(SDNode *N);
278     SDValue visitFSUB(SDNode *N);
279     SDValue visitFMUL(SDNode *N);
280     SDValue visitFMA(SDNode *N);
281     SDValue visitFDIV(SDNode *N);
282     SDValue visitFREM(SDNode *N);
283     SDValue visitFSQRT(SDNode *N);
284     SDValue visitFCOPYSIGN(SDNode *N);
285     SDValue visitSINT_TO_FP(SDNode *N);
286     SDValue visitUINT_TO_FP(SDNode *N);
287     SDValue visitFP_TO_SINT(SDNode *N);
288     SDValue visitFP_TO_UINT(SDNode *N);
289     SDValue visitFP_ROUND(SDNode *N);
290     SDValue visitFP_ROUND_INREG(SDNode *N);
291     SDValue visitFP_EXTEND(SDNode *N);
292     SDValue visitFNEG(SDNode *N);
293     SDValue visitFABS(SDNode *N);
294     SDValue visitFCEIL(SDNode *N);
295     SDValue visitFTRUNC(SDNode *N);
296     SDValue visitFFLOOR(SDNode *N);
297     SDValue visitFMINNUM(SDNode *N);
298     SDValue visitFMAXNUM(SDNode *N);
299     SDValue visitBRCOND(SDNode *N);
300     SDValue visitBR_CC(SDNode *N);
301     SDValue visitLOAD(SDNode *N);
302
303     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
304     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
305
306     SDValue visitSTORE(SDNode *N);
307     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
308     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
309     SDValue visitBUILD_VECTOR(SDNode *N);
310     SDValue visitCONCAT_VECTORS(SDNode *N);
311     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
312     SDValue visitVECTOR_SHUFFLE(SDNode *N);
313     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
314     SDValue visitINSERT_SUBVECTOR(SDNode *N);
315     SDValue visitMLOAD(SDNode *N);
316     SDValue visitMSTORE(SDNode *N);
317     SDValue visitMGATHER(SDNode *N);
318     SDValue visitMSCATTER(SDNode *N);
319     SDValue visitFP_TO_FP16(SDNode *N);
320     SDValue visitFP16_TO_FP(SDNode *N);
321
322     SDValue visitFADDForFMACombine(SDNode *N);
323     SDValue visitFSUBForFMACombine(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                                          EVT Ty) const;
410
411     /// This is a helper function for MergeConsecutiveStores. When the source
412     /// elements of the consecutive stores are all constants or all extracted
413     /// vector elements, try to merge them into one larger store.
414     /// \return True if a merged store was created.
415     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
416                                          EVT MemVT, unsigned NumStores,
417                                          bool IsConstantSrc, bool UseVector);
418
419     /// This is a helper function for MergeConsecutiveStores.
420     /// Stores that may be merged are placed in StoreNodes.
421     /// Loads that may alias with those stores are placed in AliasLoadNodes.
422     void getStoreMergeAndAliasCandidates(
423         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
424         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
425
426     /// Merge consecutive store operations into a wide store.
427     /// This optimization uses wide integers or vectors when possible.
428     /// \return True if some memory operations were changed.
429     bool MergeConsecutiveStores(StoreSDNode *N);
430
431     /// \brief Try to transform a truncation where C is a constant:
432     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
433     ///
434     /// \p N needs to be a truncation and its first operand an AND. Other
435     /// requirements are checked by the function (e.g. that trunc is
436     /// single-use) and if missed an empty SDValue is returned.
437     SDValue distributeTruncateThroughAnd(SDNode *N);
438
439   public:
440     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
441         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
442           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
443       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
444     }
445
446     /// Runs the dag combiner on all nodes in the work list
447     void Run(CombineLevel AtLevel);
448
449     SelectionDAG &getDAG() const { return DAG; }
450
451     /// Returns a type large enough to hold any valid shift amount - before type
452     /// legalization these can be huge.
453     EVT getShiftAmountTy(EVT LHSTy) {
454       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
455       if (LHSTy.isVector())
456         return LHSTy;
457       auto &DL = DAG.getDataLayout();
458       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
459                         : TLI.getPointerTy(DL);
460     }
461
462     /// This method returns true if we are running before type legalization or
463     /// if the specified VT is legal.
464     bool isTypeLegal(const EVT &VT) {
465       if (!LegalTypes) return true;
466       return TLI.isTypeLegal(VT);
467     }
468
469     /// Convenience wrapper around TargetLowering::getSetCCResultType
470     EVT getSetCCResultType(EVT VT) const {
471       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
472     }
473   };
474 }
475
476
477 namespace {
478 /// This class is a DAGUpdateListener that removes any deleted
479 /// nodes from the worklist.
480 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
481   DAGCombiner &DC;
482 public:
483   explicit WorklistRemover(DAGCombiner &dc)
484     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
485
486   void NodeDeleted(SDNode *N, SDNode *E) override {
487     DC.removeFromWorklist(N);
488   }
489 };
490 }
491
492 //===----------------------------------------------------------------------===//
493 //  TargetLowering::DAGCombinerInfo implementation
494 //===----------------------------------------------------------------------===//
495
496 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
497   ((DAGCombiner*)DC)->AddToWorklist(N);
498 }
499
500 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
501   ((DAGCombiner*)DC)->removeFromWorklist(N);
502 }
503
504 SDValue TargetLowering::DAGCombinerInfo::
505 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
506   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
507 }
508
509 SDValue TargetLowering::DAGCombinerInfo::
510 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
511   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
512 }
513
514
515 SDValue TargetLowering::DAGCombinerInfo::
516 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
517   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
518 }
519
520 void TargetLowering::DAGCombinerInfo::
521 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
522   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
523 }
524
525 //===----------------------------------------------------------------------===//
526 // Helper Functions
527 //===----------------------------------------------------------------------===//
528
529 void DAGCombiner::deleteAndRecombine(SDNode *N) {
530   removeFromWorklist(N);
531
532   // If the operands of this node are only used by the node, they will now be
533   // dead. Make sure to re-visit them and recursively delete dead nodes.
534   for (const SDValue &Op : N->ops())
535     // For an operand generating multiple values, one of the values may
536     // become dead allowing further simplification (e.g. split index
537     // arithmetic from an indexed load).
538     if (Op->hasOneUse() || Op->getNumValues() > 1)
539       AddToWorklist(Op.getNode());
540
541   DAG.DeleteNode(N);
542 }
543
544 /// Return 1 if we can compute the negated form of the specified expression for
545 /// the same cost as the expression itself, or 2 if we can compute the negated
546 /// form more cheaply than the expression itself.
547 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
548                                const TargetLowering &TLI,
549                                const TargetOptions *Options,
550                                unsigned Depth = 0) {
551   // fneg is removable even if it has multiple uses.
552   if (Op.getOpcode() == ISD::FNEG) return 2;
553
554   // Don't allow anything with multiple uses.
555   if (!Op.hasOneUse()) return 0;
556
557   // Don't recurse exponentially.
558   if (Depth > 6) return 0;
559
560   switch (Op.getOpcode()) {
561   default: return false;
562   case ISD::ConstantFP:
563     // Don't invert constant FP values after legalize.  The negated constant
564     // isn't necessarily legal.
565     return LegalOperations ? 0 : 1;
566   case ISD::FADD:
567     // FIXME: determine better conditions for this xform.
568     if (!Options->UnsafeFPMath) return 0;
569
570     // After operation legalization, it might not be legal to create new FSUBs.
571     if (LegalOperations &&
572         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
573       return 0;
574
575     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
576     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
577                                     Options, Depth + 1))
578       return V;
579     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
580     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
581                               Depth + 1);
582   case ISD::FSUB:
583     // We can't turn -(A-B) into B-A when we honor signed zeros.
584     if (!Options->UnsafeFPMath) return 0;
585
586     // fold (fneg (fsub A, B)) -> (fsub B, A)
587     return 1;
588
589   case ISD::FMUL:
590   case ISD::FDIV:
591     if (Options->HonorSignDependentRoundingFPMath()) return 0;
592
593     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
594     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
595                                     Options, Depth + 1))
596       return V;
597
598     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
599                               Depth + 1);
600
601   case ISD::FP_EXTEND:
602   case ISD::FP_ROUND:
603   case ISD::FSIN:
604     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
605                               Depth + 1);
606   }
607 }
608
609 /// If isNegatibleForFree returns true, return the newly negated expression.
610 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
611                                     bool LegalOperations, unsigned Depth = 0) {
612   const TargetOptions &Options = DAG.getTarget().Options;
613   // fneg is removable even if it has multiple uses.
614   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
615
616   // Don't allow anything with multiple uses.
617   assert(Op.hasOneUse() && "Unknown reuse!");
618
619   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
620
621   const SDNodeFlags *Flags = Op.getNode()->getFlags();
622   
623   switch (Op.getOpcode()) {
624   default: llvm_unreachable("Unknown code");
625   case ISD::ConstantFP: {
626     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
627     V.changeSign();
628     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
629   }
630   case ISD::FADD:
631     // FIXME: determine better conditions for this xform.
632     assert(Options.UnsafeFPMath);
633
634     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
635     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
636                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
637       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
638                          GetNegatedExpression(Op.getOperand(0), DAG,
639                                               LegalOperations, Depth+1),
640                          Op.getOperand(1), Flags);
641     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
642     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
643                        GetNegatedExpression(Op.getOperand(1), DAG,
644                                             LegalOperations, Depth+1),
645                        Op.getOperand(0), Flags);
646   case ISD::FSUB:
647     // We can't turn -(A-B) into B-A when we honor signed zeros.
648     assert(Options.UnsafeFPMath);
649
650     // fold (fneg (fsub 0, B)) -> B
651     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
652       if (N0CFP->isZero())
653         return Op.getOperand(1);
654
655     // fold (fneg (fsub A, B)) -> (fsub B, A)
656     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
657                        Op.getOperand(1), Op.getOperand(0), Flags);
658
659   case ISD::FMUL:
660   case ISD::FDIV:
661     assert(!Options.HonorSignDependentRoundingFPMath());
662
663     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
664     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
665                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
666       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
667                          GetNegatedExpression(Op.getOperand(0), DAG,
668                                               LegalOperations, Depth+1),
669                          Op.getOperand(1), Flags);
670
671     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
672     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
673                        Op.getOperand(0),
674                        GetNegatedExpression(Op.getOperand(1), DAG,
675                                             LegalOperations, Depth+1), Flags);
676
677   case ISD::FP_EXTEND:
678   case ISD::FSIN:
679     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
680                        GetNegatedExpression(Op.getOperand(0), DAG,
681                                             LegalOperations, Depth+1));
682   case ISD::FP_ROUND:
683       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
684                          GetNegatedExpression(Op.getOperand(0), DAG,
685                                               LegalOperations, Depth+1),
686                          Op.getOperand(1));
687   }
688 }
689
690 // Return true if this node is a setcc, or is a select_cc
691 // that selects between the target values used for true and false, making it
692 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
693 // the appropriate nodes based on the type of node we are checking. This
694 // simplifies life a bit for the callers.
695 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
696                                     SDValue &CC) const {
697   if (N.getOpcode() == ISD::SETCC) {
698     LHS = N.getOperand(0);
699     RHS = N.getOperand(1);
700     CC  = N.getOperand(2);
701     return true;
702   }
703
704   if (N.getOpcode() != ISD::SELECT_CC ||
705       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
706       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
707     return false;
708
709   if (TLI.getBooleanContents(N.getValueType()) ==
710       TargetLowering::UndefinedBooleanContent)
711     return false;
712
713   LHS = N.getOperand(0);
714   RHS = N.getOperand(1);
715   CC  = N.getOperand(4);
716   return true;
717 }
718
719 /// Return true if this is a SetCC-equivalent operation with only one use.
720 /// If this is true, it allows the users to invert the operation for free when
721 /// it is profitable to do so.
722 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
723   SDValue N0, N1, N2;
724   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
725     return true;
726   return false;
727 }
728
729 /// Returns true if N is a BUILD_VECTOR node whose
730 /// elements are all the same constant or undefined.
731 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
732   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
733   if (!C)
734     return false;
735
736   APInt SplatUndef;
737   unsigned SplatBitSize;
738   bool HasAnyUndefs;
739   EVT EltVT = N->getValueType(0).getVectorElementType();
740   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
741                              HasAnyUndefs) &&
742           EltVT.getSizeInBits() >= SplatBitSize);
743 }
744
745 // \brief Returns the SDNode if it is a constant integer BuildVector
746 // or constant integer.
747 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
748   if (isa<ConstantSDNode>(N))
749     return N.getNode();
750   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
751     return N.getNode();
752   return nullptr;
753 }
754
755 // \brief Returns the SDNode if it is a constant float BuildVector
756 // or constant float.
757 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
758   if (isa<ConstantFPSDNode>(N))
759     return N.getNode();
760   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
761     return N.getNode();
762   return nullptr;
763 }
764
765 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
766 // int.
767 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
768   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
769     return CN;
770
771   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
772     BitVector UndefElements;
773     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
774
775     // BuildVectors can truncate their operands. Ignore that case here.
776     // FIXME: We blindly ignore splats which include undef which is overly
777     // pessimistic.
778     if (CN && UndefElements.none() &&
779         CN->getValueType(0) == N.getValueType().getScalarType())
780       return CN;
781   }
782
783   return nullptr;
784 }
785
786 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
787 // float.
788 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
789   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
790     return CN;
791
792   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
793     BitVector UndefElements;
794     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
795
796     if (CN && UndefElements.none())
797       return CN;
798   }
799
800   return nullptr;
801 }
802
803 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
804                                     SDValue N0, SDValue N1) {
805   EVT VT = N0.getValueType();
806   if (N0.getOpcode() == Opc) {
807     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
808       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
809         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
810         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
811           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
812         return SDValue();
813       }
814       if (N0.hasOneUse()) {
815         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
816         // use
817         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
818         if (!OpNode.getNode())
819           return SDValue();
820         AddToWorklist(OpNode.getNode());
821         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
822       }
823     }
824   }
825
826   if (N1.getOpcode() == Opc) {
827     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
828       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
829         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
830         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
831           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
832         return SDValue();
833       }
834       if (N1.hasOneUse()) {
835         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
836         // use
837         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
838         if (!OpNode.getNode())
839           return SDValue();
840         AddToWorklist(OpNode.getNode());
841         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
842       }
843     }
844   }
845
846   return SDValue();
847 }
848
849 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
850                                bool AddTo) {
851   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
852   ++NodesCombined;
853   DEBUG(dbgs() << "\nReplacing.1 ";
854         N->dump(&DAG);
855         dbgs() << "\nWith: ";
856         To[0].getNode()->dump(&DAG);
857         dbgs() << " and " << NumTo-1 << " other values\n");
858   for (unsigned i = 0, e = NumTo; i != e; ++i)
859     assert((!To[i].getNode() ||
860             N->getValueType(i) == To[i].getValueType()) &&
861            "Cannot combine value to value of different type!");
862
863   WorklistRemover DeadNodes(*this);
864   DAG.ReplaceAllUsesWith(N, To);
865   if (AddTo) {
866     // Push the new nodes and any users onto the worklist
867     for (unsigned i = 0, e = NumTo; i != e; ++i) {
868       if (To[i].getNode()) {
869         AddToWorklist(To[i].getNode());
870         AddUsersToWorklist(To[i].getNode());
871       }
872     }
873   }
874
875   // Finally, if the node is now dead, remove it from the graph.  The node
876   // may not be dead if the replacement process recursively simplified to
877   // something else needing this node.
878   if (N->use_empty())
879     deleteAndRecombine(N);
880   return SDValue(N, 0);
881 }
882
883 void DAGCombiner::
884 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
885   // Replace all uses.  If any nodes become isomorphic to other nodes and
886   // are deleted, make sure to remove them from our worklist.
887   WorklistRemover DeadNodes(*this);
888   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
889
890   // Push the new node and any (possibly new) users onto the worklist.
891   AddToWorklist(TLO.New.getNode());
892   AddUsersToWorklist(TLO.New.getNode());
893
894   // Finally, if the node is now dead, remove it from the graph.  The node
895   // may not be dead if the replacement process recursively simplified to
896   // something else needing this node.
897   if (TLO.Old.getNode()->use_empty())
898     deleteAndRecombine(TLO.Old.getNode());
899 }
900
901 /// Check the specified integer node value to see if it can be simplified or if
902 /// things it uses can be simplified by bit propagation. If so, return true.
903 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
904   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
905   APInt KnownZero, KnownOne;
906   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
907     return false;
908
909   // Revisit the node.
910   AddToWorklist(Op.getNode());
911
912   // Replace the old value with the new one.
913   ++NodesCombined;
914   DEBUG(dbgs() << "\nReplacing.2 ";
915         TLO.Old.getNode()->dump(&DAG);
916         dbgs() << "\nWith: ";
917         TLO.New.getNode()->dump(&DAG);
918         dbgs() << '\n');
919
920   CommitTargetLoweringOpt(TLO);
921   return true;
922 }
923
924 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
925   SDLoc dl(Load);
926   EVT VT = Load->getValueType(0);
927   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
928
929   DEBUG(dbgs() << "\nReplacing.9 ";
930         Load->dump(&DAG);
931         dbgs() << "\nWith: ";
932         Trunc.getNode()->dump(&DAG);
933         dbgs() << '\n');
934   WorklistRemover DeadNodes(*this);
935   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
936   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
937   deleteAndRecombine(Load);
938   AddToWorklist(Trunc.getNode());
939 }
940
941 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
942   Replace = false;
943   SDLoc dl(Op);
944   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
945     EVT MemVT = LD->getMemoryVT();
946     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
947       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
948                                                        : ISD::EXTLOAD)
949       : LD->getExtensionType();
950     Replace = true;
951     return DAG.getExtLoad(ExtType, dl, PVT,
952                           LD->getChain(), LD->getBasePtr(),
953                           MemVT, LD->getMemOperand());
954   }
955
956   unsigned Opc = Op.getOpcode();
957   switch (Opc) {
958   default: break;
959   case ISD::AssertSext:
960     return DAG.getNode(ISD::AssertSext, dl, PVT,
961                        SExtPromoteOperand(Op.getOperand(0), PVT),
962                        Op.getOperand(1));
963   case ISD::AssertZext:
964     return DAG.getNode(ISD::AssertZext, dl, PVT,
965                        ZExtPromoteOperand(Op.getOperand(0), PVT),
966                        Op.getOperand(1));
967   case ISD::Constant: {
968     unsigned ExtOpc =
969       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
970     return DAG.getNode(ExtOpc, dl, PVT, Op);
971   }
972   }
973
974   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
975     return SDValue();
976   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
977 }
978
979 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
980   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
981     return SDValue();
982   EVT OldVT = Op.getValueType();
983   SDLoc dl(Op);
984   bool Replace = false;
985   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
986   if (!NewOp.getNode())
987     return SDValue();
988   AddToWorklist(NewOp.getNode());
989
990   if (Replace)
991     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
992   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
993                      DAG.getValueType(OldVT));
994 }
995
996 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
997   EVT OldVT = Op.getValueType();
998   SDLoc dl(Op);
999   bool Replace = false;
1000   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1001   if (!NewOp.getNode())
1002     return SDValue();
1003   AddToWorklist(NewOp.getNode());
1004
1005   if (Replace)
1006     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1007   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1008 }
1009
1010 /// Promote the specified integer binary operation if the target indicates it is
1011 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1012 /// i32 since i16 instructions are longer.
1013 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1014   if (!LegalOperations)
1015     return SDValue();
1016
1017   EVT VT = Op.getValueType();
1018   if (VT.isVector() || !VT.isInteger())
1019     return SDValue();
1020
1021   // If operation type is 'undesirable', e.g. i16 on x86, consider
1022   // promoting it.
1023   unsigned Opc = Op.getOpcode();
1024   if (TLI.isTypeDesirableForOp(Opc, VT))
1025     return SDValue();
1026
1027   EVT PVT = VT;
1028   // Consult target whether it is a good idea to promote this operation and
1029   // what's the right type to promote it to.
1030   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1031     assert(PVT != VT && "Don't know what type to promote to!");
1032
1033     bool Replace0 = false;
1034     SDValue N0 = Op.getOperand(0);
1035     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1036     if (!NN0.getNode())
1037       return SDValue();
1038
1039     bool Replace1 = false;
1040     SDValue N1 = Op.getOperand(1);
1041     SDValue NN1;
1042     if (N0 == N1)
1043       NN1 = NN0;
1044     else {
1045       NN1 = PromoteOperand(N1, PVT, Replace1);
1046       if (!NN1.getNode())
1047         return SDValue();
1048     }
1049
1050     AddToWorklist(NN0.getNode());
1051     if (NN1.getNode())
1052       AddToWorklist(NN1.getNode());
1053
1054     if (Replace0)
1055       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1056     if (Replace1)
1057       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1058
1059     DEBUG(dbgs() << "\nPromoting ";
1060           Op.getNode()->dump(&DAG));
1061     SDLoc dl(Op);
1062     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1063                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1064   }
1065   return SDValue();
1066 }
1067
1068 /// Promote the specified integer shift operation if the target indicates it is
1069 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1070 /// i32 since i16 instructions are longer.
1071 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1072   if (!LegalOperations)
1073     return SDValue();
1074
1075   EVT VT = Op.getValueType();
1076   if (VT.isVector() || !VT.isInteger())
1077     return SDValue();
1078
1079   // If operation type is 'undesirable', e.g. i16 on x86, consider
1080   // promoting it.
1081   unsigned Opc = Op.getOpcode();
1082   if (TLI.isTypeDesirableForOp(Opc, VT))
1083     return SDValue();
1084
1085   EVT PVT = VT;
1086   // Consult target whether it is a good idea to promote this operation and
1087   // what's the right type to promote it to.
1088   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1089     assert(PVT != VT && "Don't know what type to promote to!");
1090
1091     bool Replace = false;
1092     SDValue N0 = Op.getOperand(0);
1093     if (Opc == ISD::SRA)
1094       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1095     else if (Opc == ISD::SRL)
1096       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1097     else
1098       N0 = PromoteOperand(N0, PVT, Replace);
1099     if (!N0.getNode())
1100       return SDValue();
1101
1102     AddToWorklist(N0.getNode());
1103     if (Replace)
1104       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1105
1106     DEBUG(dbgs() << "\nPromoting ";
1107           Op.getNode()->dump(&DAG));
1108     SDLoc dl(Op);
1109     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1110                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1111   }
1112   return SDValue();
1113 }
1114
1115 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1116   if (!LegalOperations)
1117     return SDValue();
1118
1119   EVT VT = Op.getValueType();
1120   if (VT.isVector() || !VT.isInteger())
1121     return SDValue();
1122
1123   // If operation type is 'undesirable', e.g. i16 on x86, consider
1124   // promoting it.
1125   unsigned Opc = Op.getOpcode();
1126   if (TLI.isTypeDesirableForOp(Opc, VT))
1127     return SDValue();
1128
1129   EVT PVT = VT;
1130   // Consult target whether it is a good idea to promote this operation and
1131   // what's the right type to promote it to.
1132   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1133     assert(PVT != VT && "Don't know what type to promote to!");
1134     // fold (aext (aext x)) -> (aext x)
1135     // fold (aext (zext x)) -> (zext x)
1136     // fold (aext (sext x)) -> (sext x)
1137     DEBUG(dbgs() << "\nPromoting ";
1138           Op.getNode()->dump(&DAG));
1139     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1140   }
1141   return SDValue();
1142 }
1143
1144 bool DAGCombiner::PromoteLoad(SDValue Op) {
1145   if (!LegalOperations)
1146     return false;
1147
1148   EVT VT = Op.getValueType();
1149   if (VT.isVector() || !VT.isInteger())
1150     return false;
1151
1152   // If operation type is 'undesirable', e.g. i16 on x86, consider
1153   // promoting it.
1154   unsigned Opc = Op.getOpcode();
1155   if (TLI.isTypeDesirableForOp(Opc, VT))
1156     return false;
1157
1158   EVT PVT = VT;
1159   // Consult target whether it is a good idea to promote this operation and
1160   // what's the right type to promote it to.
1161   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1162     assert(PVT != VT && "Don't know what type to promote to!");
1163
1164     SDLoc dl(Op);
1165     SDNode *N = Op.getNode();
1166     LoadSDNode *LD = cast<LoadSDNode>(N);
1167     EVT MemVT = LD->getMemoryVT();
1168     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1169       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1170                                                        : ISD::EXTLOAD)
1171       : LD->getExtensionType();
1172     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1173                                    LD->getChain(), LD->getBasePtr(),
1174                                    MemVT, LD->getMemOperand());
1175     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1176
1177     DEBUG(dbgs() << "\nPromoting ";
1178           N->dump(&DAG);
1179           dbgs() << "\nTo: ";
1180           Result.getNode()->dump(&DAG);
1181           dbgs() << '\n');
1182     WorklistRemover DeadNodes(*this);
1183     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1184     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1185     deleteAndRecombine(N);
1186     AddToWorklist(Result.getNode());
1187     return true;
1188   }
1189   return false;
1190 }
1191
1192 /// \brief Recursively delete a node which has no uses and any operands for
1193 /// which it is the only use.
1194 ///
1195 /// Note that this both deletes the nodes and removes them from the worklist.
1196 /// It also adds any nodes who have had a user deleted to the worklist as they
1197 /// may now have only one use and subject to other combines.
1198 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1199   if (!N->use_empty())
1200     return false;
1201
1202   SmallSetVector<SDNode *, 16> Nodes;
1203   Nodes.insert(N);
1204   do {
1205     N = Nodes.pop_back_val();
1206     if (!N)
1207       continue;
1208
1209     if (N->use_empty()) {
1210       for (const SDValue &ChildN : N->op_values())
1211         Nodes.insert(ChildN.getNode());
1212
1213       removeFromWorklist(N);
1214       DAG.DeleteNode(N);
1215     } else {
1216       AddToWorklist(N);
1217     }
1218   } while (!Nodes.empty());
1219   return true;
1220 }
1221
1222 //===----------------------------------------------------------------------===//
1223 //  Main DAG Combiner implementation
1224 //===----------------------------------------------------------------------===//
1225
1226 void DAGCombiner::Run(CombineLevel AtLevel) {
1227   // set the instance variables, so that the various visit routines may use it.
1228   Level = AtLevel;
1229   LegalOperations = Level >= AfterLegalizeVectorOps;
1230   LegalTypes = Level >= AfterLegalizeTypes;
1231
1232   // Add all the dag nodes to the worklist.
1233   for (SDNode &Node : DAG.allnodes())
1234     AddToWorklist(&Node);
1235
1236   // Create a dummy node (which is not added to allnodes), that adds a reference
1237   // to the root node, preventing it from being deleted, and tracking any
1238   // changes of the root.
1239   HandleSDNode Dummy(DAG.getRoot());
1240
1241   // while the worklist isn't empty, find a node and
1242   // try and combine it.
1243   while (!WorklistMap.empty()) {
1244     SDNode *N;
1245     // The Worklist holds the SDNodes in order, but it may contain null entries.
1246     do {
1247       N = Worklist.pop_back_val();
1248     } while (!N);
1249
1250     bool GoodWorklistEntry = WorklistMap.erase(N);
1251     (void)GoodWorklistEntry;
1252     assert(GoodWorklistEntry &&
1253            "Found a worklist entry without a corresponding map entry!");
1254
1255     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1256     // N is deleted from the DAG, since they too may now be dead or may have a
1257     // reduced number of uses, allowing other xforms.
1258     if (recursivelyDeleteUnusedNodes(N))
1259       continue;
1260
1261     WorklistRemover DeadNodes(*this);
1262
1263     // If this combine is running after legalizing the DAG, re-legalize any
1264     // nodes pulled off the worklist.
1265     if (Level == AfterLegalizeDAG) {
1266       SmallSetVector<SDNode *, 16> UpdatedNodes;
1267       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1268
1269       for (SDNode *LN : UpdatedNodes) {
1270         AddToWorklist(LN);
1271         AddUsersToWorklist(LN);
1272       }
1273       if (!NIsValid)
1274         continue;
1275     }
1276
1277     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1278
1279     // Add any operands of the new node which have not yet been combined to the
1280     // worklist as well. Because the worklist uniques things already, this
1281     // won't repeatedly process the same operand.
1282     CombinedNodes.insert(N);
1283     for (const SDValue &ChildN : N->op_values())
1284       if (!CombinedNodes.count(ChildN.getNode()))
1285         AddToWorklist(ChildN.getNode());
1286
1287     SDValue RV = combine(N);
1288
1289     if (!RV.getNode())
1290       continue;
1291
1292     ++NodesCombined;
1293
1294     // If we get back the same node we passed in, rather than a new node or
1295     // zero, we know that the node must have defined multiple values and
1296     // CombineTo was used.  Since CombineTo takes care of the worklist
1297     // mechanics for us, we have no work to do in this case.
1298     if (RV.getNode() == N)
1299       continue;
1300
1301     assert(N->getOpcode() != ISD::DELETED_NODE &&
1302            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1303            "Node was deleted but visit returned new node!");
1304
1305     DEBUG(dbgs() << " ... into: ";
1306           RV.getNode()->dump(&DAG));
1307
1308     // Transfer debug value.
1309     DAG.TransferDbgValues(SDValue(N, 0), RV);
1310     if (N->getNumValues() == RV.getNode()->getNumValues())
1311       DAG.ReplaceAllUsesWith(N, RV.getNode());
1312     else {
1313       assert(N->getValueType(0) == RV.getValueType() &&
1314              N->getNumValues() == 1 && "Type mismatch");
1315       SDValue OpV = RV;
1316       DAG.ReplaceAllUsesWith(N, &OpV);
1317     }
1318
1319     // Push the new node and any users onto the worklist
1320     AddToWorklist(RV.getNode());
1321     AddUsersToWorklist(RV.getNode());
1322
1323     // Finally, if the node is now dead, remove it from the graph.  The node
1324     // may not be dead if the replacement process recursively simplified to
1325     // something else needing this node. This will also take care of adding any
1326     // operands which have lost a user to the worklist.
1327     recursivelyDeleteUnusedNodes(N);
1328   }
1329
1330   // If the root changed (e.g. it was a dead load, update the root).
1331   DAG.setRoot(Dummy.getValue());
1332   DAG.RemoveDeadNodes();
1333 }
1334
1335 SDValue DAGCombiner::visit(SDNode *N) {
1336   switch (N->getOpcode()) {
1337   default: break;
1338   case ISD::TokenFactor:        return visitTokenFactor(N);
1339   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1340   case ISD::ADD:                return visitADD(N);
1341   case ISD::SUB:                return visitSUB(N);
1342   case ISD::ADDC:               return visitADDC(N);
1343   case ISD::SUBC:               return visitSUBC(N);
1344   case ISD::ADDE:               return visitADDE(N);
1345   case ISD::SUBE:               return visitSUBE(N);
1346   case ISD::MUL:                return visitMUL(N);
1347   case ISD::SDIV:               return visitSDIV(N);
1348   case ISD::UDIV:               return visitUDIV(N);
1349   case ISD::SREM:               return visitSREM(N);
1350   case ISD::UREM:               return visitUREM(N);
1351   case ISD::MULHU:              return visitMULHU(N);
1352   case ISD::MULHS:              return visitMULHS(N);
1353   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1354   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1355   case ISD::SMULO:              return visitSMULO(N);
1356   case ISD::UMULO:              return visitUMULO(N);
1357   case ISD::SDIVREM:            return visitSDIVREM(N);
1358   case ISD::UDIVREM:            return visitUDIVREM(N);
1359   case ISD::SMIN:
1360   case ISD::SMAX:
1361   case ISD::UMIN:
1362   case ISD::UMAX:               return visitIMINMAX(N);
1363   case ISD::AND:                return visitAND(N);
1364   case ISD::OR:                 return visitOR(N);
1365   case ISD::XOR:                return visitXOR(N);
1366   case ISD::SHL:                return visitSHL(N);
1367   case ISD::SRA:                return visitSRA(N);
1368   case ISD::SRL:                return visitSRL(N);
1369   case ISD::ROTR:
1370   case ISD::ROTL:               return visitRotate(N);
1371   case ISD::BSWAP:              return visitBSWAP(N);
1372   case ISD::CTLZ:               return visitCTLZ(N);
1373   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1374   case ISD::CTTZ:               return visitCTTZ(N);
1375   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1376   case ISD::CTPOP:              return visitCTPOP(N);
1377   case ISD::SELECT:             return visitSELECT(N);
1378   case ISD::VSELECT:            return visitVSELECT(N);
1379   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1380   case ISD::SETCC:              return visitSETCC(N);
1381   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1382   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1383   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1384   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1385   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1386   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1387   case ISD::BITCAST:            return visitBITCAST(N);
1388   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1389   case ISD::FADD:               return visitFADD(N);
1390   case ISD::FSUB:               return visitFSUB(N);
1391   case ISD::FMUL:               return visitFMUL(N);
1392   case ISD::FMA:                return visitFMA(N);
1393   case ISD::FDIV:               return visitFDIV(N);
1394   case ISD::FREM:               return visitFREM(N);
1395   case ISD::FSQRT:              return visitFSQRT(N);
1396   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1397   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1398   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1399   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1400   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1401   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1402   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1403   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1404   case ISD::FNEG:               return visitFNEG(N);
1405   case ISD::FABS:               return visitFABS(N);
1406   case ISD::FFLOOR:             return visitFFLOOR(N);
1407   case ISD::FMINNUM:            return visitFMINNUM(N);
1408   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1409   case ISD::FCEIL:              return visitFCEIL(N);
1410   case ISD::FTRUNC:             return visitFTRUNC(N);
1411   case ISD::BRCOND:             return visitBRCOND(N);
1412   case ISD::BR_CC:              return visitBR_CC(N);
1413   case ISD::LOAD:               return visitLOAD(N);
1414   case ISD::STORE:              return visitSTORE(N);
1415   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1416   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1417   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1418   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1419   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1420   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1421   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1422   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1423   case ISD::MGATHER:            return visitMGATHER(N);
1424   case ISD::MLOAD:              return visitMLOAD(N);
1425   case ISD::MSCATTER:           return visitMSCATTER(N);
1426   case ISD::MSTORE:             return visitMSTORE(N);
1427   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1428   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1429   }
1430   return SDValue();
1431 }
1432
1433 SDValue DAGCombiner::combine(SDNode *N) {
1434   SDValue RV = visit(N);
1435
1436   // If nothing happened, try a target-specific DAG combine.
1437   if (!RV.getNode()) {
1438     assert(N->getOpcode() != ISD::DELETED_NODE &&
1439            "Node was deleted but visit returned NULL!");
1440
1441     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1442         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1443
1444       // Expose the DAG combiner to the target combiner impls.
1445       TargetLowering::DAGCombinerInfo
1446         DagCombineInfo(DAG, Level, false, this);
1447
1448       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1449     }
1450   }
1451
1452   // If nothing happened still, try promoting the operation.
1453   if (!RV.getNode()) {
1454     switch (N->getOpcode()) {
1455     default: break;
1456     case ISD::ADD:
1457     case ISD::SUB:
1458     case ISD::MUL:
1459     case ISD::AND:
1460     case ISD::OR:
1461     case ISD::XOR:
1462       RV = PromoteIntBinOp(SDValue(N, 0));
1463       break;
1464     case ISD::SHL:
1465     case ISD::SRA:
1466     case ISD::SRL:
1467       RV = PromoteIntShiftOp(SDValue(N, 0));
1468       break;
1469     case ISD::SIGN_EXTEND:
1470     case ISD::ZERO_EXTEND:
1471     case ISD::ANY_EXTEND:
1472       RV = PromoteExtend(SDValue(N, 0));
1473       break;
1474     case ISD::LOAD:
1475       if (PromoteLoad(SDValue(N, 0)))
1476         RV = SDValue(N, 0);
1477       break;
1478     }
1479   }
1480
1481   // If N is a commutative binary node, try commuting it to enable more
1482   // sdisel CSE.
1483   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1484       N->getNumValues() == 1) {
1485     SDValue N0 = N->getOperand(0);
1486     SDValue N1 = N->getOperand(1);
1487
1488     // Constant operands are canonicalized to RHS.
1489     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1490       SDValue Ops[] = {N1, N0};
1491       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1492                                             N->getFlags());
1493       if (CSENode)
1494         return SDValue(CSENode, 0);
1495     }
1496   }
1497
1498   return RV;
1499 }
1500
1501 /// Given a node, return its input chain if it has one, otherwise return a null
1502 /// sd operand.
1503 static SDValue getInputChainForNode(SDNode *N) {
1504   if (unsigned NumOps = N->getNumOperands()) {
1505     if (N->getOperand(0).getValueType() == MVT::Other)
1506       return N->getOperand(0);
1507     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1508       return N->getOperand(NumOps-1);
1509     for (unsigned i = 1; i < NumOps-1; ++i)
1510       if (N->getOperand(i).getValueType() == MVT::Other)
1511         return N->getOperand(i);
1512   }
1513   return SDValue();
1514 }
1515
1516 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1517   // If N has two operands, where one has an input chain equal to the other,
1518   // the 'other' chain is redundant.
1519   if (N->getNumOperands() == 2) {
1520     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1521       return N->getOperand(0);
1522     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1523       return N->getOperand(1);
1524   }
1525
1526   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1527   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1528   SmallPtrSet<SDNode*, 16> SeenOps;
1529   bool Changed = false;             // If we should replace this token factor.
1530
1531   // Start out with this token factor.
1532   TFs.push_back(N);
1533
1534   // Iterate through token factors.  The TFs grows when new token factors are
1535   // encountered.
1536   for (unsigned i = 0; i < TFs.size(); ++i) {
1537     SDNode *TF = TFs[i];
1538
1539     // Check each of the operands.
1540     for (const SDValue &Op : TF->op_values()) {
1541
1542       switch (Op.getOpcode()) {
1543       case ISD::EntryToken:
1544         // Entry tokens don't need to be added to the list. They are
1545         // redundant.
1546         Changed = true;
1547         break;
1548
1549       case ISD::TokenFactor:
1550         if (Op.hasOneUse() &&
1551             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1552           // Queue up for processing.
1553           TFs.push_back(Op.getNode());
1554           // Clean up in case the token factor is removed.
1555           AddToWorklist(Op.getNode());
1556           Changed = true;
1557           break;
1558         }
1559         // Fall thru
1560
1561       default:
1562         // Only add if it isn't already in the list.
1563         if (SeenOps.insert(Op.getNode()).second)
1564           Ops.push_back(Op);
1565         else
1566           Changed = true;
1567         break;
1568       }
1569     }
1570   }
1571
1572   SDValue Result;
1573
1574   // If we've changed things around then replace token factor.
1575   if (Changed) {
1576     if (Ops.empty()) {
1577       // The entry token is the only possible outcome.
1578       Result = DAG.getEntryNode();
1579     } else {
1580       // New and improved token factor.
1581       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1582     }
1583
1584     // Add users to worklist if AA is enabled, since it may introduce
1585     // a lot of new chained token factors while removing memory deps.
1586     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1587       : DAG.getSubtarget().useAA();
1588     return CombineTo(N, Result, UseAA /*add to worklist*/);
1589   }
1590
1591   return Result;
1592 }
1593
1594 /// MERGE_VALUES can always be eliminated.
1595 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1596   WorklistRemover DeadNodes(*this);
1597   // Replacing results may cause a different MERGE_VALUES to suddenly
1598   // be CSE'd with N, and carry its uses with it. Iterate until no
1599   // uses remain, to ensure that the node can be safely deleted.
1600   // First add the users of this node to the work list so that they
1601   // can be tried again once they have new operands.
1602   AddUsersToWorklist(N);
1603   do {
1604     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1605       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1606   } while (!N->use_empty());
1607   deleteAndRecombine(N);
1608   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1609 }
1610
1611 static bool isNullConstant(SDValue V) {
1612   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1613   return Const != nullptr && Const->isNullValue();
1614 }
1615
1616 static bool isNullFPConstant(SDValue V) {
1617   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1618   return Const != nullptr && Const->isZero() && !Const->isNegative();
1619 }
1620
1621 static bool isAllOnesConstant(SDValue V) {
1622   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1623   return Const != nullptr && Const->isAllOnesValue();
1624 }
1625
1626 static bool isOneConstant(SDValue V) {
1627   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1628   return Const != nullptr && Const->isOne();
1629 }
1630
1631 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1632 /// ContantSDNode pointer else nullptr.
1633 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1634   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1635   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1636 }
1637
1638 SDValue DAGCombiner::visitADD(SDNode *N) {
1639   SDValue N0 = N->getOperand(0);
1640   SDValue N1 = N->getOperand(1);
1641   EVT VT = N0.getValueType();
1642
1643   // fold vector ops
1644   if (VT.isVector()) {
1645     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1646       return FoldedVOp;
1647
1648     // fold (add x, 0) -> x, vector edition
1649     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1650       return N0;
1651     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1652       return N1;
1653   }
1654
1655   // fold (add x, undef) -> undef
1656   if (N0.getOpcode() == ISD::UNDEF)
1657     return N0;
1658   if (N1.getOpcode() == ISD::UNDEF)
1659     return N1;
1660   // fold (add c1, c2) -> c1+c2
1661   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1662   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1663   if (N0C && N1C)
1664     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1665   // canonicalize constant to RHS
1666   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1667      !isConstantIntBuildVectorOrConstantInt(N1))
1668     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1669   // fold (add x, 0) -> x
1670   if (isNullConstant(N1))
1671     return N0;
1672   // fold (add Sym, c) -> Sym+c
1673   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1674     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1675         GA->getOpcode() == ISD::GlobalAddress)
1676       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1677                                   GA->getOffset() +
1678                                     (uint64_t)N1C->getSExtValue());
1679   // fold ((c1-A)+c2) -> (c1+c2)-A
1680   if (N1C && N0.getOpcode() == ISD::SUB)
1681     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1682       SDLoc DL(N);
1683       return DAG.getNode(ISD::SUB, DL, VT,
1684                          DAG.getConstant(N1C->getAPIntValue()+
1685                                          N0C->getAPIntValue(), DL, VT),
1686                          N0.getOperand(1));
1687     }
1688   // reassociate add
1689   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1690     return RADD;
1691   // fold ((0-A) + B) -> B-A
1692   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1693     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1694   // fold (A + (0-B)) -> A-B
1695   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1696     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1697   // fold (A+(B-A)) -> B
1698   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1699     return N1.getOperand(0);
1700   // fold ((B-A)+A) -> B
1701   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1702     return N0.getOperand(0);
1703   // fold (A+(B-(A+C))) to (B-C)
1704   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1705       N0 == N1.getOperand(1).getOperand(0))
1706     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1707                        N1.getOperand(1).getOperand(1));
1708   // fold (A+(B-(C+A))) to (B-C)
1709   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1710       N0 == N1.getOperand(1).getOperand(1))
1711     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1712                        N1.getOperand(1).getOperand(0));
1713   // fold (A+((B-A)+or-C)) to (B+or-C)
1714   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1715       N1.getOperand(0).getOpcode() == ISD::SUB &&
1716       N0 == N1.getOperand(0).getOperand(1))
1717     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1718                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1719
1720   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1721   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1722     SDValue N00 = N0.getOperand(0);
1723     SDValue N01 = N0.getOperand(1);
1724     SDValue N10 = N1.getOperand(0);
1725     SDValue N11 = N1.getOperand(1);
1726
1727     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1728       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1729                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1730                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1731   }
1732
1733   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1734     return SDValue(N, 0);
1735
1736   // fold (a+b) -> (a|b) iff a and b share no bits.
1737   if (VT.isInteger() && !VT.isVector()) {
1738     APInt LHSZero, LHSOne;
1739     APInt RHSZero, RHSOne;
1740     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1741
1742     if (LHSZero.getBoolValue()) {
1743       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1744
1745       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1746       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1747       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1748         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1749           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1750       }
1751     }
1752   }
1753
1754   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1755   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1756       isNullConstant(N1.getOperand(0).getOperand(0)))
1757     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1758                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1759                                    N1.getOperand(0).getOperand(1),
1760                                    N1.getOperand(1)));
1761   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1762       isNullConstant(N0.getOperand(0).getOperand(0)))
1763     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1764                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1765                                    N0.getOperand(0).getOperand(1),
1766                                    N0.getOperand(1)));
1767
1768   if (N1.getOpcode() == ISD::AND) {
1769     SDValue AndOp0 = N1.getOperand(0);
1770     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1771     unsigned DestBits = VT.getScalarType().getSizeInBits();
1772
1773     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1774     // and similar xforms where the inner op is either ~0 or 0.
1775     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1776       SDLoc DL(N);
1777       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1778     }
1779   }
1780
1781   // add (sext i1), X -> sub X, (zext i1)
1782   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1783       N0.getOperand(0).getValueType() == MVT::i1 &&
1784       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1785     SDLoc DL(N);
1786     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1787     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1788   }
1789
1790   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1791   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1792     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1793     if (TN->getVT() == MVT::i1) {
1794       SDLoc DL(N);
1795       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1796                                  DAG.getConstant(1, DL, VT));
1797       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1798     }
1799   }
1800
1801   return SDValue();
1802 }
1803
1804 SDValue DAGCombiner::visitADDC(SDNode *N) {
1805   SDValue N0 = N->getOperand(0);
1806   SDValue N1 = N->getOperand(1);
1807   EVT VT = N0.getValueType();
1808
1809   // If the flag result is dead, turn this into an ADD.
1810   if (!N->hasAnyUseOfValue(1))
1811     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1812                      DAG.getNode(ISD::CARRY_FALSE,
1813                                  SDLoc(N), MVT::Glue));
1814
1815   // canonicalize constant to RHS.
1816   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1817   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1818   if (N0C && !N1C)
1819     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1820
1821   // fold (addc x, 0) -> x + no carry out
1822   if (isNullConstant(N1))
1823     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1824                                         SDLoc(N), MVT::Glue));
1825
1826   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1827   APInt LHSZero, LHSOne;
1828   APInt RHSZero, RHSOne;
1829   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1830
1831   if (LHSZero.getBoolValue()) {
1832     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1833
1834     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1835     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1836     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1837       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1838                        DAG.getNode(ISD::CARRY_FALSE,
1839                                    SDLoc(N), MVT::Glue));
1840   }
1841
1842   return SDValue();
1843 }
1844
1845 SDValue DAGCombiner::visitADDE(SDNode *N) {
1846   SDValue N0 = N->getOperand(0);
1847   SDValue N1 = N->getOperand(1);
1848   SDValue CarryIn = N->getOperand(2);
1849
1850   // canonicalize constant to RHS
1851   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1852   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1853   if (N0C && !N1C)
1854     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1855                        N1, N0, CarryIn);
1856
1857   // fold (adde x, y, false) -> (addc x, y)
1858   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1859     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1860
1861   return SDValue();
1862 }
1863
1864 // Since it may not be valid to emit a fold to zero for vector initializers
1865 // check if we can before folding.
1866 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1867                              SelectionDAG &DAG,
1868                              bool LegalOperations, bool LegalTypes) {
1869   if (!VT.isVector())
1870     return DAG.getConstant(0, DL, VT);
1871   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1872     return DAG.getConstant(0, DL, VT);
1873   return SDValue();
1874 }
1875
1876 SDValue DAGCombiner::visitSUB(SDNode *N) {
1877   SDValue N0 = N->getOperand(0);
1878   SDValue N1 = N->getOperand(1);
1879   EVT VT = N0.getValueType();
1880
1881   // fold vector ops
1882   if (VT.isVector()) {
1883     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1884       return FoldedVOp;
1885
1886     // fold (sub x, 0) -> x, vector edition
1887     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1888       return N0;
1889   }
1890
1891   // fold (sub x, x) -> 0
1892   // FIXME: Refactor this and xor and other similar operations together.
1893   if (N0 == N1)
1894     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1895   // fold (sub c1, c2) -> c1-c2
1896   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1897   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1898   if (N0C && N1C)
1899     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1900   // fold (sub x, c) -> (add x, -c)
1901   if (N1C) {
1902     SDLoc DL(N);
1903     return DAG.getNode(ISD::ADD, DL, VT, N0,
1904                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1905   }
1906   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1907   if (isAllOnesConstant(N0))
1908     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1909   // fold A-(A-B) -> B
1910   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1911     return N1.getOperand(1);
1912   // fold (A+B)-A -> B
1913   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1914     return N0.getOperand(1);
1915   // fold (A+B)-B -> A
1916   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1917     return N0.getOperand(0);
1918   // fold C2-(A+C1) -> (C2-C1)-A
1919   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1920     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1921   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1922     SDLoc DL(N);
1923     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1924                                    DL, VT);
1925     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1926                        N1.getOperand(0));
1927   }
1928   // fold ((A+(B+or-C))-B) -> A+or-C
1929   if (N0.getOpcode() == ISD::ADD &&
1930       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1931        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1932       N0.getOperand(1).getOperand(0) == N1)
1933     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1934                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1935   // fold ((A+(C+B))-B) -> A+C
1936   if (N0.getOpcode() == ISD::ADD &&
1937       N0.getOperand(1).getOpcode() == ISD::ADD &&
1938       N0.getOperand(1).getOperand(1) == N1)
1939     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1940                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1941   // fold ((A-(B-C))-C) -> A-B
1942   if (N0.getOpcode() == ISD::SUB &&
1943       N0.getOperand(1).getOpcode() == ISD::SUB &&
1944       N0.getOperand(1).getOperand(1) == N1)
1945     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1946                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1947
1948   // If either operand of a sub is undef, the result is undef
1949   if (N0.getOpcode() == ISD::UNDEF)
1950     return N0;
1951   if (N1.getOpcode() == ISD::UNDEF)
1952     return N1;
1953
1954   // If the relocation model supports it, consider symbol offsets.
1955   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1956     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1957       // fold (sub Sym, c) -> Sym-c
1958       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1959         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1960                                     GA->getOffset() -
1961                                       (uint64_t)N1C->getSExtValue());
1962       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1963       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1964         if (GA->getGlobal() == GB->getGlobal())
1965           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1966                                  SDLoc(N), VT);
1967     }
1968
1969   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1970   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1971     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1972     if (TN->getVT() == MVT::i1) {
1973       SDLoc DL(N);
1974       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1975                                  DAG.getConstant(1, DL, VT));
1976       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1977     }
1978   }
1979
1980   return SDValue();
1981 }
1982
1983 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1984   SDValue N0 = N->getOperand(0);
1985   SDValue N1 = N->getOperand(1);
1986   EVT VT = N0.getValueType();
1987
1988   // If the flag result is dead, turn this into an SUB.
1989   if (!N->hasAnyUseOfValue(1))
1990     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1991                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1992                                  MVT::Glue));
1993
1994   // fold (subc x, x) -> 0 + no borrow
1995   if (N0 == N1) {
1996     SDLoc DL(N);
1997     return CombineTo(N, DAG.getConstant(0, DL, VT),
1998                      DAG.getNode(ISD::CARRY_FALSE, DL,
1999                                  MVT::Glue));
2000   }
2001
2002   // fold (subc x, 0) -> x + no borrow
2003   if (isNullConstant(N1))
2004     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2005                                         MVT::Glue));
2006
2007   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2008   if (isAllOnesConstant(N0))
2009     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2010                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2011                                  MVT::Glue));
2012
2013   return SDValue();
2014 }
2015
2016 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2017   SDValue N0 = N->getOperand(0);
2018   SDValue N1 = N->getOperand(1);
2019   SDValue CarryIn = N->getOperand(2);
2020
2021   // fold (sube x, y, false) -> (subc x, y)
2022   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2023     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2024
2025   return SDValue();
2026 }
2027
2028 SDValue DAGCombiner::visitMUL(SDNode *N) {
2029   SDValue N0 = N->getOperand(0);
2030   SDValue N1 = N->getOperand(1);
2031   EVT VT = N0.getValueType();
2032
2033   // fold (mul x, undef) -> 0
2034   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2035     return DAG.getConstant(0, SDLoc(N), VT);
2036
2037   bool N0IsConst = false;
2038   bool N1IsConst = false;
2039   bool N1IsOpaqueConst = false;
2040   bool N0IsOpaqueConst = false;
2041   APInt ConstValue0, ConstValue1;
2042   // fold vector ops
2043   if (VT.isVector()) {
2044     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2045       return FoldedVOp;
2046
2047     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2048     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2049   } else {
2050     N0IsConst = isa<ConstantSDNode>(N0);
2051     if (N0IsConst) {
2052       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2053       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2054     }
2055     N1IsConst = isa<ConstantSDNode>(N1);
2056     if (N1IsConst) {
2057       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2058       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2059     }
2060   }
2061
2062   // fold (mul c1, c2) -> c1*c2
2063   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2064     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2065                                       N0.getNode(), N1.getNode());
2066
2067   // canonicalize constant to RHS (vector doesn't have to splat)
2068   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2069      !isConstantIntBuildVectorOrConstantInt(N1))
2070     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2071   // fold (mul x, 0) -> 0
2072   if (N1IsConst && ConstValue1 == 0)
2073     return N1;
2074   // We require a splat of the entire scalar bit width for non-contiguous
2075   // bit patterns.
2076   bool IsFullSplat =
2077     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2078   // fold (mul x, 1) -> x
2079   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2080     return N0;
2081   // fold (mul x, -1) -> 0-x
2082   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2083     SDLoc DL(N);
2084     return DAG.getNode(ISD::SUB, DL, VT,
2085                        DAG.getConstant(0, DL, VT), N0);
2086   }
2087   // fold (mul x, (1 << c)) -> x << c
2088   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2089       IsFullSplat) {
2090     SDLoc DL(N);
2091     return DAG.getNode(ISD::SHL, DL, VT, N0,
2092                        DAG.getConstant(ConstValue1.logBase2(), DL,
2093                                        getShiftAmountTy(N0.getValueType())));
2094   }
2095   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2096   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2097       IsFullSplat) {
2098     unsigned Log2Val = (-ConstValue1).logBase2();
2099     SDLoc DL(N);
2100     // FIXME: If the input is something that is easily negated (e.g. a
2101     // single-use add), we should put the negate there.
2102     return DAG.getNode(ISD::SUB, DL, VT,
2103                        DAG.getConstant(0, DL, VT),
2104                        DAG.getNode(ISD::SHL, DL, VT, N0,
2105                             DAG.getConstant(Log2Val, DL,
2106                                       getShiftAmountTy(N0.getValueType()))));
2107   }
2108
2109   APInt Val;
2110   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2111   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2112       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2113                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2114     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2115                              N1, N0.getOperand(1));
2116     AddToWorklist(C3.getNode());
2117     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2118                        N0.getOperand(0), C3);
2119   }
2120
2121   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2122   // use.
2123   {
2124     SDValue Sh(nullptr,0), Y(nullptr,0);
2125     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2126     if (N0.getOpcode() == ISD::SHL &&
2127         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2128                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2129         N0.getNode()->hasOneUse()) {
2130       Sh = N0; Y = N1;
2131     } else if (N1.getOpcode() == ISD::SHL &&
2132                isa<ConstantSDNode>(N1.getOperand(1)) &&
2133                N1.getNode()->hasOneUse()) {
2134       Sh = N1; Y = N0;
2135     }
2136
2137     if (Sh.getNode()) {
2138       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2139                                 Sh.getOperand(0), Y);
2140       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2141                          Mul, Sh.getOperand(1));
2142     }
2143   }
2144
2145   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2146   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2147       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2148                      isa<ConstantSDNode>(N0.getOperand(1))))
2149     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2150                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2151                                    N0.getOperand(0), N1),
2152                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2153                                    N0.getOperand(1), N1));
2154
2155   // reassociate mul
2156   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2157     return RMUL;
2158
2159   return SDValue();
2160 }
2161
2162 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2163   SDValue N0 = N->getOperand(0);
2164   SDValue N1 = N->getOperand(1);
2165   EVT VT = N->getValueType(0);
2166
2167   // fold vector ops
2168   if (VT.isVector())
2169     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2170       return FoldedVOp;
2171
2172   // fold (sdiv c1, c2) -> c1/c2
2173   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2174   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2175   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2176     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2177   // fold (sdiv X, 1) -> X
2178   if (N1C && N1C->isOne())
2179     return N0;
2180   // fold (sdiv X, -1) -> 0-X
2181   if (N1C && N1C->isAllOnesValue()) {
2182     SDLoc DL(N);
2183     return DAG.getNode(ISD::SUB, DL, VT,
2184                        DAG.getConstant(0, DL, VT), N0);
2185   }
2186   // If we know the sign bits of both operands are zero, strength reduce to a
2187   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2188   if (!VT.isVector()) {
2189     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2190       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2191                          N0, N1);
2192   }
2193
2194   // fold (sdiv X, pow2) -> simple ops after legalize
2195   // FIXME: We check for the exact bit here because the generic lowering gives
2196   // better results in that case. The target-specific lowering should learn how
2197   // to handle exact sdivs efficiently.
2198   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2199       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2200       (N1C->getAPIntValue().isPowerOf2() ||
2201        (-N1C->getAPIntValue()).isPowerOf2())) {
2202     // Target-specific implementation of sdiv x, pow2.
2203     if (SDValue Res = BuildSDIVPow2(N))
2204       return Res;
2205
2206     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2207     SDLoc DL(N);
2208
2209     // Splat the sign bit into the register
2210     SDValue SGN =
2211         DAG.getNode(ISD::SRA, DL, VT, N0,
2212                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2213                                     getShiftAmountTy(N0.getValueType())));
2214     AddToWorklist(SGN.getNode());
2215
2216     // Add (N0 < 0) ? abs2 - 1 : 0;
2217     SDValue SRL =
2218         DAG.getNode(ISD::SRL, DL, VT, SGN,
2219                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2220                                     getShiftAmountTy(SGN.getValueType())));
2221     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2222     AddToWorklist(SRL.getNode());
2223     AddToWorklist(ADD.getNode());    // Divide by pow2
2224     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2225                   DAG.getConstant(lg2, DL,
2226                                   getShiftAmountTy(ADD.getValueType())));
2227
2228     // If we're dividing by a positive value, we're done.  Otherwise, we must
2229     // negate the result.
2230     if (N1C->getAPIntValue().isNonNegative())
2231       return SRA;
2232
2233     AddToWorklist(SRA.getNode());
2234     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2235   }
2236
2237   // If integer divide is expensive and we satisfy the requirements, emit an
2238   // alternate sequence.  Targets may check function attributes for size/speed
2239   // trade-offs.
2240   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2241   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2242     if (SDValue Op = BuildSDIV(N))
2243       return Op;
2244
2245   // undef / X -> 0
2246   if (N0.getOpcode() == ISD::UNDEF)
2247     return DAG.getConstant(0, SDLoc(N), VT);
2248   // X / undef -> undef
2249   if (N1.getOpcode() == ISD::UNDEF)
2250     return N1;
2251
2252   return SDValue();
2253 }
2254
2255 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2256   SDValue N0 = N->getOperand(0);
2257   SDValue N1 = N->getOperand(1);
2258   EVT VT = N->getValueType(0);
2259
2260   // fold vector ops
2261   if (VT.isVector())
2262     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2263       return FoldedVOp;
2264
2265   // fold (udiv c1, c2) -> c1/c2
2266   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2267   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2268   if (N0C && N1C)
2269     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2270                                                     N0C, N1C))
2271       return Folded;
2272   // fold (udiv x, (1 << c)) -> x >>u c
2273   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2274     SDLoc DL(N);
2275     return DAG.getNode(ISD::SRL, DL, VT, N0,
2276                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2277                                        getShiftAmountTy(N0.getValueType())));
2278   }
2279   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2280   if (N1.getOpcode() == ISD::SHL) {
2281     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2282       if (SHC->getAPIntValue().isPowerOf2()) {
2283         EVT ADDVT = N1.getOperand(1).getValueType();
2284         SDLoc DL(N);
2285         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2286                                   N1.getOperand(1),
2287                                   DAG.getConstant(SHC->getAPIntValue()
2288                                                                   .logBase2(),
2289                                                   DL, ADDVT));
2290         AddToWorklist(Add.getNode());
2291         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2292       }
2293     }
2294   }
2295
2296   // fold (udiv x, c) -> alternate
2297   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2298   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2299     if (SDValue Op = BuildUDIV(N))
2300       return Op;
2301
2302   // undef / X -> 0
2303   if (N0.getOpcode() == ISD::UNDEF)
2304     return DAG.getConstant(0, SDLoc(N), VT);
2305   // X / undef -> undef
2306   if (N1.getOpcode() == ISD::UNDEF)
2307     return N1;
2308
2309   return SDValue();
2310 }
2311
2312 SDValue DAGCombiner::visitSREM(SDNode *N) {
2313   SDValue N0 = N->getOperand(0);
2314   SDValue N1 = N->getOperand(1);
2315   EVT VT = N->getValueType(0);
2316
2317   // fold (srem c1, c2) -> c1%c2
2318   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2319   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2320   if (N0C && N1C)
2321     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2322                                                     N0C, N1C))
2323       return Folded;
2324   // If we know the sign bits of both operands are zero, strength reduce to a
2325   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2326   if (!VT.isVector()) {
2327     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2328       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2329   }
2330
2331   // If X/C can be simplified by the division-by-constant logic, lower
2332   // X%C to the equivalent of X-X/C*C.
2333   if (N1C && !N1C->isNullValue()) {
2334     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2335     AddToWorklist(Div.getNode());
2336     SDValue OptimizedDiv = combine(Div.getNode());
2337     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2338       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2339                                 OptimizedDiv, N1);
2340       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2341       AddToWorklist(Mul.getNode());
2342       return Sub;
2343     }
2344   }
2345
2346   // undef % X -> 0
2347   if (N0.getOpcode() == ISD::UNDEF)
2348     return DAG.getConstant(0, SDLoc(N), VT);
2349   // X % undef -> undef
2350   if (N1.getOpcode() == ISD::UNDEF)
2351     return N1;
2352
2353   return SDValue();
2354 }
2355
2356 SDValue DAGCombiner::visitUREM(SDNode *N) {
2357   SDValue N0 = N->getOperand(0);
2358   SDValue N1 = N->getOperand(1);
2359   EVT VT = N->getValueType(0);
2360
2361   // fold (urem c1, c2) -> c1%c2
2362   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2363   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2364   if (N0C && N1C)
2365     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2366                                                     N0C, N1C))
2367       return Folded;
2368   // fold (urem x, pow2) -> (and x, pow2-1)
2369   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2370       N1C->getAPIntValue().isPowerOf2()) {
2371     SDLoc DL(N);
2372     return DAG.getNode(ISD::AND, DL, VT, N0,
2373                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2374   }
2375   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2376   if (N1.getOpcode() == ISD::SHL) {
2377     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2378       if (SHC->getAPIntValue().isPowerOf2()) {
2379         SDLoc DL(N);
2380         SDValue Add =
2381           DAG.getNode(ISD::ADD, DL, VT, N1,
2382                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2383                                  VT));
2384         AddToWorklist(Add.getNode());
2385         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2386       }
2387     }
2388   }
2389
2390   // If X/C can be simplified by the division-by-constant logic, lower
2391   // X%C to the equivalent of X-X/C*C.
2392   if (N1C && !N1C->isNullValue()) {
2393     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2394     AddToWorklist(Div.getNode());
2395     SDValue OptimizedDiv = combine(Div.getNode());
2396     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2397       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2398                                 OptimizedDiv, N1);
2399       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2400       AddToWorklist(Mul.getNode());
2401       return Sub;
2402     }
2403   }
2404
2405   // undef % X -> 0
2406   if (N0.getOpcode() == ISD::UNDEF)
2407     return DAG.getConstant(0, SDLoc(N), VT);
2408   // X % undef -> undef
2409   if (N1.getOpcode() == ISD::UNDEF)
2410     return N1;
2411
2412   return SDValue();
2413 }
2414
2415 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2416   SDValue N0 = N->getOperand(0);
2417   SDValue N1 = N->getOperand(1);
2418   EVT VT = N->getValueType(0);
2419   SDLoc DL(N);
2420
2421   // fold (mulhs x, 0) -> 0
2422   if (isNullConstant(N1))
2423     return N1;
2424   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2425   if (isOneConstant(N1)) {
2426     SDLoc DL(N);
2427     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2428                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2429                                        DL,
2430                                        getShiftAmountTy(N0.getValueType())));
2431   }
2432   // fold (mulhs x, undef) -> 0
2433   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2434     return DAG.getConstant(0, SDLoc(N), VT);
2435
2436   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2437   // plus a shift.
2438   if (VT.isSimple() && !VT.isVector()) {
2439     MVT Simple = VT.getSimpleVT();
2440     unsigned SimpleSize = Simple.getSizeInBits();
2441     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2442     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2443       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2444       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2445       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2446       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2447             DAG.getConstant(SimpleSize, DL,
2448                             getShiftAmountTy(N1.getValueType())));
2449       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2450     }
2451   }
2452
2453   return SDValue();
2454 }
2455
2456 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2457   SDValue N0 = N->getOperand(0);
2458   SDValue N1 = N->getOperand(1);
2459   EVT VT = N->getValueType(0);
2460   SDLoc DL(N);
2461
2462   // fold (mulhu x, 0) -> 0
2463   if (isNullConstant(N1))
2464     return N1;
2465   // fold (mulhu x, 1) -> 0
2466   if (isOneConstant(N1))
2467     return DAG.getConstant(0, DL, N0.getValueType());
2468   // fold (mulhu x, undef) -> 0
2469   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2470     return DAG.getConstant(0, DL, VT);
2471
2472   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2473   // plus a shift.
2474   if (VT.isSimple() && !VT.isVector()) {
2475     MVT Simple = VT.getSimpleVT();
2476     unsigned SimpleSize = Simple.getSizeInBits();
2477     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2478     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2479       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2480       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2481       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2482       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2483             DAG.getConstant(SimpleSize, DL,
2484                             getShiftAmountTy(N1.getValueType())));
2485       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2486     }
2487   }
2488
2489   return SDValue();
2490 }
2491
2492 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2493 /// give the opcodes for the two computations that are being performed. Return
2494 /// true if a simplification was made.
2495 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2496                                                 unsigned HiOp) {
2497   // If the high half is not needed, just compute the low half.
2498   bool HiExists = N->hasAnyUseOfValue(1);
2499   if (!HiExists &&
2500       (!LegalOperations ||
2501        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2502     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2503     return CombineTo(N, Res, Res);
2504   }
2505
2506   // If the low half is not needed, just compute the high half.
2507   bool LoExists = N->hasAnyUseOfValue(0);
2508   if (!LoExists &&
2509       (!LegalOperations ||
2510        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2511     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2512     return CombineTo(N, Res, Res);
2513   }
2514
2515   // If both halves are used, return as it is.
2516   if (LoExists && HiExists)
2517     return SDValue();
2518
2519   // If the two computed results can be simplified separately, separate them.
2520   if (LoExists) {
2521     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2522     AddToWorklist(Lo.getNode());
2523     SDValue LoOpt = combine(Lo.getNode());
2524     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2525         (!LegalOperations ||
2526          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2527       return CombineTo(N, LoOpt, LoOpt);
2528   }
2529
2530   if (HiExists) {
2531     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2532     AddToWorklist(Hi.getNode());
2533     SDValue HiOpt = combine(Hi.getNode());
2534     if (HiOpt.getNode() && HiOpt != Hi &&
2535         (!LegalOperations ||
2536          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2537       return CombineTo(N, HiOpt, HiOpt);
2538   }
2539
2540   return SDValue();
2541 }
2542
2543 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2544   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2545     return Res;
2546
2547   EVT VT = N->getValueType(0);
2548   SDLoc DL(N);
2549
2550   // If the type is twice as wide is legal, transform the mulhu to a wider
2551   // multiply plus a shift.
2552   if (VT.isSimple() && !VT.isVector()) {
2553     MVT Simple = VT.getSimpleVT();
2554     unsigned SimpleSize = Simple.getSizeInBits();
2555     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2556     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2557       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2558       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2559       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2560       // Compute the high part as N1.
2561       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2562             DAG.getConstant(SimpleSize, DL,
2563                             getShiftAmountTy(Lo.getValueType())));
2564       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2565       // Compute the low part as N0.
2566       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2567       return CombineTo(N, Lo, Hi);
2568     }
2569   }
2570
2571   return SDValue();
2572 }
2573
2574 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2575   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2576     return Res;
2577
2578   EVT VT = N->getValueType(0);
2579   SDLoc DL(N);
2580
2581   // If the type is twice as wide is legal, transform the mulhu to a wider
2582   // multiply plus a shift.
2583   if (VT.isSimple() && !VT.isVector()) {
2584     MVT Simple = VT.getSimpleVT();
2585     unsigned SimpleSize = Simple.getSizeInBits();
2586     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2587     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2588       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2589       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2590       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2591       // Compute the high part as N1.
2592       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2593             DAG.getConstant(SimpleSize, DL,
2594                             getShiftAmountTy(Lo.getValueType())));
2595       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2596       // Compute the low part as N0.
2597       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2598       return CombineTo(N, Lo, Hi);
2599     }
2600   }
2601
2602   return SDValue();
2603 }
2604
2605 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2606   // (smulo x, 2) -> (saddo x, x)
2607   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2608     if (C2->getAPIntValue() == 2)
2609       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2610                          N->getOperand(0), N->getOperand(0));
2611
2612   return SDValue();
2613 }
2614
2615 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2616   // (umulo x, 2) -> (uaddo x, x)
2617   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2618     if (C2->getAPIntValue() == 2)
2619       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2620                          N->getOperand(0), N->getOperand(0));
2621
2622   return SDValue();
2623 }
2624
2625 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2626   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2627     return Res;
2628
2629   return SDValue();
2630 }
2631
2632 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2633   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2634     return Res;
2635
2636   return SDValue();
2637 }
2638
2639 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2640   SDValue N0 = N->getOperand(0);
2641   SDValue N1 = N->getOperand(1);
2642   EVT VT = N0.getValueType();
2643
2644   // fold vector ops
2645   if (VT.isVector())
2646     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2647       return FoldedVOp;
2648
2649   // fold (add c1, c2) -> c1+c2
2650   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2651   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2652   if (N0C && N1C)
2653     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2654
2655   // canonicalize constant to RHS
2656   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2657      !isConstantIntBuildVectorOrConstantInt(N1))
2658     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2659
2660   return SDValue();
2661 }
2662
2663 /// If this is a binary operator with two operands of the same opcode, try to
2664 /// simplify it.
2665 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2666   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2667   EVT VT = N0.getValueType();
2668   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2669
2670   // Bail early if none of these transforms apply.
2671   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2672
2673   // For each of OP in AND/OR/XOR:
2674   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2675   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2676   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2677   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2678   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2679   //
2680   // do not sink logical op inside of a vector extend, since it may combine
2681   // into a vsetcc.
2682   EVT Op0VT = N0.getOperand(0).getValueType();
2683   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2684        N0.getOpcode() == ISD::SIGN_EXTEND ||
2685        N0.getOpcode() == ISD::BSWAP ||
2686        // Avoid infinite looping with PromoteIntBinOp.
2687        (N0.getOpcode() == ISD::ANY_EXTEND &&
2688         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2689        (N0.getOpcode() == ISD::TRUNCATE &&
2690         (!TLI.isZExtFree(VT, Op0VT) ||
2691          !TLI.isTruncateFree(Op0VT, VT)) &&
2692         TLI.isTypeLegal(Op0VT))) &&
2693       !VT.isVector() &&
2694       Op0VT == N1.getOperand(0).getValueType() &&
2695       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2696     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2697                                  N0.getOperand(0).getValueType(),
2698                                  N0.getOperand(0), N1.getOperand(0));
2699     AddToWorklist(ORNode.getNode());
2700     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2701   }
2702
2703   // For each of OP in SHL/SRL/SRA/AND...
2704   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2705   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2706   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2707   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2708        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2709       N0.getOperand(1) == N1.getOperand(1)) {
2710     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2711                                  N0.getOperand(0).getValueType(),
2712                                  N0.getOperand(0), N1.getOperand(0));
2713     AddToWorklist(ORNode.getNode());
2714     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2715                        ORNode, N0.getOperand(1));
2716   }
2717
2718   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2719   // Only perform this optimization after type legalization and before
2720   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2721   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2722   // we don't want to undo this promotion.
2723   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2724   // on scalars.
2725   if ((N0.getOpcode() == ISD::BITCAST ||
2726        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2727       Level == AfterLegalizeTypes) {
2728     SDValue In0 = N0.getOperand(0);
2729     SDValue In1 = N1.getOperand(0);
2730     EVT In0Ty = In0.getValueType();
2731     EVT In1Ty = In1.getValueType();
2732     SDLoc DL(N);
2733     // If both incoming values are integers, and the original types are the
2734     // same.
2735     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2736       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2737       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2738       AddToWorklist(Op.getNode());
2739       return BC;
2740     }
2741   }
2742
2743   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2744   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2745   // If both shuffles use the same mask, and both shuffle within a single
2746   // vector, then it is worthwhile to move the swizzle after the operation.
2747   // The type-legalizer generates this pattern when loading illegal
2748   // vector types from memory. In many cases this allows additional shuffle
2749   // optimizations.
2750   // There are other cases where moving the shuffle after the xor/and/or
2751   // is profitable even if shuffles don't perform a swizzle.
2752   // If both shuffles use the same mask, and both shuffles have the same first
2753   // or second operand, then it might still be profitable to move the shuffle
2754   // after the xor/and/or operation.
2755   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2756     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2757     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2758
2759     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2760            "Inputs to shuffles are not the same type");
2761
2762     // Check that both shuffles use the same mask. The masks are known to be of
2763     // the same length because the result vector type is the same.
2764     // Check also that shuffles have only one use to avoid introducing extra
2765     // instructions.
2766     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2767         SVN0->getMask().equals(SVN1->getMask())) {
2768       SDValue ShOp = N0->getOperand(1);
2769
2770       // Don't try to fold this node if it requires introducing a
2771       // build vector of all zeros that might be illegal at this stage.
2772       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2773         if (!LegalTypes)
2774           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2775         else
2776           ShOp = SDValue();
2777       }
2778
2779       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2780       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2781       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2782       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2783         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2784                                       N0->getOperand(0), N1->getOperand(0));
2785         AddToWorklist(NewNode.getNode());
2786         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2787                                     &SVN0->getMask()[0]);
2788       }
2789
2790       // Don't try to fold this node if it requires introducing a
2791       // build vector of all zeros that might be illegal at this stage.
2792       ShOp = N0->getOperand(0);
2793       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2794         if (!LegalTypes)
2795           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2796         else
2797           ShOp = SDValue();
2798       }
2799
2800       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2801       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2802       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2803       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2804         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2805                                       N0->getOperand(1), N1->getOperand(1));
2806         AddToWorklist(NewNode.getNode());
2807         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2808                                     &SVN0->getMask()[0]);
2809       }
2810     }
2811   }
2812
2813   return SDValue();
2814 }
2815
2816 /// This contains all DAGCombine rules which reduce two values combined by
2817 /// an And operation to a single value. This makes them reusable in the context
2818 /// of visitSELECT(). Rules involving constants are not included as
2819 /// visitSELECT() already handles those cases.
2820 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2821                                   SDNode *LocReference) {
2822   EVT VT = N1.getValueType();
2823
2824   // fold (and x, undef) -> 0
2825   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2826     return DAG.getConstant(0, SDLoc(LocReference), VT);
2827   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2828   SDValue LL, LR, RL, RR, CC0, CC1;
2829   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2830     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2831     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2832
2833     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2834         LL.getValueType().isInteger()) {
2835       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2836       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2837         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2838                                      LR.getValueType(), LL, RL);
2839         AddToWorklist(ORNode.getNode());
2840         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2841       }
2842       if (isAllOnesConstant(LR)) {
2843         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2844         if (Op1 == ISD::SETEQ) {
2845           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2846                                         LR.getValueType(), LL, RL);
2847           AddToWorklist(ANDNode.getNode());
2848           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2849         }
2850         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2851         if (Op1 == ISD::SETGT) {
2852           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2853                                        LR.getValueType(), LL, RL);
2854           AddToWorklist(ORNode.getNode());
2855           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2856         }
2857       }
2858     }
2859     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2860     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2861         Op0 == Op1 && LL.getValueType().isInteger() &&
2862       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2863                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2864       SDLoc DL(N0);
2865       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2866                                     LL, DAG.getConstant(1, DL,
2867                                                         LL.getValueType()));
2868       AddToWorklist(ADDNode.getNode());
2869       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2870                           DAG.getConstant(2, DL, LL.getValueType()),
2871                           ISD::SETUGE);
2872     }
2873     // canonicalize equivalent to ll == rl
2874     if (LL == RR && LR == RL) {
2875       Op1 = ISD::getSetCCSwappedOperands(Op1);
2876       std::swap(RL, RR);
2877     }
2878     if (LL == RL && LR == RR) {
2879       bool isInteger = LL.getValueType().isInteger();
2880       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2881       if (Result != ISD::SETCC_INVALID &&
2882           (!LegalOperations ||
2883            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2884             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2885         EVT CCVT = getSetCCResultType(LL.getValueType());
2886         if (N0.getValueType() == CCVT ||
2887             (!LegalOperations && N0.getValueType() == MVT::i1))
2888           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2889                               LL, LR, Result);
2890       }
2891     }
2892   }
2893
2894   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2895       VT.getSizeInBits() <= 64) {
2896     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2897       APInt ADDC = ADDI->getAPIntValue();
2898       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2899         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2900         // immediate for an add, but it is legal if its top c2 bits are set,
2901         // transform the ADD so the immediate doesn't need to be materialized
2902         // in a register.
2903         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2904           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2905                                              SRLI->getZExtValue());
2906           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2907             ADDC |= Mask;
2908             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2909               SDLoc DL(N0);
2910               SDValue NewAdd =
2911                 DAG.getNode(ISD::ADD, DL, VT,
2912                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2913               CombineTo(N0.getNode(), NewAdd);
2914               // Return N so it doesn't get rechecked!
2915               return SDValue(LocReference, 0);
2916             }
2917           }
2918         }
2919       }
2920     }
2921   }
2922
2923   return SDValue();
2924 }
2925
2926 SDValue DAGCombiner::visitAND(SDNode *N) {
2927   SDValue N0 = N->getOperand(0);
2928   SDValue N1 = N->getOperand(1);
2929   EVT VT = N1.getValueType();
2930
2931   // fold vector ops
2932   if (VT.isVector()) {
2933     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2934       return FoldedVOp;
2935
2936     // fold (and x, 0) -> 0, vector edition
2937     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2938       // do not return N0, because undef node may exist in N0
2939       return DAG.getConstant(
2940           APInt::getNullValue(
2941               N0.getValueType().getScalarType().getSizeInBits()),
2942           SDLoc(N), N0.getValueType());
2943     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2944       // do not return N1, because undef node may exist in N1
2945       return DAG.getConstant(
2946           APInt::getNullValue(
2947               N1.getValueType().getScalarType().getSizeInBits()),
2948           SDLoc(N), N1.getValueType());
2949
2950     // fold (and x, -1) -> x, vector edition
2951     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2952       return N1;
2953     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2954       return N0;
2955   }
2956
2957   // fold (and c1, c2) -> c1&c2
2958   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2959   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2960   if (N0C && N1C && !N1C->isOpaque())
2961     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2962   // canonicalize constant to RHS
2963   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2964      !isConstantIntBuildVectorOrConstantInt(N1))
2965     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2966   // fold (and x, -1) -> x
2967   if (isAllOnesConstant(N1))
2968     return N0;
2969   // if (and x, c) is known to be zero, return 0
2970   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2971   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2972                                    APInt::getAllOnesValue(BitWidth)))
2973     return DAG.getConstant(0, SDLoc(N), VT);
2974   // reassociate and
2975   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2976     return RAND;
2977   // fold (and (or x, C), D) -> D if (C & D) == D
2978   if (N1C && N0.getOpcode() == ISD::OR)
2979     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2980       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2981         return N1;
2982   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2983   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2984     SDValue N0Op0 = N0.getOperand(0);
2985     APInt Mask = ~N1C->getAPIntValue();
2986     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2987     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2988       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2989                                  N0.getValueType(), N0Op0);
2990
2991       // Replace uses of the AND with uses of the Zero extend node.
2992       CombineTo(N, Zext);
2993
2994       // We actually want to replace all uses of the any_extend with the
2995       // zero_extend, to avoid duplicating things.  This will later cause this
2996       // AND to be folded.
2997       CombineTo(N0.getNode(), Zext);
2998       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2999     }
3000   }
3001   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3002   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3003   // already be zero by virtue of the width of the base type of the load.
3004   //
3005   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3006   // more cases.
3007   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3008        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3009       N0.getOpcode() == ISD::LOAD) {
3010     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3011                                          N0 : N0.getOperand(0) );
3012
3013     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3014     // This can be a pure constant or a vector splat, in which case we treat the
3015     // vector as a scalar and use the splat value.
3016     APInt Constant = APInt::getNullValue(1);
3017     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3018       Constant = C->getAPIntValue();
3019     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3020       APInt SplatValue, SplatUndef;
3021       unsigned SplatBitSize;
3022       bool HasAnyUndefs;
3023       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3024                                              SplatBitSize, HasAnyUndefs);
3025       if (IsSplat) {
3026         // Undef bits can contribute to a possible optimisation if set, so
3027         // set them.
3028         SplatValue |= SplatUndef;
3029
3030         // The splat value may be something like "0x00FFFFFF", which means 0 for
3031         // the first vector value and FF for the rest, repeating. We need a mask
3032         // that will apply equally to all members of the vector, so AND all the
3033         // lanes of the constant together.
3034         EVT VT = Vector->getValueType(0);
3035         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3036
3037         // If the splat value has been compressed to a bitlength lower
3038         // than the size of the vector lane, we need to re-expand it to
3039         // the lane size.
3040         if (BitWidth > SplatBitSize)
3041           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3042                SplatBitSize < BitWidth;
3043                SplatBitSize = SplatBitSize * 2)
3044             SplatValue |= SplatValue.shl(SplatBitSize);
3045
3046         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3047         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3048         if (SplatBitSize % BitWidth == 0) {
3049           Constant = APInt::getAllOnesValue(BitWidth);
3050           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3051             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3052         }
3053       }
3054     }
3055
3056     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3057     // actually legal and isn't going to get expanded, else this is a false
3058     // optimisation.
3059     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3060                                                     Load->getValueType(0),
3061                                                     Load->getMemoryVT());
3062
3063     // Resize the constant to the same size as the original memory access before
3064     // extension. If it is still the AllOnesValue then this AND is completely
3065     // unneeded.
3066     Constant =
3067       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3068
3069     bool B;
3070     switch (Load->getExtensionType()) {
3071     default: B = false; break;
3072     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3073     case ISD::ZEXTLOAD:
3074     case ISD::NON_EXTLOAD: B = true; break;
3075     }
3076
3077     if (B && Constant.isAllOnesValue()) {
3078       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3079       // preserve semantics once we get rid of the AND.
3080       SDValue NewLoad(Load, 0);
3081       if (Load->getExtensionType() == ISD::EXTLOAD) {
3082         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3083                               Load->getValueType(0), SDLoc(Load),
3084                               Load->getChain(), Load->getBasePtr(),
3085                               Load->getOffset(), Load->getMemoryVT(),
3086                               Load->getMemOperand());
3087         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3088         if (Load->getNumValues() == 3) {
3089           // PRE/POST_INC loads have 3 values.
3090           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3091                            NewLoad.getValue(2) };
3092           CombineTo(Load, To, 3, true);
3093         } else {
3094           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3095         }
3096       }
3097
3098       // Fold the AND away, taking care not to fold to the old load node if we
3099       // replaced it.
3100       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3101
3102       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3103     }
3104   }
3105
3106   // fold (and (load x), 255) -> (zextload x, i8)
3107   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3108   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3109   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3110               (N0.getOpcode() == ISD::ANY_EXTEND &&
3111                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3112     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3113     LoadSDNode *LN0 = HasAnyExt
3114       ? cast<LoadSDNode>(N0.getOperand(0))
3115       : cast<LoadSDNode>(N0);
3116     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3117         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3118       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3119       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3120         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3121         EVT LoadedVT = LN0->getMemoryVT();
3122         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3123
3124         if (ExtVT == LoadedVT &&
3125             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3126                                                     ExtVT))) {
3127
3128           SDValue NewLoad =
3129             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3130                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3131                            LN0->getMemOperand());
3132           AddToWorklist(N);
3133           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3134           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3135         }
3136
3137         // Do not change the width of a volatile load.
3138         // Do not generate loads of non-round integer types since these can
3139         // be expensive (and would be wrong if the type is not byte sized).
3140         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3141             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3142                                                     ExtVT))) {
3143           EVT PtrType = LN0->getOperand(1).getValueType();
3144
3145           unsigned Alignment = LN0->getAlignment();
3146           SDValue NewPtr = LN0->getBasePtr();
3147
3148           // For big endian targets, we need to add an offset to the pointer
3149           // to load the correct bytes.  For little endian systems, we merely
3150           // need to read fewer bytes from the same pointer.
3151           if (DAG.getDataLayout().isBigEndian()) {
3152             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3153             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3154             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3155             SDLoc DL(LN0);
3156             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3157                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3158             Alignment = MinAlign(Alignment, PtrOff);
3159           }
3160
3161           AddToWorklist(NewPtr.getNode());
3162
3163           SDValue Load =
3164             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3165                            LN0->getChain(), NewPtr,
3166                            LN0->getPointerInfo(),
3167                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3168                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3169           AddToWorklist(N);
3170           CombineTo(LN0, Load, Load.getValue(1));
3171           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3172         }
3173       }
3174     }
3175   }
3176
3177   if (SDValue Combined = visitANDLike(N0, N1, N))
3178     return Combined;
3179
3180   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3181   if (N0.getOpcode() == N1.getOpcode())
3182     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3183       return Tmp;
3184
3185   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3186   // fold (and (sra)) -> (and (srl)) when possible.
3187   if (!VT.isVector() &&
3188       SimplifyDemandedBits(SDValue(N, 0)))
3189     return SDValue(N, 0);
3190
3191   // fold (zext_inreg (extload x)) -> (zextload x)
3192   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3193     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3194     EVT MemVT = LN0->getMemoryVT();
3195     // If we zero all the possible extended bits, then we can turn this into
3196     // a zextload if we are running before legalize or the operation is legal.
3197     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3198     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3199                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3200         ((!LegalOperations && !LN0->isVolatile()) ||
3201          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3202       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3203                                        LN0->getChain(), LN0->getBasePtr(),
3204                                        MemVT, LN0->getMemOperand());
3205       AddToWorklist(N);
3206       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3207       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3208     }
3209   }
3210   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3211   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3212       N0.hasOneUse()) {
3213     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3214     EVT MemVT = LN0->getMemoryVT();
3215     // If we zero all the possible extended bits, then we can turn this into
3216     // a zextload if we are running before legalize or the operation is legal.
3217     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3218     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3219                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3220         ((!LegalOperations && !LN0->isVolatile()) ||
3221          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3222       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3223                                        LN0->getChain(), LN0->getBasePtr(),
3224                                        MemVT, LN0->getMemOperand());
3225       AddToWorklist(N);
3226       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3227       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3228     }
3229   }
3230   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3231   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3232     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3233                                        N0.getOperand(1), false);
3234     if (BSwap.getNode())
3235       return BSwap;
3236   }
3237
3238   return SDValue();
3239 }
3240
3241 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3242 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3243                                         bool DemandHighBits) {
3244   if (!LegalOperations)
3245     return SDValue();
3246
3247   EVT VT = N->getValueType(0);
3248   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3249     return SDValue();
3250   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3251     return SDValue();
3252
3253   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3254   bool LookPassAnd0 = false;
3255   bool LookPassAnd1 = false;
3256   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3257       std::swap(N0, N1);
3258   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3259       std::swap(N0, N1);
3260   if (N0.getOpcode() == ISD::AND) {
3261     if (!N0.getNode()->hasOneUse())
3262       return SDValue();
3263     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3264     if (!N01C || N01C->getZExtValue() != 0xFF00)
3265       return SDValue();
3266     N0 = N0.getOperand(0);
3267     LookPassAnd0 = true;
3268   }
3269
3270   if (N1.getOpcode() == ISD::AND) {
3271     if (!N1.getNode()->hasOneUse())
3272       return SDValue();
3273     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3274     if (!N11C || N11C->getZExtValue() != 0xFF)
3275       return SDValue();
3276     N1 = N1.getOperand(0);
3277     LookPassAnd1 = true;
3278   }
3279
3280   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3281     std::swap(N0, N1);
3282   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3283     return SDValue();
3284   if (!N0.getNode()->hasOneUse() ||
3285       !N1.getNode()->hasOneUse())
3286     return SDValue();
3287
3288   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3289   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3290   if (!N01C || !N11C)
3291     return SDValue();
3292   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3293     return SDValue();
3294
3295   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3296   SDValue N00 = N0->getOperand(0);
3297   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3298     if (!N00.getNode()->hasOneUse())
3299       return SDValue();
3300     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3301     if (!N001C || N001C->getZExtValue() != 0xFF)
3302       return SDValue();
3303     N00 = N00.getOperand(0);
3304     LookPassAnd0 = true;
3305   }
3306
3307   SDValue N10 = N1->getOperand(0);
3308   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3309     if (!N10.getNode()->hasOneUse())
3310       return SDValue();
3311     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3312     if (!N101C || N101C->getZExtValue() != 0xFF00)
3313       return SDValue();
3314     N10 = N10.getOperand(0);
3315     LookPassAnd1 = true;
3316   }
3317
3318   if (N00 != N10)
3319     return SDValue();
3320
3321   // Make sure everything beyond the low halfword gets set to zero since the SRL
3322   // 16 will clear the top bits.
3323   unsigned OpSizeInBits = VT.getSizeInBits();
3324   if (DemandHighBits && OpSizeInBits > 16) {
3325     // If the left-shift isn't masked out then the only way this is a bswap is
3326     // if all bits beyond the low 8 are 0. In that case the entire pattern
3327     // reduces to a left shift anyway: leave it for other parts of the combiner.
3328     if (!LookPassAnd0)
3329       return SDValue();
3330
3331     // However, if the right shift isn't masked out then it might be because
3332     // it's not needed. See if we can spot that too.
3333     if (!LookPassAnd1 &&
3334         !DAG.MaskedValueIsZero(
3335             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3336       return SDValue();
3337   }
3338
3339   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3340   if (OpSizeInBits > 16) {
3341     SDLoc DL(N);
3342     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3343                       DAG.getConstant(OpSizeInBits - 16, DL,
3344                                       getShiftAmountTy(VT)));
3345   }
3346   return Res;
3347 }
3348
3349 /// Return true if the specified node is an element that makes up a 32-bit
3350 /// packed halfword byteswap.
3351 /// ((x & 0x000000ff) << 8) |
3352 /// ((x & 0x0000ff00) >> 8) |
3353 /// ((x & 0x00ff0000) << 8) |
3354 /// ((x & 0xff000000) >> 8)
3355 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3356   if (!N.getNode()->hasOneUse())
3357     return false;
3358
3359   unsigned Opc = N.getOpcode();
3360   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3361     return false;
3362
3363   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3364   if (!N1C)
3365     return false;
3366
3367   unsigned Num;
3368   switch (N1C->getZExtValue()) {
3369   default:
3370     return false;
3371   case 0xFF:       Num = 0; break;
3372   case 0xFF00:     Num = 1; break;
3373   case 0xFF0000:   Num = 2; break;
3374   case 0xFF000000: Num = 3; break;
3375   }
3376
3377   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3378   SDValue N0 = N.getOperand(0);
3379   if (Opc == ISD::AND) {
3380     if (Num == 0 || Num == 2) {
3381       // (x >> 8) & 0xff
3382       // (x >> 8) & 0xff0000
3383       if (N0.getOpcode() != ISD::SRL)
3384         return false;
3385       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3386       if (!C || C->getZExtValue() != 8)
3387         return false;
3388     } else {
3389       // (x << 8) & 0xff00
3390       // (x << 8) & 0xff000000
3391       if (N0.getOpcode() != ISD::SHL)
3392         return false;
3393       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3394       if (!C || C->getZExtValue() != 8)
3395         return false;
3396     }
3397   } else if (Opc == ISD::SHL) {
3398     // (x & 0xff) << 8
3399     // (x & 0xff0000) << 8
3400     if (Num != 0 && Num != 2)
3401       return false;
3402     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3403     if (!C || C->getZExtValue() != 8)
3404       return false;
3405   } else { // Opc == ISD::SRL
3406     // (x & 0xff00) >> 8
3407     // (x & 0xff000000) >> 8
3408     if (Num != 1 && Num != 3)
3409       return false;
3410     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3411     if (!C || C->getZExtValue() != 8)
3412       return false;
3413   }
3414
3415   if (Parts[Num])
3416     return false;
3417
3418   Parts[Num] = N0.getOperand(0).getNode();
3419   return true;
3420 }
3421
3422 /// Match a 32-bit packed halfword bswap. That is
3423 /// ((x & 0x000000ff) << 8) |
3424 /// ((x & 0x0000ff00) >> 8) |
3425 /// ((x & 0x00ff0000) << 8) |
3426 /// ((x & 0xff000000) >> 8)
3427 /// => (rotl (bswap x), 16)
3428 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3429   if (!LegalOperations)
3430     return SDValue();
3431
3432   EVT VT = N->getValueType(0);
3433   if (VT != MVT::i32)
3434     return SDValue();
3435   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3436     return SDValue();
3437
3438   // Look for either
3439   // (or (or (and), (and)), (or (and), (and)))
3440   // (or (or (or (and), (and)), (and)), (and))
3441   if (N0.getOpcode() != ISD::OR)
3442     return SDValue();
3443   SDValue N00 = N0.getOperand(0);
3444   SDValue N01 = N0.getOperand(1);
3445   SDNode *Parts[4] = {};
3446
3447   if (N1.getOpcode() == ISD::OR &&
3448       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3449     // (or (or (and), (and)), (or (and), (and)))
3450     SDValue N000 = N00.getOperand(0);
3451     if (!isBSwapHWordElement(N000, Parts))
3452       return SDValue();
3453
3454     SDValue N001 = N00.getOperand(1);
3455     if (!isBSwapHWordElement(N001, Parts))
3456       return SDValue();
3457     SDValue N010 = N01.getOperand(0);
3458     if (!isBSwapHWordElement(N010, Parts))
3459       return SDValue();
3460     SDValue N011 = N01.getOperand(1);
3461     if (!isBSwapHWordElement(N011, Parts))
3462       return SDValue();
3463   } else {
3464     // (or (or (or (and), (and)), (and)), (and))
3465     if (!isBSwapHWordElement(N1, Parts))
3466       return SDValue();
3467     if (!isBSwapHWordElement(N01, Parts))
3468       return SDValue();
3469     if (N00.getOpcode() != ISD::OR)
3470       return SDValue();
3471     SDValue N000 = N00.getOperand(0);
3472     if (!isBSwapHWordElement(N000, Parts))
3473       return SDValue();
3474     SDValue N001 = N00.getOperand(1);
3475     if (!isBSwapHWordElement(N001, Parts))
3476       return SDValue();
3477   }
3478
3479   // Make sure the parts are all coming from the same node.
3480   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3481     return SDValue();
3482
3483   SDLoc DL(N);
3484   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3485                               SDValue(Parts[0], 0));
3486
3487   // Result of the bswap should be rotated by 16. If it's not legal, then
3488   // do  (x << 16) | (x >> 16).
3489   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3490   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3491     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3492   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3493     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3494   return DAG.getNode(ISD::OR, DL, VT,
3495                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3496                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3497 }
3498
3499 /// This contains all DAGCombine rules which reduce two values combined by
3500 /// an Or operation to a single value \see visitANDLike().
3501 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3502   EVT VT = N1.getValueType();
3503   // fold (or x, undef) -> -1
3504   if (!LegalOperations &&
3505       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3506     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3507     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3508                            SDLoc(LocReference), VT);
3509   }
3510   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3511   SDValue LL, LR, RL, RR, CC0, CC1;
3512   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3513     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3514     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3515
3516     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3517       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3518       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3519       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3520         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3521                                      LR.getValueType(), LL, RL);
3522         AddToWorklist(ORNode.getNode());
3523         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3524       }
3525       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3526       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3527       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3528         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3529                                       LR.getValueType(), LL, RL);
3530         AddToWorklist(ANDNode.getNode());
3531         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3532       }
3533     }
3534     // canonicalize equivalent to ll == rl
3535     if (LL == RR && LR == RL) {
3536       Op1 = ISD::getSetCCSwappedOperands(Op1);
3537       std::swap(RL, RR);
3538     }
3539     if (LL == RL && LR == RR) {
3540       bool isInteger = LL.getValueType().isInteger();
3541       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3542       if (Result != ISD::SETCC_INVALID &&
3543           (!LegalOperations ||
3544            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3545             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3546         EVT CCVT = getSetCCResultType(LL.getValueType());
3547         if (N0.getValueType() == CCVT ||
3548             (!LegalOperations && N0.getValueType() == MVT::i1))
3549           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3550                               LL, LR, Result);
3551       }
3552     }
3553   }
3554
3555   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3556   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3557       // Don't increase # computations.
3558       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3559     // We can only do this xform if we know that bits from X that are set in C2
3560     // but not in C1 are already zero.  Likewise for Y.
3561     if (const ConstantSDNode *N0O1C =
3562         getAsNonOpaqueConstant(N0.getOperand(1))) {
3563       if (const ConstantSDNode *N1O1C =
3564           getAsNonOpaqueConstant(N1.getOperand(1))) {
3565         // We can only do this xform if we know that bits from X that are set in
3566         // C2 but not in C1 are already zero.  Likewise for Y.
3567         const APInt &LHSMask = N0O1C->getAPIntValue();
3568         const APInt &RHSMask = N1O1C->getAPIntValue();
3569
3570         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3571             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3572           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3573                                   N0.getOperand(0), N1.getOperand(0));
3574           SDLoc DL(LocReference);
3575           return DAG.getNode(ISD::AND, DL, VT, X,
3576                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3577         }
3578       }
3579     }
3580   }
3581
3582   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3583   if (N0.getOpcode() == ISD::AND &&
3584       N1.getOpcode() == ISD::AND &&
3585       N0.getOperand(0) == N1.getOperand(0) &&
3586       // Don't increase # computations.
3587       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3588     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3589                             N0.getOperand(1), N1.getOperand(1));
3590     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3591   }
3592
3593   return SDValue();
3594 }
3595
3596 SDValue DAGCombiner::visitOR(SDNode *N) {
3597   SDValue N0 = N->getOperand(0);
3598   SDValue N1 = N->getOperand(1);
3599   EVT VT = N1.getValueType();
3600
3601   // fold vector ops
3602   if (VT.isVector()) {
3603     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3604       return FoldedVOp;
3605
3606     // fold (or x, 0) -> x, vector edition
3607     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3608       return N1;
3609     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3610       return N0;
3611
3612     // fold (or x, -1) -> -1, vector edition
3613     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3614       // do not return N0, because undef node may exist in N0
3615       return DAG.getConstant(
3616           APInt::getAllOnesValue(
3617               N0.getValueType().getScalarType().getSizeInBits()),
3618           SDLoc(N), N0.getValueType());
3619     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3620       // do not return N1, because undef node may exist in N1
3621       return DAG.getConstant(
3622           APInt::getAllOnesValue(
3623               N1.getValueType().getScalarType().getSizeInBits()),
3624           SDLoc(N), N1.getValueType());
3625
3626     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3627     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3628     // Do this only if the resulting shuffle is legal.
3629     if (isa<ShuffleVectorSDNode>(N0) &&
3630         isa<ShuffleVectorSDNode>(N1) &&
3631         // Avoid folding a node with illegal type.
3632         TLI.isTypeLegal(VT) &&
3633         N0->getOperand(1) == N1->getOperand(1) &&
3634         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3635       bool CanFold = true;
3636       unsigned NumElts = VT.getVectorNumElements();
3637       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3638       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3639       // We construct two shuffle masks:
3640       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3641       // and N1 as the second operand.
3642       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3643       // and N0 as the second operand.
3644       // We do this because OR is commutable and therefore there might be
3645       // two ways to fold this node into a shuffle.
3646       SmallVector<int,4> Mask1;
3647       SmallVector<int,4> Mask2;
3648
3649       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3650         int M0 = SV0->getMaskElt(i);
3651         int M1 = SV1->getMaskElt(i);
3652
3653         // Both shuffle indexes are undef. Propagate Undef.
3654         if (M0 < 0 && M1 < 0) {
3655           Mask1.push_back(M0);
3656           Mask2.push_back(M0);
3657           continue;
3658         }
3659
3660         if (M0 < 0 || M1 < 0 ||
3661             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3662             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3663           CanFold = false;
3664           break;
3665         }
3666
3667         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3668         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3669       }
3670
3671       if (CanFold) {
3672         // Fold this sequence only if the resulting shuffle is 'legal'.
3673         if (TLI.isShuffleMaskLegal(Mask1, VT))
3674           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3675                                       N1->getOperand(0), &Mask1[0]);
3676         if (TLI.isShuffleMaskLegal(Mask2, VT))
3677           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3678                                       N0->getOperand(0), &Mask2[0]);
3679       }
3680     }
3681   }
3682
3683   // fold (or c1, c2) -> c1|c2
3684   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3685   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3686   if (N0C && N1C && !N1C->isOpaque())
3687     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3688   // canonicalize constant to RHS
3689   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3690      !isConstantIntBuildVectorOrConstantInt(N1))
3691     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3692   // fold (or x, 0) -> x
3693   if (isNullConstant(N1))
3694     return N0;
3695   // fold (or x, -1) -> -1
3696   if (isAllOnesConstant(N1))
3697     return N1;
3698   // fold (or x, c) -> c iff (x & ~c) == 0
3699   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3700     return N1;
3701
3702   if (SDValue Combined = visitORLike(N0, N1, N))
3703     return Combined;
3704
3705   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3706   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3707     return BSwap;
3708   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3709     return BSwap;
3710
3711   // reassociate or
3712   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3713     return ROR;
3714   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3715   // iff (c1 & c2) == 0.
3716   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3717              isa<ConstantSDNode>(N0.getOperand(1))) {
3718     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3719     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3720       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3721                                                    N1C, C1))
3722         return DAG.getNode(
3723             ISD::AND, SDLoc(N), VT,
3724             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3725       return SDValue();
3726     }
3727   }
3728   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3729   if (N0.getOpcode() == N1.getOpcode())
3730     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3731       return Tmp;
3732
3733   // See if this is some rotate idiom.
3734   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3735     return SDValue(Rot, 0);
3736
3737   // Simplify the operands using demanded-bits information.
3738   if (!VT.isVector() &&
3739       SimplifyDemandedBits(SDValue(N, 0)))
3740     return SDValue(N, 0);
3741
3742   return SDValue();
3743 }
3744
3745 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3746 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3747   if (Op.getOpcode() == ISD::AND) {
3748     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3749       Mask = Op.getOperand(1);
3750       Op = Op.getOperand(0);
3751     } else {
3752       return false;
3753     }
3754   }
3755
3756   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3757     Shift = Op;
3758     return true;
3759   }
3760
3761   return false;
3762 }
3763
3764 // Return true if we can prove that, whenever Neg and Pos are both in the
3765 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3766 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3767 //
3768 //     (or (shift1 X, Neg), (shift2 X, Pos))
3769 //
3770 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3771 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3772 // to consider shift amounts with defined behavior.
3773 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3774   // If OpSize is a power of 2 then:
3775   //
3776   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3777   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3778   //
3779   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3780   // for the stronger condition:
3781   //
3782   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3783   //
3784   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3785   // we can just replace Neg with Neg' for the rest of the function.
3786   //
3787   // In other cases we check for the even stronger condition:
3788   //
3789   //     Neg == OpSize - Pos                                    [B]
3790   //
3791   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3792   // behavior if Pos == 0 (and consequently Neg == OpSize).
3793   //
3794   // We could actually use [A] whenever OpSize is a power of 2, but the
3795   // only extra cases that it would match are those uninteresting ones
3796   // where Neg and Pos are never in range at the same time.  E.g. for
3797   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3798   // as well as (sub 32, Pos), but:
3799   //
3800   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3801   //
3802   // always invokes undefined behavior for 32-bit X.
3803   //
3804   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3805   unsigned MaskLoBits = 0;
3806   if (Neg.getOpcode() == ISD::AND &&
3807       isPowerOf2_64(OpSize) &&
3808       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3809       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3810     Neg = Neg.getOperand(0);
3811     MaskLoBits = Log2_64(OpSize);
3812   }
3813
3814   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3815   if (Neg.getOpcode() != ISD::SUB)
3816     return 0;
3817   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3818   if (!NegC)
3819     return 0;
3820   SDValue NegOp1 = Neg.getOperand(1);
3821
3822   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3823   // Pos'.  The truncation is redundant for the purpose of the equality.
3824   if (MaskLoBits &&
3825       Pos.getOpcode() == ISD::AND &&
3826       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3827       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3828     Pos = Pos.getOperand(0);
3829
3830   // The condition we need is now:
3831   //
3832   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3833   //
3834   // If NegOp1 == Pos then we need:
3835   //
3836   //              OpSize & Mask == NegC & Mask
3837   //
3838   // (because "x & Mask" is a truncation and distributes through subtraction).
3839   APInt Width;
3840   if (Pos == NegOp1)
3841     Width = NegC->getAPIntValue();
3842   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3843   // Then the condition we want to prove becomes:
3844   //
3845   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3846   //
3847   // which, again because "x & Mask" is a truncation, becomes:
3848   //
3849   //                NegC & Mask == (OpSize - PosC) & Mask
3850   //              OpSize & Mask == (NegC + PosC) & Mask
3851   else if (Pos.getOpcode() == ISD::ADD &&
3852            Pos.getOperand(0) == NegOp1 &&
3853            Pos.getOperand(1).getOpcode() == ISD::Constant)
3854     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3855              NegC->getAPIntValue());
3856   else
3857     return false;
3858
3859   // Now we just need to check that OpSize & Mask == Width & Mask.
3860   if (MaskLoBits)
3861     // Opsize & Mask is 0 since Mask is Opsize - 1.
3862     return Width.getLoBits(MaskLoBits) == 0;
3863   return Width == OpSize;
3864 }
3865
3866 // A subroutine of MatchRotate used once we have found an OR of two opposite
3867 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3868 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3869 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3870 // Neg with outer conversions stripped away.
3871 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3872                                        SDValue Neg, SDValue InnerPos,
3873                                        SDValue InnerNeg, unsigned PosOpcode,
3874                                        unsigned NegOpcode, SDLoc DL) {
3875   // fold (or (shl x, (*ext y)),
3876   //          (srl x, (*ext (sub 32, y)))) ->
3877   //   (rotl x, y) or (rotr x, (sub 32, y))
3878   //
3879   // fold (or (shl x, (*ext (sub 32, y))),
3880   //          (srl x, (*ext y))) ->
3881   //   (rotr x, y) or (rotl x, (sub 32, y))
3882   EVT VT = Shifted.getValueType();
3883   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3884     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3885     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3886                        HasPos ? Pos : Neg).getNode();
3887   }
3888
3889   return nullptr;
3890 }
3891
3892 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3893 // idioms for rotate, and if the target supports rotation instructions, generate
3894 // a rot[lr].
3895 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3896   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3897   EVT VT = LHS.getValueType();
3898   if (!TLI.isTypeLegal(VT)) return nullptr;
3899
3900   // The target must have at least one rotate flavor.
3901   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3902   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3903   if (!HasROTL && !HasROTR) return nullptr;
3904
3905   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3906   SDValue LHSShift;   // The shift.
3907   SDValue LHSMask;    // AND value if any.
3908   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3909     return nullptr; // Not part of a rotate.
3910
3911   SDValue RHSShift;   // The shift.
3912   SDValue RHSMask;    // AND value if any.
3913   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3914     return nullptr; // Not part of a rotate.
3915
3916   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3917     return nullptr;   // Not shifting the same value.
3918
3919   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3920     return nullptr;   // Shifts must disagree.
3921
3922   // Canonicalize shl to left side in a shl/srl pair.
3923   if (RHSShift.getOpcode() == ISD::SHL) {
3924     std::swap(LHS, RHS);
3925     std::swap(LHSShift, RHSShift);
3926     std::swap(LHSMask , RHSMask );
3927   }
3928
3929   unsigned OpSizeInBits = VT.getSizeInBits();
3930   SDValue LHSShiftArg = LHSShift.getOperand(0);
3931   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3932   SDValue RHSShiftArg = RHSShift.getOperand(0);
3933   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3934
3935   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3936   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3937   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3938       RHSShiftAmt.getOpcode() == ISD::Constant) {
3939     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3940     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3941     if ((LShVal + RShVal) != OpSizeInBits)
3942       return nullptr;
3943
3944     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3945                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3946
3947     // If there is an AND of either shifted operand, apply it to the result.
3948     if (LHSMask.getNode() || RHSMask.getNode()) {
3949       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3950
3951       if (LHSMask.getNode()) {
3952         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3953         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3954       }
3955       if (RHSMask.getNode()) {
3956         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3957         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3958       }
3959
3960       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3961     }
3962
3963     return Rot.getNode();
3964   }
3965
3966   // If there is a mask here, and we have a variable shift, we can't be sure
3967   // that we're masking out the right stuff.
3968   if (LHSMask.getNode() || RHSMask.getNode())
3969     return nullptr;
3970
3971   // If the shift amount is sign/zext/any-extended just peel it off.
3972   SDValue LExtOp0 = LHSShiftAmt;
3973   SDValue RExtOp0 = RHSShiftAmt;
3974   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3975        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3976        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3977        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3978       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3979        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3980        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3981        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3982     LExtOp0 = LHSShiftAmt.getOperand(0);
3983     RExtOp0 = RHSShiftAmt.getOperand(0);
3984   }
3985
3986   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3987                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3988   if (TryL)
3989     return TryL;
3990
3991   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3992                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3993   if (TryR)
3994     return TryR;
3995
3996   return nullptr;
3997 }
3998
3999 SDValue DAGCombiner::visitXOR(SDNode *N) {
4000   SDValue N0 = N->getOperand(0);
4001   SDValue N1 = N->getOperand(1);
4002   EVT VT = N0.getValueType();
4003
4004   // fold vector ops
4005   if (VT.isVector()) {
4006     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4007       return FoldedVOp;
4008
4009     // fold (xor x, 0) -> x, vector edition
4010     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4011       return N1;
4012     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4013       return N0;
4014   }
4015
4016   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4017   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4018     return DAG.getConstant(0, SDLoc(N), VT);
4019   // fold (xor x, undef) -> undef
4020   if (N0.getOpcode() == ISD::UNDEF)
4021     return N0;
4022   if (N1.getOpcode() == ISD::UNDEF)
4023     return N1;
4024   // fold (xor c1, c2) -> c1^c2
4025   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4026   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4027   if (N0C && N1C)
4028     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4029   // canonicalize constant to RHS
4030   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4031      !isConstantIntBuildVectorOrConstantInt(N1))
4032     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4033   // fold (xor x, 0) -> x
4034   if (isNullConstant(N1))
4035     return N0;
4036   // reassociate xor
4037   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4038     return RXOR;
4039
4040   // fold !(x cc y) -> (x !cc y)
4041   SDValue LHS, RHS, CC;
4042   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4043     bool isInt = LHS.getValueType().isInteger();
4044     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4045                                                isInt);
4046
4047     if (!LegalOperations ||
4048         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4049       switch (N0.getOpcode()) {
4050       default:
4051         llvm_unreachable("Unhandled SetCC Equivalent!");
4052       case ISD::SETCC:
4053         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4054       case ISD::SELECT_CC:
4055         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4056                                N0.getOperand(3), NotCC);
4057       }
4058     }
4059   }
4060
4061   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4062   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4063       N0.getNode()->hasOneUse() &&
4064       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4065     SDValue V = N0.getOperand(0);
4066     SDLoc DL(N0);
4067     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4068                     DAG.getConstant(1, DL, V.getValueType()));
4069     AddToWorklist(V.getNode());
4070     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4071   }
4072
4073   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4074   if (isOneConstant(N1) && VT == MVT::i1 &&
4075       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4076     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4077     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4078       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4079       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4080       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4081       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4082       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4083     }
4084   }
4085   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4086   if (isAllOnesConstant(N1) &&
4087       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4088     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4089     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4090       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4091       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4092       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4093       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4094       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4095     }
4096   }
4097   // fold (xor (and x, y), y) -> (and (not x), y)
4098   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4099       N0->getOperand(1) == N1) {
4100     SDValue X = N0->getOperand(0);
4101     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4102     AddToWorklist(NotX.getNode());
4103     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4104   }
4105   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4106   if (N1C && N0.getOpcode() == ISD::XOR) {
4107     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4108       SDLoc DL(N);
4109       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4110                          DAG.getConstant(N1C->getAPIntValue() ^
4111                                          N00C->getAPIntValue(), DL, VT));
4112     }
4113     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4114       SDLoc DL(N);
4115       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4116                          DAG.getConstant(N1C->getAPIntValue() ^
4117                                          N01C->getAPIntValue(), DL, VT));
4118     }
4119   }
4120   // fold (xor x, x) -> 0
4121   if (N0 == N1)
4122     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4123
4124   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4125   // Here is a concrete example of this equivalence:
4126   // i16   x ==  14
4127   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4128   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4129   //
4130   // =>
4131   //
4132   // i16     ~1      == 0b1111111111111110
4133   // i16 rol(~1, 14) == 0b1011111111111111
4134   //
4135   // Some additional tips to help conceptualize this transform:
4136   // - Try to see the operation as placing a single zero in a value of all ones.
4137   // - There exists no value for x which would allow the result to contain zero.
4138   // - Values of x larger than the bitwidth are undefined and do not require a
4139   //   consistent result.
4140   // - Pushing the zero left requires shifting one bits in from the right.
4141   // A rotate left of ~1 is a nice way of achieving the desired result.
4142   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4143       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4144     SDLoc DL(N);
4145     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4146                        N0.getOperand(1));
4147   }
4148
4149   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4150   if (N0.getOpcode() == N1.getOpcode())
4151     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4152       return Tmp;
4153
4154   // Simplify the expression using non-local knowledge.
4155   if (!VT.isVector() &&
4156       SimplifyDemandedBits(SDValue(N, 0)))
4157     return SDValue(N, 0);
4158
4159   return SDValue();
4160 }
4161
4162 /// Handle transforms common to the three shifts, when the shift amount is a
4163 /// constant.
4164 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4165   SDNode *LHS = N->getOperand(0).getNode();
4166   if (!LHS->hasOneUse()) return SDValue();
4167
4168   // We want to pull some binops through shifts, so that we have (and (shift))
4169   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4170   // thing happens with address calculations, so it's important to canonicalize
4171   // it.
4172   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4173
4174   switch (LHS->getOpcode()) {
4175   default: return SDValue();
4176   case ISD::OR:
4177   case ISD::XOR:
4178     HighBitSet = false; // We can only transform sra if the high bit is clear.
4179     break;
4180   case ISD::AND:
4181     HighBitSet = true;  // We can only transform sra if the high bit is set.
4182     break;
4183   case ISD::ADD:
4184     if (N->getOpcode() != ISD::SHL)
4185       return SDValue(); // only shl(add) not sr[al](add).
4186     HighBitSet = false; // We can only transform sra if the high bit is clear.
4187     break;
4188   }
4189
4190   // We require the RHS of the binop to be a constant and not opaque as well.
4191   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4192   if (!BinOpCst) return SDValue();
4193
4194   // FIXME: disable this unless the input to the binop is a shift by a constant.
4195   // If it is not a shift, it pessimizes some common cases like:
4196   //
4197   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4198   //    int bar(int *X, int i) { return X[i & 255]; }
4199   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4200   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4201        BinOpLHSVal->getOpcode() != ISD::SRA &&
4202        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4203       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4204     return SDValue();
4205
4206   EVT VT = N->getValueType(0);
4207
4208   // If this is a signed shift right, and the high bit is modified by the
4209   // logical operation, do not perform the transformation. The highBitSet
4210   // boolean indicates the value of the high bit of the constant which would
4211   // cause it to be modified for this operation.
4212   if (N->getOpcode() == ISD::SRA) {
4213     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4214     if (BinOpRHSSignSet != HighBitSet)
4215       return SDValue();
4216   }
4217
4218   if (!TLI.isDesirableToCommuteWithShift(LHS))
4219     return SDValue();
4220
4221   // Fold the constants, shifting the binop RHS by the shift amount.
4222   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4223                                N->getValueType(0),
4224                                LHS->getOperand(1), N->getOperand(1));
4225   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4226
4227   // Create the new shift.
4228   SDValue NewShift = DAG.getNode(N->getOpcode(),
4229                                  SDLoc(LHS->getOperand(0)),
4230                                  VT, LHS->getOperand(0), N->getOperand(1));
4231
4232   // Create the new binop.
4233   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4234 }
4235
4236 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4237   assert(N->getOpcode() == ISD::TRUNCATE);
4238   assert(N->getOperand(0).getOpcode() == ISD::AND);
4239
4240   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4241   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4242     SDValue N01 = N->getOperand(0).getOperand(1);
4243
4244     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4245       if (!N01C->isOpaque()) {
4246         EVT TruncVT = N->getValueType(0);
4247         SDValue N00 = N->getOperand(0).getOperand(0);
4248         APInt TruncC = N01C->getAPIntValue();
4249         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4250         SDLoc DL(N);
4251
4252         return DAG.getNode(ISD::AND, DL, TruncVT,
4253                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4254                            DAG.getConstant(TruncC, DL, TruncVT));
4255       }
4256     }
4257   }
4258
4259   return SDValue();
4260 }
4261
4262 SDValue DAGCombiner::visitRotate(SDNode *N) {
4263   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4264   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4265       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4266     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4267     if (NewOp1.getNode())
4268       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4269                          N->getOperand(0), NewOp1);
4270   }
4271   return SDValue();
4272 }
4273
4274 SDValue DAGCombiner::visitSHL(SDNode *N) {
4275   SDValue N0 = N->getOperand(0);
4276   SDValue N1 = N->getOperand(1);
4277   EVT VT = N0.getValueType();
4278   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4279
4280   // fold vector ops
4281   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4282   if (VT.isVector()) {
4283     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4284       return FoldedVOp;
4285
4286     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4287     // If setcc produces all-one true value then:
4288     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4289     if (N1CV && N1CV->isConstant()) {
4290       if (N0.getOpcode() == ISD::AND) {
4291         SDValue N00 = N0->getOperand(0);
4292         SDValue N01 = N0->getOperand(1);
4293         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4294
4295         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4296             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4297                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4298           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4299                                                      N01CV, N1CV))
4300             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4301         }
4302       } else {
4303         N1C = isConstOrConstSplat(N1);
4304       }
4305     }
4306   }
4307
4308   // fold (shl c1, c2) -> c1<<c2
4309   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4310   if (N0C && N1C && !N1C->isOpaque())
4311     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4312   // fold (shl 0, x) -> 0
4313   if (isNullConstant(N0))
4314     return N0;
4315   // fold (shl x, c >= size(x)) -> undef
4316   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4317     return DAG.getUNDEF(VT);
4318   // fold (shl x, 0) -> x
4319   if (N1C && N1C->isNullValue())
4320     return N0;
4321   // fold (shl undef, x) -> 0
4322   if (N0.getOpcode() == ISD::UNDEF)
4323     return DAG.getConstant(0, SDLoc(N), VT);
4324   // if (shl x, c) is known to be zero, return 0
4325   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4326                             APInt::getAllOnesValue(OpSizeInBits)))
4327     return DAG.getConstant(0, SDLoc(N), VT);
4328   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4329   if (N1.getOpcode() == ISD::TRUNCATE &&
4330       N1.getOperand(0).getOpcode() == ISD::AND) {
4331     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4332     if (NewOp1.getNode())
4333       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4334   }
4335
4336   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4337     return SDValue(N, 0);
4338
4339   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4340   if (N1C && N0.getOpcode() == ISD::SHL) {
4341     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4342       uint64_t c1 = N0C1->getZExtValue();
4343       uint64_t c2 = N1C->getZExtValue();
4344       SDLoc DL(N);
4345       if (c1 + c2 >= OpSizeInBits)
4346         return DAG.getConstant(0, DL, VT);
4347       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4348                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4349     }
4350   }
4351
4352   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4353   // For this to be valid, the second form must not preserve any of the bits
4354   // that are shifted out by the inner shift in the first form.  This means
4355   // the outer shift size must be >= the number of bits added by the ext.
4356   // As a corollary, we don't care what kind of ext it is.
4357   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4358               N0.getOpcode() == ISD::ANY_EXTEND ||
4359               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4360       N0.getOperand(0).getOpcode() == ISD::SHL) {
4361     SDValue N0Op0 = N0.getOperand(0);
4362     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4363       uint64_t c1 = N0Op0C1->getZExtValue();
4364       uint64_t c2 = N1C->getZExtValue();
4365       EVT InnerShiftVT = N0Op0.getValueType();
4366       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4367       if (c2 >= OpSizeInBits - InnerShiftSize) {
4368         SDLoc DL(N0);
4369         if (c1 + c2 >= OpSizeInBits)
4370           return DAG.getConstant(0, DL, VT);
4371         return DAG.getNode(ISD::SHL, DL, VT,
4372                            DAG.getNode(N0.getOpcode(), DL, VT,
4373                                        N0Op0->getOperand(0)),
4374                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4375       }
4376     }
4377   }
4378
4379   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4380   // Only fold this if the inner zext has no other uses to avoid increasing
4381   // the total number of instructions.
4382   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4383       N0.getOperand(0).getOpcode() == ISD::SRL) {
4384     SDValue N0Op0 = N0.getOperand(0);
4385     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4386       uint64_t c1 = N0Op0C1->getZExtValue();
4387       if (c1 < VT.getScalarSizeInBits()) {
4388         uint64_t c2 = N1C->getZExtValue();
4389         if (c1 == c2) {
4390           SDValue NewOp0 = N0.getOperand(0);
4391           EVT CountVT = NewOp0.getOperand(1).getValueType();
4392           SDLoc DL(N);
4393           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4394                                        NewOp0,
4395                                        DAG.getConstant(c2, DL, CountVT));
4396           AddToWorklist(NewSHL.getNode());
4397           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4398         }
4399       }
4400     }
4401   }
4402
4403   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4404   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4405   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4406       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4407     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4408       uint64_t C1 = N0C1->getZExtValue();
4409       uint64_t C2 = N1C->getZExtValue();
4410       SDLoc DL(N);
4411       if (C1 <= C2)
4412         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4413                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4414       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4415                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4416     }
4417   }
4418
4419   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4420   //                               (and (srl x, (sub c1, c2), MASK)
4421   // Only fold this if the inner shift has no other uses -- if it does, folding
4422   // this will increase the total number of instructions.
4423   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4424     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4425       uint64_t c1 = N0C1->getZExtValue();
4426       if (c1 < OpSizeInBits) {
4427         uint64_t c2 = N1C->getZExtValue();
4428         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4429         SDValue Shift;
4430         if (c2 > c1) {
4431           Mask = Mask.shl(c2 - c1);
4432           SDLoc DL(N);
4433           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4434                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4435         } else {
4436           Mask = Mask.lshr(c1 - c2);
4437           SDLoc DL(N);
4438           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4439                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4440         }
4441         SDLoc DL(N0);
4442         return DAG.getNode(ISD::AND, DL, VT, Shift,
4443                            DAG.getConstant(Mask, DL, VT));
4444       }
4445     }
4446   }
4447   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4448   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4449     unsigned BitSize = VT.getScalarSizeInBits();
4450     SDLoc DL(N);
4451     SDValue HiBitsMask =
4452       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4453                                             BitSize - N1C->getZExtValue()),
4454                       DL, VT);
4455     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4456                        HiBitsMask);
4457   }
4458
4459   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4460   // Variant of version done on multiply, except mul by a power of 2 is turned
4461   // into a shift.
4462   APInt Val;
4463   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4464       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4465        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4466     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4467     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4468     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4469   }
4470
4471   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4472   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4473     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4474       if (SDValue Folded =
4475               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4476         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4477     }
4478   }
4479
4480   if (N1C && !N1C->isOpaque())
4481     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4482       return NewSHL;
4483
4484   return SDValue();
4485 }
4486
4487 SDValue DAGCombiner::visitSRA(SDNode *N) {
4488   SDValue N0 = N->getOperand(0);
4489   SDValue N1 = N->getOperand(1);
4490   EVT VT = N0.getValueType();
4491   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4492
4493   // fold vector ops
4494   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4495   if (VT.isVector()) {
4496     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4497       return FoldedVOp;
4498
4499     N1C = isConstOrConstSplat(N1);
4500   }
4501
4502   // fold (sra c1, c2) -> (sra c1, c2)
4503   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4504   if (N0C && N1C && !N1C->isOpaque())
4505     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4506   // fold (sra 0, x) -> 0
4507   if (isNullConstant(N0))
4508     return N0;
4509   // fold (sra -1, x) -> -1
4510   if (isAllOnesConstant(N0))
4511     return N0;
4512   // fold (sra x, (setge c, size(x))) -> undef
4513   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4514     return DAG.getUNDEF(VT);
4515   // fold (sra x, 0) -> x
4516   if (N1C && N1C->isNullValue())
4517     return N0;
4518   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4519   // sext_inreg.
4520   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4521     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4522     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4523     if (VT.isVector())
4524       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4525                                ExtVT, VT.getVectorNumElements());
4526     if ((!LegalOperations ||
4527          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4528       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4529                          N0.getOperand(0), DAG.getValueType(ExtVT));
4530   }
4531
4532   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4533   if (N1C && N0.getOpcode() == ISD::SRA) {
4534     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4535       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4536       if (Sum >= OpSizeInBits)
4537         Sum = OpSizeInBits - 1;
4538       SDLoc DL(N);
4539       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4540                          DAG.getConstant(Sum, DL, N1.getValueType()));
4541     }
4542   }
4543
4544   // fold (sra (shl X, m), (sub result_size, n))
4545   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4546   // result_size - n != m.
4547   // If truncate is free for the target sext(shl) is likely to result in better
4548   // code.
4549   if (N0.getOpcode() == ISD::SHL && N1C) {
4550     // Get the two constanst of the shifts, CN0 = m, CN = n.
4551     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4552     if (N01C) {
4553       LLVMContext &Ctx = *DAG.getContext();
4554       // Determine what the truncate's result bitsize and type would be.
4555       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4556
4557       if (VT.isVector())
4558         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4559
4560       // Determine the residual right-shift amount.
4561       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4562
4563       // If the shift is not a no-op (in which case this should be just a sign
4564       // extend already), the truncated to type is legal, sign_extend is legal
4565       // on that type, and the truncate to that type is both legal and free,
4566       // perform the transform.
4567       if ((ShiftAmt > 0) &&
4568           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4569           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4570           TLI.isTruncateFree(VT, TruncVT)) {
4571
4572         SDLoc DL(N);
4573         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4574             getShiftAmountTy(N0.getOperand(0).getValueType()));
4575         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4576                                     N0.getOperand(0), Amt);
4577         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4578                                     Shift);
4579         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4580                            N->getValueType(0), Trunc);
4581       }
4582     }
4583   }
4584
4585   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4586   if (N1.getOpcode() == ISD::TRUNCATE &&
4587       N1.getOperand(0).getOpcode() == ISD::AND) {
4588     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4589     if (NewOp1.getNode())
4590       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4591   }
4592
4593   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4594   //      if c1 is equal to the number of bits the trunc removes
4595   if (N0.getOpcode() == ISD::TRUNCATE &&
4596       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4597        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4598       N0.getOperand(0).hasOneUse() &&
4599       N0.getOperand(0).getOperand(1).hasOneUse() &&
4600       N1C) {
4601     SDValue N0Op0 = N0.getOperand(0);
4602     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4603       unsigned LargeShiftVal = LargeShift->getZExtValue();
4604       EVT LargeVT = N0Op0.getValueType();
4605
4606       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4607         SDLoc DL(N);
4608         SDValue Amt =
4609           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4610                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4611         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4612                                   N0Op0.getOperand(0), Amt);
4613         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4614       }
4615     }
4616   }
4617
4618   // Simplify, based on bits shifted out of the LHS.
4619   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4620     return SDValue(N, 0);
4621
4622
4623   // If the sign bit is known to be zero, switch this to a SRL.
4624   if (DAG.SignBitIsZero(N0))
4625     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4626
4627   if (N1C && !N1C->isOpaque())
4628     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4629       return NewSRA;
4630
4631   return SDValue();
4632 }
4633
4634 SDValue DAGCombiner::visitSRL(SDNode *N) {
4635   SDValue N0 = N->getOperand(0);
4636   SDValue N1 = N->getOperand(1);
4637   EVT VT = N0.getValueType();
4638   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4639
4640   // fold vector ops
4641   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4642   if (VT.isVector()) {
4643     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4644       return FoldedVOp;
4645
4646     N1C = isConstOrConstSplat(N1);
4647   }
4648
4649   // fold (srl c1, c2) -> c1 >>u c2
4650   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4651   if (N0C && N1C && !N1C->isOpaque())
4652     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4653   // fold (srl 0, x) -> 0
4654   if (isNullConstant(N0))
4655     return N0;
4656   // fold (srl x, c >= size(x)) -> undef
4657   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4658     return DAG.getUNDEF(VT);
4659   // fold (srl x, 0) -> x
4660   if (N1C && N1C->isNullValue())
4661     return N0;
4662   // if (srl x, c) is known to be zero, return 0
4663   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4664                                    APInt::getAllOnesValue(OpSizeInBits)))
4665     return DAG.getConstant(0, SDLoc(N), VT);
4666
4667   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4668   if (N1C && N0.getOpcode() == ISD::SRL) {
4669     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4670       uint64_t c1 = N01C->getZExtValue();
4671       uint64_t c2 = N1C->getZExtValue();
4672       SDLoc DL(N);
4673       if (c1 + c2 >= OpSizeInBits)
4674         return DAG.getConstant(0, DL, VT);
4675       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4676                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4677     }
4678   }
4679
4680   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4681   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4682       N0.getOperand(0).getOpcode() == ISD::SRL &&
4683       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4684     uint64_t c1 =
4685       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4686     uint64_t c2 = N1C->getZExtValue();
4687     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4688     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4689     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4690     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4691     if (c1 + OpSizeInBits == InnerShiftSize) {
4692       SDLoc DL(N0);
4693       if (c1 + c2 >= InnerShiftSize)
4694         return DAG.getConstant(0, DL, VT);
4695       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4696                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4697                                      N0.getOperand(0)->getOperand(0),
4698                                      DAG.getConstant(c1 + c2, DL,
4699                                                      ShiftCountVT)));
4700     }
4701   }
4702
4703   // fold (srl (shl x, c), c) -> (and x, cst2)
4704   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4705     unsigned BitSize = N0.getScalarValueSizeInBits();
4706     if (BitSize <= 64) {
4707       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4708       SDLoc DL(N);
4709       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4710                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4711     }
4712   }
4713
4714   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4715   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4716     // Shifting in all undef bits?
4717     EVT SmallVT = N0.getOperand(0).getValueType();
4718     unsigned BitSize = SmallVT.getScalarSizeInBits();
4719     if (N1C->getZExtValue() >= BitSize)
4720       return DAG.getUNDEF(VT);
4721
4722     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4723       uint64_t ShiftAmt = N1C->getZExtValue();
4724       SDLoc DL0(N0);
4725       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4726                                        N0.getOperand(0),
4727                           DAG.getConstant(ShiftAmt, DL0,
4728                                           getShiftAmountTy(SmallVT)));
4729       AddToWorklist(SmallShift.getNode());
4730       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4731       SDLoc DL(N);
4732       return DAG.getNode(ISD::AND, DL, VT,
4733                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4734                          DAG.getConstant(Mask, DL, VT));
4735     }
4736   }
4737
4738   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4739   // bit, which is unmodified by sra.
4740   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4741     if (N0.getOpcode() == ISD::SRA)
4742       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4743   }
4744
4745   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4746   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4747       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4748     APInt KnownZero, KnownOne;
4749     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4750
4751     // If any of the input bits are KnownOne, then the input couldn't be all
4752     // zeros, thus the result of the srl will always be zero.
4753     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4754
4755     // If all of the bits input the to ctlz node are known to be zero, then
4756     // the result of the ctlz is "32" and the result of the shift is one.
4757     APInt UnknownBits = ~KnownZero;
4758     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4759
4760     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4761     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4762       // Okay, we know that only that the single bit specified by UnknownBits
4763       // could be set on input to the CTLZ node. If this bit is set, the SRL
4764       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4765       // to an SRL/XOR pair, which is likely to simplify more.
4766       unsigned ShAmt = UnknownBits.countTrailingZeros();
4767       SDValue Op = N0.getOperand(0);
4768
4769       if (ShAmt) {
4770         SDLoc DL(N0);
4771         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4772                   DAG.getConstant(ShAmt, DL,
4773                                   getShiftAmountTy(Op.getValueType())));
4774         AddToWorklist(Op.getNode());
4775       }
4776
4777       SDLoc DL(N);
4778       return DAG.getNode(ISD::XOR, DL, VT,
4779                          Op, DAG.getConstant(1, DL, VT));
4780     }
4781   }
4782
4783   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4784   if (N1.getOpcode() == ISD::TRUNCATE &&
4785       N1.getOperand(0).getOpcode() == ISD::AND) {
4786     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4787       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4788   }
4789
4790   // fold operands of srl based on knowledge that the low bits are not
4791   // demanded.
4792   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4793     return SDValue(N, 0);
4794
4795   if (N1C && !N1C->isOpaque())
4796     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4797       return NewSRL;
4798
4799   // Attempt to convert a srl of a load into a narrower zero-extending load.
4800   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4801     return NarrowLoad;
4802
4803   // Here is a common situation. We want to optimize:
4804   //
4805   //   %a = ...
4806   //   %b = and i32 %a, 2
4807   //   %c = srl i32 %b, 1
4808   //   brcond i32 %c ...
4809   //
4810   // into
4811   //
4812   //   %a = ...
4813   //   %b = and %a, 2
4814   //   %c = setcc eq %b, 0
4815   //   brcond %c ...
4816   //
4817   // However when after the source operand of SRL is optimized into AND, the SRL
4818   // itself may not be optimized further. Look for it and add the BRCOND into
4819   // the worklist.
4820   if (N->hasOneUse()) {
4821     SDNode *Use = *N->use_begin();
4822     if (Use->getOpcode() == ISD::BRCOND)
4823       AddToWorklist(Use);
4824     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4825       // Also look pass the truncate.
4826       Use = *Use->use_begin();
4827       if (Use->getOpcode() == ISD::BRCOND)
4828         AddToWorklist(Use);
4829     }
4830   }
4831
4832   return SDValue();
4833 }
4834
4835 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4836   SDValue N0 = N->getOperand(0);
4837   EVT VT = N->getValueType(0);
4838
4839   // fold (bswap c1) -> c2
4840   if (isConstantIntBuildVectorOrConstantInt(N0))
4841     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4842   // fold (bswap (bswap x)) -> x
4843   if (N0.getOpcode() == ISD::BSWAP)
4844     return N0->getOperand(0);
4845   return SDValue();
4846 }
4847
4848 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4849   SDValue N0 = N->getOperand(0);
4850   EVT VT = N->getValueType(0);
4851
4852   // fold (ctlz c1) -> c2
4853   if (isConstantIntBuildVectorOrConstantInt(N0))
4854     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4855   return SDValue();
4856 }
4857
4858 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4859   SDValue N0 = N->getOperand(0);
4860   EVT VT = N->getValueType(0);
4861
4862   // fold (ctlz_zero_undef c1) -> c2
4863   if (isConstantIntBuildVectorOrConstantInt(N0))
4864     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4865   return SDValue();
4866 }
4867
4868 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4869   SDValue N0 = N->getOperand(0);
4870   EVT VT = N->getValueType(0);
4871
4872   // fold (cttz c1) -> c2
4873   if (isConstantIntBuildVectorOrConstantInt(N0))
4874     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4875   return SDValue();
4876 }
4877
4878 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4879   SDValue N0 = N->getOperand(0);
4880   EVT VT = N->getValueType(0);
4881
4882   // fold (cttz_zero_undef c1) -> c2
4883   if (isConstantIntBuildVectorOrConstantInt(N0))
4884     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4885   return SDValue();
4886 }
4887
4888 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4889   SDValue N0 = N->getOperand(0);
4890   EVT VT = N->getValueType(0);
4891
4892   // fold (ctpop c1) -> c2
4893   if (isConstantIntBuildVectorOrConstantInt(N0))
4894     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4895   return SDValue();
4896 }
4897
4898
4899 /// \brief Generate Min/Max node
4900 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4901                                    SDValue True, SDValue False,
4902                                    ISD::CondCode CC, const TargetLowering &TLI,
4903                                    SelectionDAG &DAG) {
4904   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4905     return SDValue();
4906
4907   switch (CC) {
4908   case ISD::SETOLT:
4909   case ISD::SETOLE:
4910   case ISD::SETLT:
4911   case ISD::SETLE:
4912   case ISD::SETULT:
4913   case ISD::SETULE: {
4914     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4915     if (TLI.isOperationLegal(Opcode, VT))
4916       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4917     return SDValue();
4918   }
4919   case ISD::SETOGT:
4920   case ISD::SETOGE:
4921   case ISD::SETGT:
4922   case ISD::SETGE:
4923   case ISD::SETUGT:
4924   case ISD::SETUGE: {
4925     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4926     if (TLI.isOperationLegal(Opcode, VT))
4927       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4928     return SDValue();
4929   }
4930   default:
4931     return SDValue();
4932   }
4933 }
4934
4935 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4936   SDValue N0 = N->getOperand(0);
4937   SDValue N1 = N->getOperand(1);
4938   SDValue N2 = N->getOperand(2);
4939   EVT VT = N->getValueType(0);
4940   EVT VT0 = N0.getValueType();
4941
4942   // fold (select C, X, X) -> X
4943   if (N1 == N2)
4944     return N1;
4945   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4946     // fold (select true, X, Y) -> X
4947     // fold (select false, X, Y) -> Y
4948     return !N0C->isNullValue() ? N1 : N2;
4949   }
4950   // fold (select C, 1, X) -> (or C, X)
4951   if (VT == MVT::i1 && isOneConstant(N1))
4952     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4953   // fold (select C, 0, 1) -> (xor C, 1)
4954   // We can't do this reliably if integer based booleans have different contents
4955   // to floating point based booleans. This is because we can't tell whether we
4956   // have an integer-based boolean or a floating-point-based boolean unless we
4957   // can find the SETCC that produced it and inspect its operands. This is
4958   // fairly easy if C is the SETCC node, but it can potentially be
4959   // undiscoverable (or not reasonably discoverable). For example, it could be
4960   // in another basic block or it could require searching a complicated
4961   // expression.
4962   if (VT.isInteger() &&
4963       (VT0 == MVT::i1 || (VT0.isInteger() &&
4964                           TLI.getBooleanContents(false, false) ==
4965                               TLI.getBooleanContents(false, true) &&
4966                           TLI.getBooleanContents(false, false) ==
4967                               TargetLowering::ZeroOrOneBooleanContent)) &&
4968       isNullConstant(N1) && isOneConstant(N2)) {
4969     SDValue XORNode;
4970     if (VT == VT0) {
4971       SDLoc DL(N);
4972       return DAG.getNode(ISD::XOR, DL, VT0,
4973                          N0, DAG.getConstant(1, DL, VT0));
4974     }
4975     SDLoc DL0(N0);
4976     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4977                           N0, DAG.getConstant(1, DL0, VT0));
4978     AddToWorklist(XORNode.getNode());
4979     if (VT.bitsGT(VT0))
4980       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4981     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4982   }
4983   // fold (select C, 0, X) -> (and (not C), X)
4984   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4985     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4986     AddToWorklist(NOTNode.getNode());
4987     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4988   }
4989   // fold (select C, X, 1) -> (or (not C), X)
4990   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4991     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4992     AddToWorklist(NOTNode.getNode());
4993     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4994   }
4995   // fold (select C, X, 0) -> (and C, X)
4996   if (VT == MVT::i1 && isNullConstant(N2))
4997     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4998   // fold (select X, X, Y) -> (or X, Y)
4999   // fold (select X, 1, Y) -> (or X, Y)
5000   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5001     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5002   // fold (select X, Y, X) -> (and X, Y)
5003   // fold (select X, Y, 0) -> (and X, Y)
5004   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5005     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5006
5007   // If we can fold this based on the true/false value, do so.
5008   if (SimplifySelectOps(N, N1, N2))
5009     return SDValue(N, 0);  // Don't revisit N.
5010
5011   if (VT0 == MVT::i1) {
5012     // The code in this block deals with the following 2 equivalences:
5013     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5014     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5015     // The target can specify its prefered form with the
5016     // shouldNormalizeToSelectSequence() callback. However we always transform
5017     // to the right anyway if we find the inner select exists in the DAG anyway
5018     // and we always transform to the left side if we know that we can further
5019     // optimize the combination of the conditions.
5020     bool normalizeToSequence
5021       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5022     // select (and Cond0, Cond1), X, Y
5023     //   -> select Cond0, (select Cond1, X, Y), Y
5024     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5025       SDValue Cond0 = N0->getOperand(0);
5026       SDValue Cond1 = N0->getOperand(1);
5027       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5028                                         N1.getValueType(), Cond1, N1, N2);
5029       if (normalizeToSequence || !InnerSelect.use_empty())
5030         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5031                            InnerSelect, N2);
5032     }
5033     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5034     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5035       SDValue Cond0 = N0->getOperand(0);
5036       SDValue Cond1 = N0->getOperand(1);
5037       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5038                                         N1.getValueType(), Cond1, N1, N2);
5039       if (normalizeToSequence || !InnerSelect.use_empty())
5040         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5041                            InnerSelect);
5042     }
5043
5044     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5045     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5046       SDValue N1_0 = N1->getOperand(0);
5047       SDValue N1_1 = N1->getOperand(1);
5048       SDValue N1_2 = N1->getOperand(2);
5049       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5050         // Create the actual and node if we can generate good code for it.
5051         if (!normalizeToSequence) {
5052           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5053                                     N0, N1_0);
5054           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5055                              N1_1, N2);
5056         }
5057         // Otherwise see if we can optimize the "and" to a better pattern.
5058         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5059           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5060                              N1_1, N2);
5061       }
5062     }
5063     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5064     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5065       SDValue N2_0 = N2->getOperand(0);
5066       SDValue N2_1 = N2->getOperand(1);
5067       SDValue N2_2 = N2->getOperand(2);
5068       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5069         // Create the actual or node if we can generate good code for it.
5070         if (!normalizeToSequence) {
5071           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5072                                    N0, N2_0);
5073           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5074                              N1, N2_2);
5075         }
5076         // Otherwise see if we can optimize to a better pattern.
5077         if (SDValue Combined = visitORLike(N0, N2_0, N))
5078           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5079                              N1, N2_2);
5080       }
5081     }
5082   }
5083
5084   // fold selects based on a setcc into other things, such as min/max/abs
5085   if (N0.getOpcode() == ISD::SETCC) {
5086     // select x, y (fcmp lt x, y) -> fminnum x, y
5087     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5088     //
5089     // This is OK if we don't care about what happens if either operand is a
5090     // NaN.
5091     //
5092
5093     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5094     // no signed zeros as well as no nans.
5095     const TargetOptions &Options = DAG.getTarget().Options;
5096     if (Options.UnsafeFPMath &&
5097         VT.isFloatingPoint() && N0.hasOneUse() &&
5098         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5099       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5100
5101       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5102                                                 N0.getOperand(1), N1, N2, CC,
5103                                                 TLI, DAG))
5104         return FMinMax;
5105     }
5106
5107     if ((!LegalOperations &&
5108          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5109         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5110       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5111                          N0.getOperand(0), N0.getOperand(1),
5112                          N1, N2, N0.getOperand(2));
5113     return SimplifySelect(SDLoc(N), N0, N1, N2);
5114   }
5115
5116   return SDValue();
5117 }
5118
5119 static
5120 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5121   SDLoc DL(N);
5122   EVT LoVT, HiVT;
5123   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5124
5125   // Split the inputs.
5126   SDValue Lo, Hi, LL, LH, RL, RH;
5127   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5128   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5129
5130   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5131   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5132
5133   return std::make_pair(Lo, Hi);
5134 }
5135
5136 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5137 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5138 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5139   SDLoc dl(N);
5140   SDValue Cond = N->getOperand(0);
5141   SDValue LHS = N->getOperand(1);
5142   SDValue RHS = N->getOperand(2);
5143   EVT VT = N->getValueType(0);
5144   int NumElems = VT.getVectorNumElements();
5145   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5146          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5147          Cond.getOpcode() == ISD::BUILD_VECTOR);
5148
5149   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5150   // binary ones here.
5151   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5152     return SDValue();
5153
5154   // We're sure we have an even number of elements due to the
5155   // concat_vectors we have as arguments to vselect.
5156   // Skip BV elements until we find one that's not an UNDEF
5157   // After we find an UNDEF element, keep looping until we get to half the
5158   // length of the BV and see if all the non-undef nodes are the same.
5159   ConstantSDNode *BottomHalf = nullptr;
5160   for (int i = 0; i < NumElems / 2; ++i) {
5161     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5162       continue;
5163
5164     if (BottomHalf == nullptr)
5165       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5166     else if (Cond->getOperand(i).getNode() != BottomHalf)
5167       return SDValue();
5168   }
5169
5170   // Do the same for the second half of the BuildVector
5171   ConstantSDNode *TopHalf = nullptr;
5172   for (int i = NumElems / 2; i < NumElems; ++i) {
5173     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5174       continue;
5175
5176     if (TopHalf == nullptr)
5177       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5178     else if (Cond->getOperand(i).getNode() != TopHalf)
5179       return SDValue();
5180   }
5181
5182   assert(TopHalf && BottomHalf &&
5183          "One half of the selector was all UNDEFs and the other was all the "
5184          "same value. This should have been addressed before this function.");
5185   return DAG.getNode(
5186       ISD::CONCAT_VECTORS, dl, VT,
5187       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5188       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5189 }
5190
5191 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5192
5193   if (Level >= AfterLegalizeTypes)
5194     return SDValue();
5195
5196   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5197   SDValue Mask = MSC->getMask();
5198   SDValue Data  = MSC->getValue();
5199   SDLoc DL(N);
5200
5201   // If the MSCATTER data type requires splitting and the mask is provided by a
5202   // SETCC, then split both nodes and its operands before legalization. This
5203   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5204   // and enables future optimizations (e.g. min/max pattern matching on X86).
5205   if (Mask.getOpcode() != ISD::SETCC)
5206     return SDValue();
5207
5208   // Check if any splitting is required.
5209   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5210       TargetLowering::TypeSplitVector)
5211     return SDValue();
5212   SDValue MaskLo, MaskHi, Lo, Hi;
5213   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5214
5215   EVT LoVT, HiVT;
5216   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5217
5218   SDValue Chain = MSC->getChain();
5219
5220   EVT MemoryVT = MSC->getMemoryVT();
5221   unsigned Alignment = MSC->getOriginalAlignment();
5222
5223   EVT LoMemVT, HiMemVT;
5224   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5225
5226   SDValue DataLo, DataHi;
5227   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5228
5229   SDValue BasePtr = MSC->getBasePtr();
5230   SDValue IndexLo, IndexHi;
5231   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5232
5233   MachineMemOperand *MMO = DAG.getMachineFunction().
5234     getMachineMemOperand(MSC->getPointerInfo(),
5235                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5236                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5237
5238   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5239   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5240                             DL, OpsLo, MMO);
5241
5242   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5243   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5244                             DL, OpsHi, MMO);
5245
5246   AddToWorklist(Lo.getNode());
5247   AddToWorklist(Hi.getNode());
5248
5249   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5250 }
5251
5252 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5253
5254   if (Level >= AfterLegalizeTypes)
5255     return SDValue();
5256
5257   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5258   SDValue Mask = MST->getMask();
5259   SDValue Data  = MST->getValue();
5260   SDLoc DL(N);
5261
5262   // If the MSTORE data type requires splitting and the mask is provided by a
5263   // SETCC, then split both nodes and its operands before legalization. This
5264   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5265   // and enables future optimizations (e.g. min/max pattern matching on X86).
5266   if (Mask.getOpcode() == ISD::SETCC) {
5267
5268     // Check if any splitting is required.
5269     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5270         TargetLowering::TypeSplitVector)
5271       return SDValue();
5272
5273     SDValue MaskLo, MaskHi, Lo, Hi;
5274     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5275
5276     EVT LoVT, HiVT;
5277     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5278
5279     SDValue Chain = MST->getChain();
5280     SDValue Ptr   = MST->getBasePtr();
5281
5282     EVT MemoryVT = MST->getMemoryVT();
5283     unsigned Alignment = MST->getOriginalAlignment();
5284
5285     // if Alignment is equal to the vector size,
5286     // take the half of it for the second part
5287     unsigned SecondHalfAlignment =
5288       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5289          Alignment/2 : Alignment;
5290
5291     EVT LoMemVT, HiMemVT;
5292     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5293
5294     SDValue DataLo, DataHi;
5295     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5296
5297     MachineMemOperand *MMO = DAG.getMachineFunction().
5298       getMachineMemOperand(MST->getPointerInfo(),
5299                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5300                            Alignment, MST->getAAInfo(), MST->getRanges());
5301
5302     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5303                             MST->isTruncatingStore());
5304
5305     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5306     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5307                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5308
5309     MMO = DAG.getMachineFunction().
5310       getMachineMemOperand(MST->getPointerInfo(),
5311                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5312                            SecondHalfAlignment, MST->getAAInfo(),
5313                            MST->getRanges());
5314
5315     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5316                             MST->isTruncatingStore());
5317
5318     AddToWorklist(Lo.getNode());
5319     AddToWorklist(Hi.getNode());
5320
5321     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5322   }
5323   return SDValue();
5324 }
5325
5326 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5327
5328   if (Level >= AfterLegalizeTypes)
5329     return SDValue();
5330
5331   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5332   SDValue Mask = MGT->getMask();
5333   SDLoc DL(N);
5334
5335   // If the MGATHER result requires splitting and the mask is provided by a
5336   // SETCC, then split both nodes and its operands before legalization. This
5337   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5338   // and enables future optimizations (e.g. min/max pattern matching on X86).
5339
5340   if (Mask.getOpcode() != ISD::SETCC)
5341     return SDValue();
5342
5343   EVT VT = N->getValueType(0);
5344
5345   // Check if any splitting is required.
5346   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5347       TargetLowering::TypeSplitVector)
5348     return SDValue();
5349
5350   SDValue MaskLo, MaskHi, Lo, Hi;
5351   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5352
5353   SDValue Src0 = MGT->getValue();
5354   SDValue Src0Lo, Src0Hi;
5355   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5356
5357   EVT LoVT, HiVT;
5358   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5359
5360   SDValue Chain = MGT->getChain();
5361   EVT MemoryVT = MGT->getMemoryVT();
5362   unsigned Alignment = MGT->getOriginalAlignment();
5363
5364   EVT LoMemVT, HiMemVT;
5365   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5366
5367   SDValue BasePtr = MGT->getBasePtr();
5368   SDValue Index = MGT->getIndex();
5369   SDValue IndexLo, IndexHi;
5370   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5371
5372   MachineMemOperand *MMO = DAG.getMachineFunction().
5373     getMachineMemOperand(MGT->getPointerInfo(),
5374                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5375                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5376
5377   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5378   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5379                             MMO);
5380
5381   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5382   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5383                             MMO);
5384
5385   AddToWorklist(Lo.getNode());
5386   AddToWorklist(Hi.getNode());
5387
5388   // Build a factor node to remember that this load is independent of the
5389   // other one.
5390   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5391                       Hi.getValue(1));
5392
5393   // Legalized the chain result - switch anything that used the old chain to
5394   // use the new one.
5395   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5396
5397   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5398
5399   SDValue RetOps[] = { GatherRes, Chain };
5400   return DAG.getMergeValues(RetOps, DL);
5401 }
5402
5403 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5404
5405   if (Level >= AfterLegalizeTypes)
5406     return SDValue();
5407
5408   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5409   SDValue Mask = MLD->getMask();
5410   SDLoc DL(N);
5411
5412   // If the MLOAD result requires splitting and the mask is provided by a
5413   // SETCC, then split both nodes and its operands before legalization. This
5414   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5415   // and enables future optimizations (e.g. min/max pattern matching on X86).
5416
5417   if (Mask.getOpcode() == ISD::SETCC) {
5418     EVT VT = N->getValueType(0);
5419
5420     // Check if any splitting is required.
5421     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5422         TargetLowering::TypeSplitVector)
5423       return SDValue();
5424
5425     SDValue MaskLo, MaskHi, Lo, Hi;
5426     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5427
5428     SDValue Src0 = MLD->getSrc0();
5429     SDValue Src0Lo, Src0Hi;
5430     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5431
5432     EVT LoVT, HiVT;
5433     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5434
5435     SDValue Chain = MLD->getChain();
5436     SDValue Ptr   = MLD->getBasePtr();
5437     EVT MemoryVT = MLD->getMemoryVT();
5438     unsigned Alignment = MLD->getOriginalAlignment();
5439
5440     // if Alignment is equal to the vector size,
5441     // take the half of it for the second part
5442     unsigned SecondHalfAlignment =
5443       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5444          Alignment/2 : Alignment;
5445
5446     EVT LoMemVT, HiMemVT;
5447     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5448
5449     MachineMemOperand *MMO = DAG.getMachineFunction().
5450     getMachineMemOperand(MLD->getPointerInfo(),
5451                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5452                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5453
5454     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5455                            ISD::NON_EXTLOAD);
5456
5457     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5458     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5459                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5460
5461     MMO = DAG.getMachineFunction().
5462     getMachineMemOperand(MLD->getPointerInfo(),
5463                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5464                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5465
5466     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5467                            ISD::NON_EXTLOAD);
5468
5469     AddToWorklist(Lo.getNode());
5470     AddToWorklist(Hi.getNode());
5471
5472     // Build a factor node to remember that this load is independent of the
5473     // other one.
5474     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5475                         Hi.getValue(1));
5476
5477     // Legalized the chain result - switch anything that used the old chain to
5478     // use the new one.
5479     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5480
5481     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5482
5483     SDValue RetOps[] = { LoadRes, Chain };
5484     return DAG.getMergeValues(RetOps, DL);
5485   }
5486   return SDValue();
5487 }
5488
5489 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5490   SDValue N0 = N->getOperand(0);
5491   SDValue N1 = N->getOperand(1);
5492   SDValue N2 = N->getOperand(2);
5493   SDLoc DL(N);
5494
5495   // Canonicalize integer abs.
5496   // vselect (setg[te] X,  0),  X, -X ->
5497   // vselect (setgt    X, -1),  X, -X ->
5498   // vselect (setl[te] X,  0), -X,  X ->
5499   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5500   if (N0.getOpcode() == ISD::SETCC) {
5501     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5502     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5503     bool isAbs = false;
5504     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5505
5506     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5507          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5508         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5509       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5510     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5511              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5512       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5513
5514     if (isAbs) {
5515       EVT VT = LHS.getValueType();
5516       SDValue Shift = DAG.getNode(
5517           ISD::SRA, DL, VT, LHS,
5518           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5519       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5520       AddToWorklist(Shift.getNode());
5521       AddToWorklist(Add.getNode());
5522       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5523     }
5524   }
5525
5526   if (SimplifySelectOps(N, N1, N2))
5527     return SDValue(N, 0);  // Don't revisit N.
5528
5529   // If the VSELECT result requires splitting and the mask is provided by a
5530   // SETCC, then split both nodes and its operands before legalization. This
5531   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5532   // and enables future optimizations (e.g. min/max pattern matching on X86).
5533   if (N0.getOpcode() == ISD::SETCC) {
5534     EVT VT = N->getValueType(0);
5535
5536     // Check if any splitting is required.
5537     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5538         TargetLowering::TypeSplitVector)
5539       return SDValue();
5540
5541     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5542     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5543     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5544     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5545
5546     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5547     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5548
5549     // Add the new VSELECT nodes to the work list in case they need to be split
5550     // again.
5551     AddToWorklist(Lo.getNode());
5552     AddToWorklist(Hi.getNode());
5553
5554     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5555   }
5556
5557   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5558   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5559     return N1;
5560   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5561   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5562     return N2;
5563
5564   // The ConvertSelectToConcatVector function is assuming both the above
5565   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5566   // and addressed.
5567   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5568       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5569       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5570     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5571       return CV;
5572   }
5573
5574   return SDValue();
5575 }
5576
5577 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5578   SDValue N0 = N->getOperand(0);
5579   SDValue N1 = N->getOperand(1);
5580   SDValue N2 = N->getOperand(2);
5581   SDValue N3 = N->getOperand(3);
5582   SDValue N4 = N->getOperand(4);
5583   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5584
5585   // fold select_cc lhs, rhs, x, x, cc -> x
5586   if (N2 == N3)
5587     return N2;
5588
5589   // Determine if the condition we're dealing with is constant
5590   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5591                               N0, N1, CC, SDLoc(N), false);
5592   if (SCC.getNode()) {
5593     AddToWorklist(SCC.getNode());
5594
5595     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5596       if (!SCCC->isNullValue())
5597         return N2;    // cond always true -> true val
5598       else
5599         return N3;    // cond always false -> false val
5600     } else if (SCC->getOpcode() == ISD::UNDEF) {
5601       // When the condition is UNDEF, just return the first operand. This is
5602       // coherent the DAG creation, no setcc node is created in this case
5603       return N2;
5604     } else if (SCC.getOpcode() == ISD::SETCC) {
5605       // Fold to a simpler select_cc
5606       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5607                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5608                          SCC.getOperand(2));
5609     }
5610   }
5611
5612   // If we can fold this based on the true/false value, do so.
5613   if (SimplifySelectOps(N, N2, N3))
5614     return SDValue(N, 0);  // Don't revisit N.
5615
5616   // fold select_cc into other things, such as min/max/abs
5617   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5618 }
5619
5620 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5621   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5622                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5623                        SDLoc(N));
5624 }
5625
5626 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5627 /// a build_vector of constants.
5628 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5629 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5630 /// Vector extends are not folded if operations are legal; this is to
5631 /// avoid introducing illegal build_vector dag nodes.
5632 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5633                                          SelectionDAG &DAG, bool LegalTypes,
5634                                          bool LegalOperations) {
5635   unsigned Opcode = N->getOpcode();
5636   SDValue N0 = N->getOperand(0);
5637   EVT VT = N->getValueType(0);
5638
5639   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5640          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5641          && "Expected EXTEND dag node in input!");
5642
5643   // fold (sext c1) -> c1
5644   // fold (zext c1) -> c1
5645   // fold (aext c1) -> c1
5646   if (isa<ConstantSDNode>(N0))
5647     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5648
5649   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5650   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5651   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5652   EVT SVT = VT.getScalarType();
5653   if (!(VT.isVector() &&
5654       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5655       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5656     return nullptr;
5657
5658   // We can fold this node into a build_vector.
5659   unsigned VTBits = SVT.getSizeInBits();
5660   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5661   SmallVector<SDValue, 8> Elts;
5662   unsigned NumElts = VT.getVectorNumElements();
5663   SDLoc DL(N);
5664
5665   for (unsigned i=0; i != NumElts; ++i) {
5666     SDValue Op = N0->getOperand(i);
5667     if (Op->getOpcode() == ISD::UNDEF) {
5668       Elts.push_back(DAG.getUNDEF(SVT));
5669       continue;
5670     }
5671
5672     SDLoc DL(Op);
5673     // Get the constant value and if needed trunc it to the size of the type.
5674     // Nodes like build_vector might have constants wider than the scalar type.
5675     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5676     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5677       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5678     else
5679       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5680   }
5681
5682   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5683 }
5684
5685 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5686 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5687 // transformation. Returns true if extension are possible and the above
5688 // mentioned transformation is profitable.
5689 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5690                                     unsigned ExtOpc,
5691                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5692                                     const TargetLowering &TLI) {
5693   bool HasCopyToRegUses = false;
5694   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5695   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5696                             UE = N0.getNode()->use_end();
5697        UI != UE; ++UI) {
5698     SDNode *User = *UI;
5699     if (User == N)
5700       continue;
5701     if (UI.getUse().getResNo() != N0.getResNo())
5702       continue;
5703     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5704     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5705       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5706       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5707         // Sign bits will be lost after a zext.
5708         return false;
5709       bool Add = false;
5710       for (unsigned i = 0; i != 2; ++i) {
5711         SDValue UseOp = User->getOperand(i);
5712         if (UseOp == N0)
5713           continue;
5714         if (!isa<ConstantSDNode>(UseOp))
5715           return false;
5716         Add = true;
5717       }
5718       if (Add)
5719         ExtendNodes.push_back(User);
5720       continue;
5721     }
5722     // If truncates aren't free and there are users we can't
5723     // extend, it isn't worthwhile.
5724     if (!isTruncFree)
5725       return false;
5726     // Remember if this value is live-out.
5727     if (User->getOpcode() == ISD::CopyToReg)
5728       HasCopyToRegUses = true;
5729   }
5730
5731   if (HasCopyToRegUses) {
5732     bool BothLiveOut = false;
5733     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5734          UI != UE; ++UI) {
5735       SDUse &Use = UI.getUse();
5736       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5737         BothLiveOut = true;
5738         break;
5739       }
5740     }
5741     if (BothLiveOut)
5742       // Both unextended and extended values are live out. There had better be
5743       // a good reason for the transformation.
5744       return ExtendNodes.size();
5745   }
5746   return true;
5747 }
5748
5749 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5750                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5751                                   ISD::NodeType ExtType) {
5752   // Extend SetCC uses if necessary.
5753   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5754     SDNode *SetCC = SetCCs[i];
5755     SmallVector<SDValue, 4> Ops;
5756
5757     for (unsigned j = 0; j != 2; ++j) {
5758       SDValue SOp = SetCC->getOperand(j);
5759       if (SOp == Trunc)
5760         Ops.push_back(ExtLoad);
5761       else
5762         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5763     }
5764
5765     Ops.push_back(SetCC->getOperand(2));
5766     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5767   }
5768 }
5769
5770 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5771 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5772   SDValue N0 = N->getOperand(0);
5773   EVT DstVT = N->getValueType(0);
5774   EVT SrcVT = N0.getValueType();
5775
5776   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5777           N->getOpcode() == ISD::ZERO_EXTEND) &&
5778          "Unexpected node type (not an extend)!");
5779
5780   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5781   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5782   //   (v8i32 (sext (v8i16 (load x))))
5783   // into:
5784   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5785   //                          (v4i32 (sextload (x + 16)))))
5786   // Where uses of the original load, i.e.:
5787   //   (v8i16 (load x))
5788   // are replaced with:
5789   //   (v8i16 (truncate
5790   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5791   //                            (v4i32 (sextload (x + 16)))))))
5792   //
5793   // This combine is only applicable to illegal, but splittable, vectors.
5794   // All legal types, and illegal non-vector types, are handled elsewhere.
5795   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5796   //
5797   if (N0->getOpcode() != ISD::LOAD)
5798     return SDValue();
5799
5800   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5801
5802   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5803       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5804       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5805     return SDValue();
5806
5807   SmallVector<SDNode *, 4> SetCCs;
5808   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5809     return SDValue();
5810
5811   ISD::LoadExtType ExtType =
5812       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5813
5814   // Try to split the vector types to get down to legal types.
5815   EVT SplitSrcVT = SrcVT;
5816   EVT SplitDstVT = DstVT;
5817   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5818          SplitSrcVT.getVectorNumElements() > 1) {
5819     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5820     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5821   }
5822
5823   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5824     return SDValue();
5825
5826   SDLoc DL(N);
5827   const unsigned NumSplits =
5828       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5829   const unsigned Stride = SplitSrcVT.getStoreSize();
5830   SmallVector<SDValue, 4> Loads;
5831   SmallVector<SDValue, 4> Chains;
5832
5833   SDValue BasePtr = LN0->getBasePtr();
5834   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5835     const unsigned Offset = Idx * Stride;
5836     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5837
5838     SDValue SplitLoad = DAG.getExtLoad(
5839         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5840         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5841         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5842         Align, LN0->getAAInfo());
5843
5844     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5845                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5846
5847     Loads.push_back(SplitLoad.getValue(0));
5848     Chains.push_back(SplitLoad.getValue(1));
5849   }
5850
5851   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5852   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5853
5854   CombineTo(N, NewValue);
5855
5856   // Replace uses of the original load (before extension)
5857   // with a truncate of the concatenated sextloaded vectors.
5858   SDValue Trunc =
5859       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5860   CombineTo(N0.getNode(), Trunc, NewChain);
5861   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5862                   (ISD::NodeType)N->getOpcode());
5863   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5864 }
5865
5866 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5867   SDValue N0 = N->getOperand(0);
5868   EVT VT = N->getValueType(0);
5869
5870   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5871                                               LegalOperations))
5872     return SDValue(Res, 0);
5873
5874   // fold (sext (sext x)) -> (sext x)
5875   // fold (sext (aext x)) -> (sext x)
5876   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5877     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5878                        N0.getOperand(0));
5879
5880   if (N0.getOpcode() == ISD::TRUNCATE) {
5881     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5882     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5883     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5884       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5885       if (NarrowLoad.getNode() != N0.getNode()) {
5886         CombineTo(N0.getNode(), NarrowLoad);
5887         // CombineTo deleted the truncate, if needed, but not what's under it.
5888         AddToWorklist(oye);
5889       }
5890       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5891     }
5892
5893     // See if the value being truncated is already sign extended.  If so, just
5894     // eliminate the trunc/sext pair.
5895     SDValue Op = N0.getOperand(0);
5896     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5897     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5898     unsigned DestBits = VT.getScalarType().getSizeInBits();
5899     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5900
5901     if (OpBits == DestBits) {
5902       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5903       // bits, it is already ready.
5904       if (NumSignBits > DestBits-MidBits)
5905         return Op;
5906     } else if (OpBits < DestBits) {
5907       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5908       // bits, just sext from i32.
5909       if (NumSignBits > OpBits-MidBits)
5910         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5911     } else {
5912       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5913       // bits, just truncate to i32.
5914       if (NumSignBits > OpBits-MidBits)
5915         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5916     }
5917
5918     // fold (sext (truncate x)) -> (sextinreg x).
5919     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5920                                                  N0.getValueType())) {
5921       if (OpBits < DestBits)
5922         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5923       else if (OpBits > DestBits)
5924         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5925       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5926                          DAG.getValueType(N0.getValueType()));
5927     }
5928   }
5929
5930   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5931   // Only generate vector extloads when 1) they're legal, and 2) they are
5932   // deemed desirable by the target.
5933   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5934       ((!LegalOperations && !VT.isVector() &&
5935         !cast<LoadSDNode>(N0)->isVolatile()) ||
5936        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5937     bool DoXform = true;
5938     SmallVector<SDNode*, 4> SetCCs;
5939     if (!N0.hasOneUse())
5940       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5941     if (VT.isVector())
5942       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5943     if (DoXform) {
5944       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5945       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5946                                        LN0->getChain(),
5947                                        LN0->getBasePtr(), N0.getValueType(),
5948                                        LN0->getMemOperand());
5949       CombineTo(N, ExtLoad);
5950       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5951                                   N0.getValueType(), ExtLoad);
5952       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5953       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5954                       ISD::SIGN_EXTEND);
5955       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5956     }
5957   }
5958
5959   // fold (sext (load x)) to multiple smaller sextloads.
5960   // Only on illegal but splittable vectors.
5961   if (SDValue ExtLoad = CombineExtLoad(N))
5962     return ExtLoad;
5963
5964   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5965   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5966   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5967       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5968     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5969     EVT MemVT = LN0->getMemoryVT();
5970     if ((!LegalOperations && !LN0->isVolatile()) ||
5971         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5972       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5973                                        LN0->getChain(),
5974                                        LN0->getBasePtr(), MemVT,
5975                                        LN0->getMemOperand());
5976       CombineTo(N, ExtLoad);
5977       CombineTo(N0.getNode(),
5978                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5979                             N0.getValueType(), ExtLoad),
5980                 ExtLoad.getValue(1));
5981       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5982     }
5983   }
5984
5985   // fold (sext (and/or/xor (load x), cst)) ->
5986   //      (and/or/xor (sextload x), (sext cst))
5987   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5988        N0.getOpcode() == ISD::XOR) &&
5989       isa<LoadSDNode>(N0.getOperand(0)) &&
5990       N0.getOperand(1).getOpcode() == ISD::Constant &&
5991       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5992       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5993     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5994     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5995       bool DoXform = true;
5996       SmallVector<SDNode*, 4> SetCCs;
5997       if (!N0.hasOneUse())
5998         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5999                                           SetCCs, TLI);
6000       if (DoXform) {
6001         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6002                                          LN0->getChain(), LN0->getBasePtr(),
6003                                          LN0->getMemoryVT(),
6004                                          LN0->getMemOperand());
6005         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6006         Mask = Mask.sext(VT.getSizeInBits());
6007         SDLoc DL(N);
6008         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6009                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6010         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6011                                     SDLoc(N0.getOperand(0)),
6012                                     N0.getOperand(0).getValueType(), ExtLoad);
6013         CombineTo(N, And);
6014         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6015         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6016                         ISD::SIGN_EXTEND);
6017         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6018       }
6019     }
6020   }
6021
6022   if (N0.getOpcode() == ISD::SETCC) {
6023     EVT N0VT = N0.getOperand(0).getValueType();
6024     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6025     // Only do this before legalize for now.
6026     if (VT.isVector() && !LegalOperations &&
6027         TLI.getBooleanContents(N0VT) ==
6028             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6029       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6030       // of the same size as the compared operands. Only optimize sext(setcc())
6031       // if this is the case.
6032       EVT SVT = getSetCCResultType(N0VT);
6033
6034       // We know that the # elements of the results is the same as the
6035       // # elements of the compare (and the # elements of the compare result
6036       // for that matter).  Check to see that they are the same size.  If so,
6037       // we know that the element size of the sext'd result matches the
6038       // element size of the compare operands.
6039       if (VT.getSizeInBits() == SVT.getSizeInBits())
6040         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6041                              N0.getOperand(1),
6042                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6043
6044       // If the desired elements are smaller or larger than the source
6045       // elements we can use a matching integer vector type and then
6046       // truncate/sign extend
6047       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6048       if (SVT == MatchingVectorType) {
6049         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6050                                N0.getOperand(0), N0.getOperand(1),
6051                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6052         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6053       }
6054     }
6055
6056     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6057     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6058     SDLoc DL(N);
6059     SDValue NegOne =
6060       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6061     SDValue SCC =
6062       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6063                        NegOne, DAG.getConstant(0, DL, VT),
6064                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6065     if (SCC.getNode()) return SCC;
6066
6067     if (!VT.isVector()) {
6068       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6069       if (!LegalOperations ||
6070           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6071         SDLoc DL(N);
6072         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6073         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6074                                      N0.getOperand(0), N0.getOperand(1), CC);
6075         return DAG.getSelect(DL, VT, SetCC,
6076                              NegOne, DAG.getConstant(0, DL, VT));
6077       }
6078     }
6079   }
6080
6081   // fold (sext x) -> (zext x) if the sign bit is known zero.
6082   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6083       DAG.SignBitIsZero(N0))
6084     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6085
6086   return SDValue();
6087 }
6088
6089 // isTruncateOf - If N is a truncate of some other value, return true, record
6090 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6091 // This function computes KnownZero to avoid a duplicated call to
6092 // computeKnownBits in the caller.
6093 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6094                          APInt &KnownZero) {
6095   APInt KnownOne;
6096   if (N->getOpcode() == ISD::TRUNCATE) {
6097     Op = N->getOperand(0);
6098     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6099     return true;
6100   }
6101
6102   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6103       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6104     return false;
6105
6106   SDValue Op0 = N->getOperand(0);
6107   SDValue Op1 = N->getOperand(1);
6108   assert(Op0.getValueType() == Op1.getValueType());
6109
6110   if (isNullConstant(Op0))
6111     Op = Op1;
6112   else if (isNullConstant(Op1))
6113     Op = Op0;
6114   else
6115     return false;
6116
6117   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6118
6119   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6120     return false;
6121
6122   return true;
6123 }
6124
6125 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6126   SDValue N0 = N->getOperand(0);
6127   EVT VT = N->getValueType(0);
6128
6129   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6130                                               LegalOperations))
6131     return SDValue(Res, 0);
6132
6133   // fold (zext (zext x)) -> (zext x)
6134   // fold (zext (aext x)) -> (zext x)
6135   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6136     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6137                        N0.getOperand(0));
6138
6139   // fold (zext (truncate x)) -> (zext x) or
6140   //      (zext (truncate x)) -> (truncate x)
6141   // This is valid when the truncated bits of x are already zero.
6142   // FIXME: We should extend this to work for vectors too.
6143   SDValue Op;
6144   APInt KnownZero;
6145   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6146     APInt TruncatedBits =
6147       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6148       APInt(Op.getValueSizeInBits(), 0) :
6149       APInt::getBitsSet(Op.getValueSizeInBits(),
6150                         N0.getValueSizeInBits(),
6151                         std::min(Op.getValueSizeInBits(),
6152                                  VT.getSizeInBits()));
6153     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6154       if (VT.bitsGT(Op.getValueType()))
6155         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6156       if (VT.bitsLT(Op.getValueType()))
6157         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6158
6159       return Op;
6160     }
6161   }
6162
6163   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6164   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6165   if (N0.getOpcode() == ISD::TRUNCATE) {
6166     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6167       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6168       if (NarrowLoad.getNode() != N0.getNode()) {
6169         CombineTo(N0.getNode(), NarrowLoad);
6170         // CombineTo deleted the truncate, if needed, but not what's under it.
6171         AddToWorklist(oye);
6172       }
6173       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6174     }
6175   }
6176
6177   // fold (zext (truncate x)) -> (and x, mask)
6178   if (N0.getOpcode() == ISD::TRUNCATE) {
6179     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6180     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6181     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6182       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6183       if (NarrowLoad.getNode() != N0.getNode()) {
6184         CombineTo(N0.getNode(), NarrowLoad);
6185         // CombineTo deleted the truncate, if needed, but not what's under it.
6186         AddToWorklist(oye);
6187       }
6188       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6189     }
6190
6191     EVT SrcVT = N0.getOperand(0).getValueType();
6192     EVT MinVT = N0.getValueType();
6193
6194     // Try to mask before the extension to avoid having to generate a larger mask,
6195     // possibly over several sub-vectors.
6196     if (SrcVT.bitsLT(VT)) {
6197       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6198                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6199         SDValue Op = N0.getOperand(0);
6200         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6201         AddToWorklist(Op.getNode());
6202         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6203       }
6204     }
6205
6206     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6207       SDValue Op = N0.getOperand(0);
6208       if (SrcVT.bitsLT(VT)) {
6209         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6210         AddToWorklist(Op.getNode());
6211       } else if (SrcVT.bitsGT(VT)) {
6212         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6213         AddToWorklist(Op.getNode());
6214       }
6215       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6216     }
6217   }
6218
6219   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6220   // if either of the casts is not free.
6221   if (N0.getOpcode() == ISD::AND &&
6222       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6223       N0.getOperand(1).getOpcode() == ISD::Constant &&
6224       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6225                            N0.getValueType()) ||
6226        !TLI.isZExtFree(N0.getValueType(), VT))) {
6227     SDValue X = N0.getOperand(0).getOperand(0);
6228     if (X.getValueType().bitsLT(VT)) {
6229       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6230     } else if (X.getValueType().bitsGT(VT)) {
6231       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6232     }
6233     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6234     Mask = Mask.zext(VT.getSizeInBits());
6235     SDLoc DL(N);
6236     return DAG.getNode(ISD::AND, DL, VT,
6237                        X, DAG.getConstant(Mask, DL, VT));
6238   }
6239
6240   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6241   // Only generate vector extloads when 1) they're legal, and 2) they are
6242   // deemed desirable by the target.
6243   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6244       ((!LegalOperations && !VT.isVector() &&
6245         !cast<LoadSDNode>(N0)->isVolatile()) ||
6246        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6247     bool DoXform = true;
6248     SmallVector<SDNode*, 4> SetCCs;
6249     if (!N0.hasOneUse())
6250       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6251     if (VT.isVector())
6252       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6253     if (DoXform) {
6254       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6255       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6256                                        LN0->getChain(),
6257                                        LN0->getBasePtr(), N0.getValueType(),
6258                                        LN0->getMemOperand());
6259       CombineTo(N, ExtLoad);
6260       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6261                                   N0.getValueType(), ExtLoad);
6262       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6263
6264       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6265                       ISD::ZERO_EXTEND);
6266       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6267     }
6268   }
6269
6270   // fold (zext (load x)) to multiple smaller zextloads.
6271   // Only on illegal but splittable vectors.
6272   if (SDValue ExtLoad = CombineExtLoad(N))
6273     return ExtLoad;
6274
6275   // fold (zext (and/or/xor (load x), cst)) ->
6276   //      (and/or/xor (zextload x), (zext cst))
6277   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6278        N0.getOpcode() == ISD::XOR) &&
6279       isa<LoadSDNode>(N0.getOperand(0)) &&
6280       N0.getOperand(1).getOpcode() == ISD::Constant &&
6281       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6282       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6283     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6284     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6285       bool DoXform = true;
6286       SmallVector<SDNode*, 4> SetCCs;
6287       if (!N0.hasOneUse())
6288         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6289                                           SetCCs, TLI);
6290       if (DoXform) {
6291         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6292                                          LN0->getChain(), LN0->getBasePtr(),
6293                                          LN0->getMemoryVT(),
6294                                          LN0->getMemOperand());
6295         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6296         Mask = Mask.zext(VT.getSizeInBits());
6297         SDLoc DL(N);
6298         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6299                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6300         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6301                                     SDLoc(N0.getOperand(0)),
6302                                     N0.getOperand(0).getValueType(), ExtLoad);
6303         CombineTo(N, And);
6304         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6305         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6306                         ISD::ZERO_EXTEND);
6307         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6308       }
6309     }
6310   }
6311
6312   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6313   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6314   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6315       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6316     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6317     EVT MemVT = LN0->getMemoryVT();
6318     if ((!LegalOperations && !LN0->isVolatile()) ||
6319         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6320       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6321                                        LN0->getChain(),
6322                                        LN0->getBasePtr(), MemVT,
6323                                        LN0->getMemOperand());
6324       CombineTo(N, ExtLoad);
6325       CombineTo(N0.getNode(),
6326                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6327                             ExtLoad),
6328                 ExtLoad.getValue(1));
6329       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6330     }
6331   }
6332
6333   if (N0.getOpcode() == ISD::SETCC) {
6334     if (!LegalOperations && VT.isVector() &&
6335         N0.getValueType().getVectorElementType() == MVT::i1) {
6336       EVT N0VT = N0.getOperand(0).getValueType();
6337       if (getSetCCResultType(N0VT) == N0.getValueType())
6338         return SDValue();
6339
6340       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6341       // Only do this before legalize for now.
6342       EVT EltVT = VT.getVectorElementType();
6343       SDLoc DL(N);
6344       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6345                                     DAG.getConstant(1, DL, EltVT));
6346       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6347         // We know that the # elements of the results is the same as the
6348         // # elements of the compare (and the # elements of the compare result
6349         // for that matter).  Check to see that they are the same size.  If so,
6350         // we know that the element size of the sext'd result matches the
6351         // element size of the compare operands.
6352         return DAG.getNode(ISD::AND, DL, VT,
6353                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6354                                          N0.getOperand(1),
6355                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6356                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6357                                        OneOps));
6358
6359       // If the desired elements are smaller or larger than the source
6360       // elements we can use a matching integer vector type and then
6361       // truncate/sign extend
6362       EVT MatchingElementType =
6363         EVT::getIntegerVT(*DAG.getContext(),
6364                           N0VT.getScalarType().getSizeInBits());
6365       EVT MatchingVectorType =
6366         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6367                          N0VT.getVectorNumElements());
6368       SDValue VsetCC =
6369         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6370                       N0.getOperand(1),
6371                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6372       return DAG.getNode(ISD::AND, DL, VT,
6373                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6374                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6375     }
6376
6377     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6378     SDLoc DL(N);
6379     SDValue SCC =
6380       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6381                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6382                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6383     if (SCC.getNode()) return SCC;
6384   }
6385
6386   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6387   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6388       isa<ConstantSDNode>(N0.getOperand(1)) &&
6389       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6390       N0.hasOneUse()) {
6391     SDValue ShAmt = N0.getOperand(1);
6392     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6393     if (N0.getOpcode() == ISD::SHL) {
6394       SDValue InnerZExt = N0.getOperand(0);
6395       // If the original shl may be shifting out bits, do not perform this
6396       // transformation.
6397       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6398         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6399       if (ShAmtVal > KnownZeroBits)
6400         return SDValue();
6401     }
6402
6403     SDLoc DL(N);
6404
6405     // Ensure that the shift amount is wide enough for the shifted value.
6406     if (VT.getSizeInBits() >= 256)
6407       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6408
6409     return DAG.getNode(N0.getOpcode(), DL, VT,
6410                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6411                        ShAmt);
6412   }
6413
6414   return SDValue();
6415 }
6416
6417 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6418   SDValue N0 = N->getOperand(0);
6419   EVT VT = N->getValueType(0);
6420
6421   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6422                                               LegalOperations))
6423     return SDValue(Res, 0);
6424
6425   // fold (aext (aext x)) -> (aext x)
6426   // fold (aext (zext x)) -> (zext x)
6427   // fold (aext (sext x)) -> (sext x)
6428   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6429       N0.getOpcode() == ISD::ZERO_EXTEND ||
6430       N0.getOpcode() == ISD::SIGN_EXTEND)
6431     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6432
6433   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6434   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6435   if (N0.getOpcode() == ISD::TRUNCATE) {
6436     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6437       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6438       if (NarrowLoad.getNode() != N0.getNode()) {
6439         CombineTo(N0.getNode(), NarrowLoad);
6440         // CombineTo deleted the truncate, if needed, but not what's under it.
6441         AddToWorklist(oye);
6442       }
6443       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6444     }
6445   }
6446
6447   // fold (aext (truncate x))
6448   if (N0.getOpcode() == ISD::TRUNCATE) {
6449     SDValue TruncOp = N0.getOperand(0);
6450     if (TruncOp.getValueType() == VT)
6451       return TruncOp; // x iff x size == zext size.
6452     if (TruncOp.getValueType().bitsGT(VT))
6453       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6454     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6455   }
6456
6457   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6458   // if the trunc is not free.
6459   if (N0.getOpcode() == ISD::AND &&
6460       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6461       N0.getOperand(1).getOpcode() == ISD::Constant &&
6462       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6463                           N0.getValueType())) {
6464     SDValue X = N0.getOperand(0).getOperand(0);
6465     if (X.getValueType().bitsLT(VT)) {
6466       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6467     } else if (X.getValueType().bitsGT(VT)) {
6468       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6469     }
6470     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6471     Mask = Mask.zext(VT.getSizeInBits());
6472     SDLoc DL(N);
6473     return DAG.getNode(ISD::AND, DL, VT,
6474                        X, DAG.getConstant(Mask, DL, VT));
6475   }
6476
6477   // fold (aext (load x)) -> (aext (truncate (extload x)))
6478   // None of the supported targets knows how to perform load and any_ext
6479   // on vectors in one instruction.  We only perform this transformation on
6480   // scalars.
6481   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6482       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6483       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6484     bool DoXform = true;
6485     SmallVector<SDNode*, 4> SetCCs;
6486     if (!N0.hasOneUse())
6487       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6488     if (DoXform) {
6489       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6490       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6491                                        LN0->getChain(),
6492                                        LN0->getBasePtr(), N0.getValueType(),
6493                                        LN0->getMemOperand());
6494       CombineTo(N, ExtLoad);
6495       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6496                                   N0.getValueType(), ExtLoad);
6497       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6498       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6499                       ISD::ANY_EXTEND);
6500       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6501     }
6502   }
6503
6504   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6505   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6506   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6507   if (N0.getOpcode() == ISD::LOAD &&
6508       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6509       N0.hasOneUse()) {
6510     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6511     ISD::LoadExtType ExtType = LN0->getExtensionType();
6512     EVT MemVT = LN0->getMemoryVT();
6513     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6514       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6515                                        VT, LN0->getChain(), LN0->getBasePtr(),
6516                                        MemVT, LN0->getMemOperand());
6517       CombineTo(N, ExtLoad);
6518       CombineTo(N0.getNode(),
6519                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6520                             N0.getValueType(), ExtLoad),
6521                 ExtLoad.getValue(1));
6522       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6523     }
6524   }
6525
6526   if (N0.getOpcode() == ISD::SETCC) {
6527     // For vectors:
6528     // aext(setcc) -> vsetcc
6529     // aext(setcc) -> truncate(vsetcc)
6530     // aext(setcc) -> aext(vsetcc)
6531     // Only do this before legalize for now.
6532     if (VT.isVector() && !LegalOperations) {
6533       EVT N0VT = N0.getOperand(0).getValueType();
6534         // We know that the # elements of the results is the same as the
6535         // # elements of the compare (and the # elements of the compare result
6536         // for that matter).  Check to see that they are the same size.  If so,
6537         // we know that the element size of the sext'd result matches the
6538         // element size of the compare operands.
6539       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6540         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6541                              N0.getOperand(1),
6542                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6543       // If the desired elements are smaller or larger than the source
6544       // elements we can use a matching integer vector type and then
6545       // truncate/any extend
6546       else {
6547         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6548         SDValue VsetCC =
6549           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6550                         N0.getOperand(1),
6551                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6552         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6553       }
6554     }
6555
6556     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6557     SDLoc DL(N);
6558     SDValue SCC =
6559       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6560                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6561                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6562     if (SCC.getNode())
6563       return SCC;
6564   }
6565
6566   return SDValue();
6567 }
6568
6569 /// See if the specified operand can be simplified with the knowledge that only
6570 /// the bits specified by Mask are used.  If so, return the simpler operand,
6571 /// otherwise return a null SDValue.
6572 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6573   switch (V.getOpcode()) {
6574   default: break;
6575   case ISD::Constant: {
6576     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6577     assert(CV && "Const value should be ConstSDNode.");
6578     const APInt &CVal = CV->getAPIntValue();
6579     APInt NewVal = CVal & Mask;
6580     if (NewVal != CVal)
6581       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6582     break;
6583   }
6584   case ISD::OR:
6585   case ISD::XOR:
6586     // If the LHS or RHS don't contribute bits to the or, drop them.
6587     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6588       return V.getOperand(1);
6589     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6590       return V.getOperand(0);
6591     break;
6592   case ISD::SRL:
6593     // Only look at single-use SRLs.
6594     if (!V.getNode()->hasOneUse())
6595       break;
6596     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6597       // See if we can recursively simplify the LHS.
6598       unsigned Amt = RHSC->getZExtValue();
6599
6600       // Watch out for shift count overflow though.
6601       if (Amt >= Mask.getBitWidth()) break;
6602       APInt NewMask = Mask << Amt;
6603       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6604         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6605                            SimplifyLHS, V.getOperand(1));
6606     }
6607   }
6608   return SDValue();
6609 }
6610
6611 /// If the result of a wider load is shifted to right of N  bits and then
6612 /// truncated to a narrower type and where N is a multiple of number of bits of
6613 /// the narrower type, transform it to a narrower load from address + N / num of
6614 /// bits of new type. If the result is to be extended, also fold the extension
6615 /// to form a extending load.
6616 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6617   unsigned Opc = N->getOpcode();
6618
6619   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6620   SDValue N0 = N->getOperand(0);
6621   EVT VT = N->getValueType(0);
6622   EVT ExtVT = VT;
6623
6624   // This transformation isn't valid for vector loads.
6625   if (VT.isVector())
6626     return SDValue();
6627
6628   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6629   // extended to VT.
6630   if (Opc == ISD::SIGN_EXTEND_INREG) {
6631     ExtType = ISD::SEXTLOAD;
6632     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6633   } else if (Opc == ISD::SRL) {
6634     // Another special-case: SRL is basically zero-extending a narrower value.
6635     ExtType = ISD::ZEXTLOAD;
6636     N0 = SDValue(N, 0);
6637     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6638     if (!N01) return SDValue();
6639     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6640                               VT.getSizeInBits() - N01->getZExtValue());
6641   }
6642   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6643     return SDValue();
6644
6645   unsigned EVTBits = ExtVT.getSizeInBits();
6646
6647   // Do not generate loads of non-round integer types since these can
6648   // be expensive (and would be wrong if the type is not byte sized).
6649   if (!ExtVT.isRound())
6650     return SDValue();
6651
6652   unsigned ShAmt = 0;
6653   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6654     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6655       ShAmt = N01->getZExtValue();
6656       // Is the shift amount a multiple of size of VT?
6657       if ((ShAmt & (EVTBits-1)) == 0) {
6658         N0 = N0.getOperand(0);
6659         // Is the load width a multiple of size of VT?
6660         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6661           return SDValue();
6662       }
6663
6664       // At this point, we must have a load or else we can't do the transform.
6665       if (!isa<LoadSDNode>(N0)) return SDValue();
6666
6667       // Because a SRL must be assumed to *need* to zero-extend the high bits
6668       // (as opposed to anyext the high bits), we can't combine the zextload
6669       // lowering of SRL and an sextload.
6670       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6671         return SDValue();
6672
6673       // If the shift amount is larger than the input type then we're not
6674       // accessing any of the loaded bytes.  If the load was a zextload/extload
6675       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6676       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6677         return SDValue();
6678     }
6679   }
6680
6681   // If the load is shifted left (and the result isn't shifted back right),
6682   // we can fold the truncate through the shift.
6683   unsigned ShLeftAmt = 0;
6684   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6685       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6686     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6687       ShLeftAmt = N01->getZExtValue();
6688       N0 = N0.getOperand(0);
6689     }
6690   }
6691
6692   // If we haven't found a load, we can't narrow it.  Don't transform one with
6693   // multiple uses, this would require adding a new load.
6694   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6695     return SDValue();
6696
6697   // Don't change the width of a volatile load.
6698   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6699   if (LN0->isVolatile())
6700     return SDValue();
6701
6702   // Verify that we are actually reducing a load width here.
6703   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6704     return SDValue();
6705
6706   // For the transform to be legal, the load must produce only two values
6707   // (the value loaded and the chain).  Don't transform a pre-increment
6708   // load, for example, which produces an extra value.  Otherwise the
6709   // transformation is not equivalent, and the downstream logic to replace
6710   // uses gets things wrong.
6711   if (LN0->getNumValues() > 2)
6712     return SDValue();
6713
6714   // If the load that we're shrinking is an extload and we're not just
6715   // discarding the extension we can't simply shrink the load. Bail.
6716   // TODO: It would be possible to merge the extensions in some cases.
6717   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6718       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6719     return SDValue();
6720
6721   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6722     return SDValue();
6723
6724   EVT PtrType = N0.getOperand(1).getValueType();
6725
6726   if (PtrType == MVT::Untyped || PtrType.isExtended())
6727     // It's not possible to generate a constant of extended or untyped type.
6728     return SDValue();
6729
6730   // For big endian targets, we need to adjust the offset to the pointer to
6731   // load the correct bytes.
6732   if (DAG.getDataLayout().isBigEndian()) {
6733     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6734     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6735     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6736   }
6737
6738   uint64_t PtrOff = ShAmt / 8;
6739   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6740   SDLoc DL(LN0);
6741   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6742                                PtrType, LN0->getBasePtr(),
6743                                DAG.getConstant(PtrOff, DL, PtrType));
6744   AddToWorklist(NewPtr.getNode());
6745
6746   SDValue Load;
6747   if (ExtType == ISD::NON_EXTLOAD)
6748     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6749                         LN0->getPointerInfo().getWithOffset(PtrOff),
6750                         LN0->isVolatile(), LN0->isNonTemporal(),
6751                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6752   else
6753     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6754                           LN0->getPointerInfo().getWithOffset(PtrOff),
6755                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6756                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6757
6758   // Replace the old load's chain with the new load's chain.
6759   WorklistRemover DeadNodes(*this);
6760   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6761
6762   // Shift the result left, if we've swallowed a left shift.
6763   SDValue Result = Load;
6764   if (ShLeftAmt != 0) {
6765     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6766     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6767       ShImmTy = VT;
6768     // If the shift amount is as large as the result size (but, presumably,
6769     // no larger than the source) then the useful bits of the result are
6770     // zero; we can't simply return the shortened shift, because the result
6771     // of that operation is undefined.
6772     SDLoc DL(N0);
6773     if (ShLeftAmt >= VT.getSizeInBits())
6774       Result = DAG.getConstant(0, DL, VT);
6775     else
6776       Result = DAG.getNode(ISD::SHL, DL, VT,
6777                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6778   }
6779
6780   // Return the new loaded value.
6781   return Result;
6782 }
6783
6784 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6785   SDValue N0 = N->getOperand(0);
6786   SDValue N1 = N->getOperand(1);
6787   EVT VT = N->getValueType(0);
6788   EVT EVT = cast<VTSDNode>(N1)->getVT();
6789   unsigned VTBits = VT.getScalarType().getSizeInBits();
6790   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6791
6792   // fold (sext_in_reg c1) -> c1
6793   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6794     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6795
6796   // If the input is already sign extended, just drop the extension.
6797   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6798     return N0;
6799
6800   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6801   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6802       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6803     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6804                        N0.getOperand(0), N1);
6805
6806   // fold (sext_in_reg (sext x)) -> (sext x)
6807   // fold (sext_in_reg (aext x)) -> (sext x)
6808   // if x is small enough.
6809   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6810     SDValue N00 = N0.getOperand(0);
6811     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6812         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6813       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6814   }
6815
6816   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6817   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6818     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6819
6820   // fold operands of sext_in_reg based on knowledge that the top bits are not
6821   // demanded.
6822   if (SimplifyDemandedBits(SDValue(N, 0)))
6823     return SDValue(N, 0);
6824
6825   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6826   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6827   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6828     return NarrowLoad;
6829
6830   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6831   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6832   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6833   if (N0.getOpcode() == ISD::SRL) {
6834     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6835       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6836         // We can turn this into an SRA iff the input to the SRL is already sign
6837         // extended enough.
6838         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6839         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6840           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6841                              N0.getOperand(0), N0.getOperand(1));
6842       }
6843   }
6844
6845   // fold (sext_inreg (extload x)) -> (sextload x)
6846   if (ISD::isEXTLoad(N0.getNode()) &&
6847       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6848       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6849       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6850        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6851     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6852     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6853                                      LN0->getChain(),
6854                                      LN0->getBasePtr(), EVT,
6855                                      LN0->getMemOperand());
6856     CombineTo(N, ExtLoad);
6857     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6858     AddToWorklist(ExtLoad.getNode());
6859     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6860   }
6861   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6862   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6863       N0.hasOneUse() &&
6864       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6865       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6866        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6867     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6868     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6869                                      LN0->getChain(),
6870                                      LN0->getBasePtr(), EVT,
6871                                      LN0->getMemOperand());
6872     CombineTo(N, ExtLoad);
6873     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6874     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6875   }
6876
6877   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6878   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6879     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6880                                        N0.getOperand(1), false);
6881     if (BSwap.getNode())
6882       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6883                          BSwap, N1);
6884   }
6885
6886   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6887   // into a build_vector.
6888   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6889     SmallVector<SDValue, 8> Elts;
6890     unsigned NumElts = N0->getNumOperands();
6891     unsigned ShAmt = VTBits - EVTBits;
6892
6893     for (unsigned i = 0; i != NumElts; ++i) {
6894       SDValue Op = N0->getOperand(i);
6895       if (Op->getOpcode() == ISD::UNDEF) {
6896         Elts.push_back(Op);
6897         continue;
6898       }
6899
6900       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6901       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6902       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6903                                      SDLoc(Op), Op.getValueType()));
6904     }
6905
6906     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6907   }
6908
6909   return SDValue();
6910 }
6911
6912 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6913   SDValue N0 = N->getOperand(0);
6914   EVT VT = N->getValueType(0);
6915
6916   if (N0.getOpcode() == ISD::UNDEF)
6917     return DAG.getUNDEF(VT);
6918
6919   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6920                                               LegalOperations))
6921     return SDValue(Res, 0);
6922
6923   return SDValue();
6924 }
6925
6926 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6927   SDValue N0 = N->getOperand(0);
6928   EVT VT = N->getValueType(0);
6929   bool isLE = DAG.getDataLayout().isLittleEndian();
6930
6931   // noop truncate
6932   if (N0.getValueType() == N->getValueType(0))
6933     return N0;
6934   // fold (truncate c1) -> c1
6935   if (isConstantIntBuildVectorOrConstantInt(N0))
6936     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6937   // fold (truncate (truncate x)) -> (truncate x)
6938   if (N0.getOpcode() == ISD::TRUNCATE)
6939     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6940   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6941   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6942       N0.getOpcode() == ISD::SIGN_EXTEND ||
6943       N0.getOpcode() == ISD::ANY_EXTEND) {
6944     if (N0.getOperand(0).getValueType().bitsLT(VT))
6945       // if the source is smaller than the dest, we still need an extend
6946       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6947                          N0.getOperand(0));
6948     if (N0.getOperand(0).getValueType().bitsGT(VT))
6949       // if the source is larger than the dest, than we just need the truncate
6950       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6951     // if the source and dest are the same type, we can drop both the extend
6952     // and the truncate.
6953     return N0.getOperand(0);
6954   }
6955
6956   // Fold extract-and-trunc into a narrow extract. For example:
6957   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6958   //   i32 y = TRUNCATE(i64 x)
6959   //        -- becomes --
6960   //   v16i8 b = BITCAST (v2i64 val)
6961   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6962   //
6963   // Note: We only run this optimization after type legalization (which often
6964   // creates this pattern) and before operation legalization after which
6965   // we need to be more careful about the vector instructions that we generate.
6966   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6967       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6968
6969     EVT VecTy = N0.getOperand(0).getValueType();
6970     EVT ExTy = N0.getValueType();
6971     EVT TrTy = N->getValueType(0);
6972
6973     unsigned NumElem = VecTy.getVectorNumElements();
6974     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6975
6976     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6977     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6978
6979     SDValue EltNo = N0->getOperand(1);
6980     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6981       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6982       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6983       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6984
6985       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6986                               NVT, N0.getOperand(0));
6987
6988       SDLoc DL(N);
6989       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6990                          DL, TrTy, V,
6991                          DAG.getConstant(Index, DL, IndexTy));
6992     }
6993   }
6994
6995   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6996   if (N0.getOpcode() == ISD::SELECT) {
6997     EVT SrcVT = N0.getValueType();
6998     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6999         TLI.isTruncateFree(SrcVT, VT)) {
7000       SDLoc SL(N0);
7001       SDValue Cond = N0.getOperand(0);
7002       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7003       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7004       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7005     }
7006   }
7007
7008   // Fold a series of buildvector, bitcast, and truncate if possible.
7009   // For example fold
7010   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7011   //   (2xi32 (buildvector x, y)).
7012   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7013       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7014       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7015       N0.getOperand(0).hasOneUse()) {
7016
7017     SDValue BuildVect = N0.getOperand(0);
7018     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7019     EVT TruncVecEltTy = VT.getVectorElementType();
7020
7021     // Check that the element types match.
7022     if (BuildVectEltTy == TruncVecEltTy) {
7023       // Now we only need to compute the offset of the truncated elements.
7024       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7025       unsigned TruncVecNumElts = VT.getVectorNumElements();
7026       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7027
7028       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7029              "Invalid number of elements");
7030
7031       SmallVector<SDValue, 8> Opnds;
7032       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7033         Opnds.push_back(BuildVect.getOperand(i));
7034
7035       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7036     }
7037   }
7038
7039   // See if we can simplify the input to this truncate through knowledge that
7040   // only the low bits are being used.
7041   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7042   // Currently we only perform this optimization on scalars because vectors
7043   // may have different active low bits.
7044   if (!VT.isVector()) {
7045     SDValue Shorter =
7046       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7047                                                VT.getSizeInBits()));
7048     if (Shorter.getNode())
7049       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7050   }
7051   // fold (truncate (load x)) -> (smaller load x)
7052   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7053   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7054     if (SDValue Reduced = ReduceLoadWidth(N))
7055       return Reduced;
7056
7057     // Handle the case where the load remains an extending load even
7058     // after truncation.
7059     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7060       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7061       if (!LN0->isVolatile() &&
7062           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7063         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7064                                          VT, LN0->getChain(), LN0->getBasePtr(),
7065                                          LN0->getMemoryVT(),
7066                                          LN0->getMemOperand());
7067         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7068         return NewLoad;
7069       }
7070     }
7071   }
7072   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7073   // where ... are all 'undef'.
7074   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7075     SmallVector<EVT, 8> VTs;
7076     SDValue V;
7077     unsigned Idx = 0;
7078     unsigned NumDefs = 0;
7079
7080     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7081       SDValue X = N0.getOperand(i);
7082       if (X.getOpcode() != ISD::UNDEF) {
7083         V = X;
7084         Idx = i;
7085         NumDefs++;
7086       }
7087       // Stop if more than one members are non-undef.
7088       if (NumDefs > 1)
7089         break;
7090       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7091                                      VT.getVectorElementType(),
7092                                      X.getValueType().getVectorNumElements()));
7093     }
7094
7095     if (NumDefs == 0)
7096       return DAG.getUNDEF(VT);
7097
7098     if (NumDefs == 1) {
7099       assert(V.getNode() && "The single defined operand is empty!");
7100       SmallVector<SDValue, 8> Opnds;
7101       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7102         if (i != Idx) {
7103           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7104           continue;
7105         }
7106         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7107         AddToWorklist(NV.getNode());
7108         Opnds.push_back(NV);
7109       }
7110       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7111     }
7112   }
7113
7114   // Simplify the operands using demanded-bits information.
7115   if (!VT.isVector() &&
7116       SimplifyDemandedBits(SDValue(N, 0)))
7117     return SDValue(N, 0);
7118
7119   return SDValue();
7120 }
7121
7122 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7123   SDValue Elt = N->getOperand(i);
7124   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7125     return Elt.getNode();
7126   return Elt.getOperand(Elt.getResNo()).getNode();
7127 }
7128
7129 /// build_pair (load, load) -> load
7130 /// if load locations are consecutive.
7131 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7132   assert(N->getOpcode() == ISD::BUILD_PAIR);
7133
7134   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7135   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7136   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7137       LD1->getAddressSpace() != LD2->getAddressSpace())
7138     return SDValue();
7139   EVT LD1VT = LD1->getValueType(0);
7140
7141   if (ISD::isNON_EXTLoad(LD2) &&
7142       LD2->hasOneUse() &&
7143       // If both are volatile this would reduce the number of volatile loads.
7144       // If one is volatile it might be ok, but play conservative and bail out.
7145       !LD1->isVolatile() &&
7146       !LD2->isVolatile() &&
7147       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7148     unsigned Align = LD1->getAlignment();
7149     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7150         VT.getTypeForEVT(*DAG.getContext()));
7151
7152     if (NewAlign <= Align &&
7153         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7154       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7155                          LD1->getBasePtr(), LD1->getPointerInfo(),
7156                          false, false, false, Align);
7157   }
7158
7159   return SDValue();
7160 }
7161
7162 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7163   SDValue N0 = N->getOperand(0);
7164   EVT VT = N->getValueType(0);
7165
7166   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7167   // Only do this before legalize, since afterward the target may be depending
7168   // on the bitconvert.
7169   // First check to see if this is all constant.
7170   if (!LegalTypes &&
7171       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7172       VT.isVector()) {
7173     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7174
7175     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7176     assert(!DestEltVT.isVector() &&
7177            "Element type of vector ValueType must not be vector!");
7178     if (isSimple)
7179       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7180   }
7181
7182   // If the input is a constant, let getNode fold it.
7183   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7184     // If we can't allow illegal operations, we need to check that this is just
7185     // a fp -> int or int -> conversion and that the resulting operation will
7186     // be legal.
7187     if (!LegalOperations ||
7188         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7189          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7190         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7191          TLI.isOperationLegal(ISD::Constant, VT)))
7192       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7193   }
7194
7195   // (conv (conv x, t1), t2) -> (conv x, t2)
7196   if (N0.getOpcode() == ISD::BITCAST)
7197     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7198                        N0.getOperand(0));
7199
7200   // fold (conv (load x)) -> (load (conv*)x)
7201   // If the resultant load doesn't need a higher alignment than the original!
7202   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7203       // Do not change the width of a volatile load.
7204       !cast<LoadSDNode>(N0)->isVolatile() &&
7205       // Do not remove the cast if the types differ in endian layout.
7206       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7207           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7208       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7209       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7210     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7211     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7212         VT.getTypeForEVT(*DAG.getContext()));
7213     unsigned OrigAlign = LN0->getAlignment();
7214
7215     if (Align <= OrigAlign) {
7216       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7217                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7218                                  LN0->isVolatile(), LN0->isNonTemporal(),
7219                                  LN0->isInvariant(), OrigAlign,
7220                                  LN0->getAAInfo());
7221       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7222       return Load;
7223     }
7224   }
7225
7226   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7227   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7228   // This often reduces constant pool loads.
7229   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7230        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7231       N0.getNode()->hasOneUse() && VT.isInteger() &&
7232       !VT.isVector() && !N0.getValueType().isVector()) {
7233     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7234                                   N0.getOperand(0));
7235     AddToWorklist(NewConv.getNode());
7236
7237     SDLoc DL(N);
7238     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7239     if (N0.getOpcode() == ISD::FNEG)
7240       return DAG.getNode(ISD::XOR, DL, VT,
7241                          NewConv, DAG.getConstant(SignBit, DL, VT));
7242     assert(N0.getOpcode() == ISD::FABS);
7243     return DAG.getNode(ISD::AND, DL, VT,
7244                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7245   }
7246
7247   // fold (bitconvert (fcopysign cst, x)) ->
7248   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7249   // Note that we don't handle (copysign x, cst) because this can always be
7250   // folded to an fneg or fabs.
7251   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7252       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7253       VT.isInteger() && !VT.isVector()) {
7254     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7255     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7256     if (isTypeLegal(IntXVT)) {
7257       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7258                               IntXVT, N0.getOperand(1));
7259       AddToWorklist(X.getNode());
7260
7261       // If X has a different width than the result/lhs, sext it or truncate it.
7262       unsigned VTWidth = VT.getSizeInBits();
7263       if (OrigXWidth < VTWidth) {
7264         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7265         AddToWorklist(X.getNode());
7266       } else if (OrigXWidth > VTWidth) {
7267         // To get the sign bit in the right place, we have to shift it right
7268         // before truncating.
7269         SDLoc DL(X);
7270         X = DAG.getNode(ISD::SRL, DL,
7271                         X.getValueType(), X,
7272                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7273                                         X.getValueType()));
7274         AddToWorklist(X.getNode());
7275         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7276         AddToWorklist(X.getNode());
7277       }
7278
7279       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7280       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7281                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7282       AddToWorklist(X.getNode());
7283
7284       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7285                                 VT, N0.getOperand(0));
7286       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7287                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7288       AddToWorklist(Cst.getNode());
7289
7290       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7291     }
7292   }
7293
7294   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7295   if (N0.getOpcode() == ISD::BUILD_PAIR)
7296     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7297       return CombineLD;
7298
7299   // Remove double bitcasts from shuffles - this is often a legacy of
7300   // XformToShuffleWithZero being used to combine bitmaskings (of
7301   // float vectors bitcast to integer vectors) into shuffles.
7302   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7303   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7304       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7305       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7306       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7307     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7308
7309     // If operands are a bitcast, peek through if it casts the original VT.
7310     // If operands are a constant, just bitcast back to original VT.
7311     auto PeekThroughBitcast = [&](SDValue Op) {
7312       if (Op.getOpcode() == ISD::BITCAST &&
7313           Op.getOperand(0).getValueType() == VT)
7314         return SDValue(Op.getOperand(0));
7315       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7316           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7317         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7318       return SDValue();
7319     };
7320
7321     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7322     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7323     if (!(SV0 && SV1))
7324       return SDValue();
7325
7326     int MaskScale =
7327         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7328     SmallVector<int, 8> NewMask;
7329     for (int M : SVN->getMask())
7330       for (int i = 0; i != MaskScale; ++i)
7331         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7332
7333     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7334     if (!LegalMask) {
7335       std::swap(SV0, SV1);
7336       ShuffleVectorSDNode::commuteMask(NewMask);
7337       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7338     }
7339
7340     if (LegalMask)
7341       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7342   }
7343
7344   return SDValue();
7345 }
7346
7347 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7348   EVT VT = N->getValueType(0);
7349   return CombineConsecutiveLoads(N, VT);
7350 }
7351
7352 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7353 /// operands. DstEltVT indicates the destination element value type.
7354 SDValue DAGCombiner::
7355 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7356   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7357
7358   // If this is already the right type, we're done.
7359   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7360
7361   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7362   unsigned DstBitSize = DstEltVT.getSizeInBits();
7363
7364   // If this is a conversion of N elements of one type to N elements of another
7365   // type, convert each element.  This handles FP<->INT cases.
7366   if (SrcBitSize == DstBitSize) {
7367     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7368                               BV->getValueType(0).getVectorNumElements());
7369
7370     // Due to the FP element handling below calling this routine recursively,
7371     // we can end up with a scalar-to-vector node here.
7372     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7373       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7374                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7375                                      DstEltVT, BV->getOperand(0)));
7376
7377     SmallVector<SDValue, 8> Ops;
7378     for (SDValue Op : BV->op_values()) {
7379       // If the vector element type is not legal, the BUILD_VECTOR operands
7380       // are promoted and implicitly truncated.  Make that explicit here.
7381       if (Op.getValueType() != SrcEltVT)
7382         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7383       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7384                                 DstEltVT, Op));
7385       AddToWorklist(Ops.back().getNode());
7386     }
7387     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7388   }
7389
7390   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7391   // handle annoying details of growing/shrinking FP values, we convert them to
7392   // int first.
7393   if (SrcEltVT.isFloatingPoint()) {
7394     // Convert the input float vector to a int vector where the elements are the
7395     // same sizes.
7396     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7397     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7398     SrcEltVT = IntVT;
7399   }
7400
7401   // Now we know the input is an integer vector.  If the output is a FP type,
7402   // convert to integer first, then to FP of the right size.
7403   if (DstEltVT.isFloatingPoint()) {
7404     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7405     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7406
7407     // Next, convert to FP elements of the same size.
7408     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7409   }
7410
7411   SDLoc DL(BV);
7412
7413   // Okay, we know the src/dst types are both integers of differing types.
7414   // Handling growing first.
7415   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7416   if (SrcBitSize < DstBitSize) {
7417     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7418
7419     SmallVector<SDValue, 8> Ops;
7420     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7421          i += NumInputsPerOutput) {
7422       bool isLE = DAG.getDataLayout().isLittleEndian();
7423       APInt NewBits = APInt(DstBitSize, 0);
7424       bool EltIsUndef = true;
7425       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7426         // Shift the previously computed bits over.
7427         NewBits <<= SrcBitSize;
7428         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7429         if (Op.getOpcode() == ISD::UNDEF) continue;
7430         EltIsUndef = false;
7431
7432         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7433                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7434       }
7435
7436       if (EltIsUndef)
7437         Ops.push_back(DAG.getUNDEF(DstEltVT));
7438       else
7439         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7440     }
7441
7442     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7443     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7444   }
7445
7446   // Finally, this must be the case where we are shrinking elements: each input
7447   // turns into multiple outputs.
7448   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7449   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7450                             NumOutputsPerInput*BV->getNumOperands());
7451   SmallVector<SDValue, 8> Ops;
7452
7453   for (const SDValue &Op : BV->op_values()) {
7454     if (Op.getOpcode() == ISD::UNDEF) {
7455       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7456       continue;
7457     }
7458
7459     APInt OpVal = cast<ConstantSDNode>(Op)->
7460                   getAPIntValue().zextOrTrunc(SrcBitSize);
7461
7462     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7463       APInt ThisVal = OpVal.trunc(DstBitSize);
7464       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7465       OpVal = OpVal.lshr(DstBitSize);
7466     }
7467
7468     // For big endian targets, swap the order of the pieces of each element.
7469     if (DAG.getDataLayout().isBigEndian())
7470       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7471   }
7472
7473   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7474 }
7475
7476 /// Try to perform FMA combining on a given FADD node.
7477 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7478   SDValue N0 = N->getOperand(0);
7479   SDValue N1 = N->getOperand(1);
7480   EVT VT = N->getValueType(0);
7481   SDLoc SL(N);
7482
7483   const TargetOptions &Options = DAG.getTarget().Options;
7484   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7485                        Options.UnsafeFPMath);
7486
7487   // Floating-point multiply-add with intermediate rounding.
7488   bool HasFMAD = (LegalOperations &&
7489                   TLI.isOperationLegal(ISD::FMAD, VT));
7490
7491   // Floating-point multiply-add without intermediate rounding.
7492   bool HasFMA = ((!LegalOperations ||
7493                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7494                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7495                  UnsafeFPMath);
7496
7497   // No valid opcode, do not combine.
7498   if (!HasFMAD && !HasFMA)
7499     return SDValue();
7500
7501   // Always prefer FMAD to FMA for precision.
7502   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7503   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7504   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7505
7506   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7507   // prefer to fold the multiply with fewer uses.
7508   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7509       N1.getOpcode() == ISD::FMUL) {
7510     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7511       std::swap(N0, N1);
7512   }
7513
7514   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7515   if (N0.getOpcode() == ISD::FMUL &&
7516       (Aggressive || N0->hasOneUse())) {
7517     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7518                        N0.getOperand(0), N0.getOperand(1), N1);
7519   }
7520
7521   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7522   // Note: Commutes FADD operands.
7523   if (N1.getOpcode() == ISD::FMUL &&
7524       (Aggressive || N1->hasOneUse())) {
7525     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7526                        N1.getOperand(0), N1.getOperand(1), N0);
7527   }
7528
7529   // Look through FP_EXTEND nodes to do more combining.
7530   if (UnsafeFPMath && LookThroughFPExt) {
7531     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7532     if (N0.getOpcode() == ISD::FP_EXTEND) {
7533       SDValue N00 = N0.getOperand(0);
7534       if (N00.getOpcode() == ISD::FMUL)
7535         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7536                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7537                                        N00.getOperand(0)),
7538                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7539                                        N00.getOperand(1)), N1);
7540     }
7541
7542     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7543     // Note: Commutes FADD operands.
7544     if (N1.getOpcode() == ISD::FP_EXTEND) {
7545       SDValue N10 = N1.getOperand(0);
7546       if (N10.getOpcode() == ISD::FMUL)
7547         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7548                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7549                                        N10.getOperand(0)),
7550                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7551                                        N10.getOperand(1)), N0);
7552     }
7553   }
7554
7555   // More folding opportunities when target permits.
7556   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7557     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7558     if (N0.getOpcode() == PreferredFusedOpcode &&
7559         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7560       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7561                          N0.getOperand(0), N0.getOperand(1),
7562                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7563                                      N0.getOperand(2).getOperand(0),
7564                                      N0.getOperand(2).getOperand(1),
7565                                      N1));
7566     }
7567
7568     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7569     if (N1->getOpcode() == PreferredFusedOpcode &&
7570         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7571       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7572                          N1.getOperand(0), N1.getOperand(1),
7573                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7574                                      N1.getOperand(2).getOperand(0),
7575                                      N1.getOperand(2).getOperand(1),
7576                                      N0));
7577     }
7578
7579     if (UnsafeFPMath && LookThroughFPExt) {
7580       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7581       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7582       auto FoldFAddFMAFPExtFMul = [&] (
7583           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7584         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7585                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7586                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7587                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7588                                        Z));
7589       };
7590       if (N0.getOpcode() == PreferredFusedOpcode) {
7591         SDValue N02 = N0.getOperand(2);
7592         if (N02.getOpcode() == ISD::FP_EXTEND) {
7593           SDValue N020 = N02.getOperand(0);
7594           if (N020.getOpcode() == ISD::FMUL)
7595             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7596                                         N020.getOperand(0), N020.getOperand(1),
7597                                         N1);
7598         }
7599       }
7600
7601       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7602       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7603       // FIXME: This turns two single-precision and one double-precision
7604       // operation into two double-precision operations, which might not be
7605       // interesting for all targets, especially GPUs.
7606       auto FoldFAddFPExtFMAFMul = [&] (
7607           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7608         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7609                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7610                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7611                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7612                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7613                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7614                                        Z));
7615       };
7616       if (N0.getOpcode() == ISD::FP_EXTEND) {
7617         SDValue N00 = N0.getOperand(0);
7618         if (N00.getOpcode() == PreferredFusedOpcode) {
7619           SDValue N002 = N00.getOperand(2);
7620           if (N002.getOpcode() == ISD::FMUL)
7621             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7622                                         N002.getOperand(0), N002.getOperand(1),
7623                                         N1);
7624         }
7625       }
7626
7627       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7628       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7629       if (N1.getOpcode() == PreferredFusedOpcode) {
7630         SDValue N12 = N1.getOperand(2);
7631         if (N12.getOpcode() == ISD::FP_EXTEND) {
7632           SDValue N120 = N12.getOperand(0);
7633           if (N120.getOpcode() == ISD::FMUL)
7634             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7635                                         N120.getOperand(0), N120.getOperand(1),
7636                                         N0);
7637         }
7638       }
7639
7640       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7641       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7642       // FIXME: This turns two single-precision and one double-precision
7643       // operation into two double-precision operations, which might not be
7644       // interesting for all targets, especially GPUs.
7645       if (N1.getOpcode() == ISD::FP_EXTEND) {
7646         SDValue N10 = N1.getOperand(0);
7647         if (N10.getOpcode() == PreferredFusedOpcode) {
7648           SDValue N102 = N10.getOperand(2);
7649           if (N102.getOpcode() == ISD::FMUL)
7650             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7651                                         N102.getOperand(0), N102.getOperand(1),
7652                                         N0);
7653         }
7654       }
7655     }
7656   }
7657
7658   return SDValue();
7659 }
7660
7661 /// Try to perform FMA combining on a given FSUB node.
7662 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7663   SDValue N0 = N->getOperand(0);
7664   SDValue N1 = N->getOperand(1);
7665   EVT VT = N->getValueType(0);
7666   SDLoc SL(N);
7667
7668   const TargetOptions &Options = DAG.getTarget().Options;
7669   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7670                        Options.UnsafeFPMath);
7671
7672   // Floating-point multiply-add with intermediate rounding.
7673   bool HasFMAD = (LegalOperations &&
7674                   TLI.isOperationLegal(ISD::FMAD, VT));
7675
7676   // Floating-point multiply-add without intermediate rounding.
7677   bool HasFMA = ((!LegalOperations ||
7678                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7679                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7680                  UnsafeFPMath);
7681
7682   // No valid opcode, do not combine.
7683   if (!HasFMAD && !HasFMA)
7684     return SDValue();
7685
7686   // Always prefer FMAD to FMA for precision.
7687   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7688   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7689   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7690
7691   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7692   if (N0.getOpcode() == ISD::FMUL &&
7693       (Aggressive || N0->hasOneUse())) {
7694     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7695                        N0.getOperand(0), N0.getOperand(1),
7696                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7697   }
7698
7699   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7700   // Note: Commutes FSUB operands.
7701   if (N1.getOpcode() == ISD::FMUL &&
7702       (Aggressive || N1->hasOneUse()))
7703     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7704                        DAG.getNode(ISD::FNEG, SL, VT,
7705                                    N1.getOperand(0)),
7706                        N1.getOperand(1), N0);
7707
7708   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7709   if (N0.getOpcode() == ISD::FNEG &&
7710       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7711       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7712     SDValue N00 = N0.getOperand(0).getOperand(0);
7713     SDValue N01 = N0.getOperand(0).getOperand(1);
7714     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7715                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7716                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7717   }
7718
7719   // Look through FP_EXTEND nodes to do more combining.
7720   if (UnsafeFPMath && LookThroughFPExt) {
7721     // fold (fsub (fpext (fmul x, y)), z)
7722     //   -> (fma (fpext x), (fpext y), (fneg z))
7723     if (N0.getOpcode() == ISD::FP_EXTEND) {
7724       SDValue N00 = N0.getOperand(0);
7725       if (N00.getOpcode() == ISD::FMUL)
7726         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7727                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7728                                        N00.getOperand(0)),
7729                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7730                                        N00.getOperand(1)),
7731                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7732     }
7733
7734     // fold (fsub x, (fpext (fmul y, z)))
7735     //   -> (fma (fneg (fpext y)), (fpext z), x)
7736     // Note: Commutes FSUB operands.
7737     if (N1.getOpcode() == ISD::FP_EXTEND) {
7738       SDValue N10 = N1.getOperand(0);
7739       if (N10.getOpcode() == ISD::FMUL)
7740         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7741                            DAG.getNode(ISD::FNEG, SL, VT,
7742                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7743                                                    N10.getOperand(0))),
7744                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7745                                        N10.getOperand(1)),
7746                            N0);
7747     }
7748
7749     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7750     //   -> (fneg (fma (fpext x), (fpext y), z))
7751     // Note: This could be removed with appropriate canonicalization of the
7752     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7753     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7754     // from implementing the canonicalization in visitFSUB.
7755     if (N0.getOpcode() == ISD::FP_EXTEND) {
7756       SDValue N00 = N0.getOperand(0);
7757       if (N00.getOpcode() == ISD::FNEG) {
7758         SDValue N000 = N00.getOperand(0);
7759         if (N000.getOpcode() == ISD::FMUL) {
7760           return DAG.getNode(ISD::FNEG, SL, VT,
7761                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7762                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7763                                                      N000.getOperand(0)),
7764                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7765                                                      N000.getOperand(1)),
7766                                          N1));
7767         }
7768       }
7769     }
7770
7771     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7772     //   -> (fneg (fma (fpext x)), (fpext y), z)
7773     // Note: This could be removed with appropriate canonicalization of the
7774     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7775     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7776     // from implementing the canonicalization in visitFSUB.
7777     if (N0.getOpcode() == ISD::FNEG) {
7778       SDValue N00 = N0.getOperand(0);
7779       if (N00.getOpcode() == ISD::FP_EXTEND) {
7780         SDValue N000 = N00.getOperand(0);
7781         if (N000.getOpcode() == ISD::FMUL) {
7782           return DAG.getNode(ISD::FNEG, SL, VT,
7783                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7784                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7785                                                      N000.getOperand(0)),
7786                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7787                                                      N000.getOperand(1)),
7788                                          N1));
7789         }
7790       }
7791     }
7792
7793   }
7794
7795   // More folding opportunities when target permits.
7796   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7797     // fold (fsub (fma x, y, (fmul u, v)), z)
7798     //   -> (fma x, y (fma u, v, (fneg z)))
7799     if (N0.getOpcode() == PreferredFusedOpcode &&
7800         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7801       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7802                          N0.getOperand(0), N0.getOperand(1),
7803                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7804                                      N0.getOperand(2).getOperand(0),
7805                                      N0.getOperand(2).getOperand(1),
7806                                      DAG.getNode(ISD::FNEG, SL, VT,
7807                                                  N1)));
7808     }
7809
7810     // fold (fsub x, (fma y, z, (fmul u, v)))
7811     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7812     if (N1.getOpcode() == PreferredFusedOpcode &&
7813         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7814       SDValue N20 = N1.getOperand(2).getOperand(0);
7815       SDValue N21 = N1.getOperand(2).getOperand(1);
7816       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7817                          DAG.getNode(ISD::FNEG, SL, VT,
7818                                      N1.getOperand(0)),
7819                          N1.getOperand(1),
7820                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7821                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7822
7823                                      N21, N0));
7824     }
7825
7826     if (UnsafeFPMath && LookThroughFPExt) {
7827       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7828       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7829       if (N0.getOpcode() == PreferredFusedOpcode) {
7830         SDValue N02 = N0.getOperand(2);
7831         if (N02.getOpcode() == ISD::FP_EXTEND) {
7832           SDValue N020 = N02.getOperand(0);
7833           if (N020.getOpcode() == ISD::FMUL)
7834             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7835                                N0.getOperand(0), N0.getOperand(1),
7836                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7837                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7838                                                        N020.getOperand(0)),
7839                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7840                                                        N020.getOperand(1)),
7841                                            DAG.getNode(ISD::FNEG, SL, VT,
7842                                                        N1)));
7843         }
7844       }
7845
7846       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7847       //   -> (fma (fpext x), (fpext y),
7848       //           (fma (fpext u), (fpext v), (fneg z)))
7849       // FIXME: This turns two single-precision and one double-precision
7850       // operation into two double-precision operations, which might not be
7851       // interesting for all targets, especially GPUs.
7852       if (N0.getOpcode() == ISD::FP_EXTEND) {
7853         SDValue N00 = N0.getOperand(0);
7854         if (N00.getOpcode() == PreferredFusedOpcode) {
7855           SDValue N002 = N00.getOperand(2);
7856           if (N002.getOpcode() == ISD::FMUL)
7857             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7858                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7859                                            N00.getOperand(0)),
7860                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7861                                            N00.getOperand(1)),
7862                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7863                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7864                                                        N002.getOperand(0)),
7865                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7866                                                        N002.getOperand(1)),
7867                                            DAG.getNode(ISD::FNEG, SL, VT,
7868                                                        N1)));
7869         }
7870       }
7871
7872       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7873       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7874       if (N1.getOpcode() == PreferredFusedOpcode &&
7875         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7876         SDValue N120 = N1.getOperand(2).getOperand(0);
7877         if (N120.getOpcode() == ISD::FMUL) {
7878           SDValue N1200 = N120.getOperand(0);
7879           SDValue N1201 = N120.getOperand(1);
7880           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7881                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7882                              N1.getOperand(1),
7883                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7884                                          DAG.getNode(ISD::FNEG, SL, VT,
7885                                              DAG.getNode(ISD::FP_EXTEND, SL,
7886                                                          VT, N1200)),
7887                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7888                                                      N1201),
7889                                          N0));
7890         }
7891       }
7892
7893       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7894       //   -> (fma (fneg (fpext y)), (fpext z),
7895       //           (fma (fneg (fpext u)), (fpext v), x))
7896       // FIXME: This turns two single-precision and one double-precision
7897       // operation into two double-precision operations, which might not be
7898       // interesting for all targets, especially GPUs.
7899       if (N1.getOpcode() == ISD::FP_EXTEND &&
7900         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7901         SDValue N100 = N1.getOperand(0).getOperand(0);
7902         SDValue N101 = N1.getOperand(0).getOperand(1);
7903         SDValue N102 = N1.getOperand(0).getOperand(2);
7904         if (N102.getOpcode() == ISD::FMUL) {
7905           SDValue N1020 = N102.getOperand(0);
7906           SDValue N1021 = N102.getOperand(1);
7907           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7908                              DAG.getNode(ISD::FNEG, SL, VT,
7909                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7910                                                      N100)),
7911                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7912                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7913                                          DAG.getNode(ISD::FNEG, SL, VT,
7914                                              DAG.getNode(ISD::FP_EXTEND, SL,
7915                                                          VT, N1020)),
7916                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7917                                                      N1021),
7918                                          N0));
7919         }
7920       }
7921     }
7922   }
7923
7924   return SDValue();
7925 }
7926
7927 SDValue DAGCombiner::visitFADD(SDNode *N) {
7928   SDValue N0 = N->getOperand(0);
7929   SDValue N1 = N->getOperand(1);
7930   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7931   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7932   EVT VT = N->getValueType(0);
7933   SDLoc DL(N);
7934   const TargetOptions &Options = DAG.getTarget().Options;
7935   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
7936
7937   // fold vector ops
7938   if (VT.isVector())
7939     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7940       return FoldedVOp;
7941
7942   // fold (fadd c1, c2) -> c1 + c2
7943   if (N0CFP && N1CFP)
7944     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
7945
7946   // canonicalize constant to RHS
7947   if (N0CFP && !N1CFP)
7948     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
7949
7950   // fold (fadd A, (fneg B)) -> (fsub A, B)
7951   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7952       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7953     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7954                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
7955
7956   // fold (fadd (fneg A), B) -> (fsub B, A)
7957   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7958       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7959     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7960                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
7961
7962   // If 'unsafe math' is enabled, fold lots of things.
7963   if (Options.UnsafeFPMath) {
7964     // No FP constant should be created after legalization as Instruction
7965     // Selection pass has a hard time dealing with FP constants.
7966     bool AllowNewConst = (Level < AfterLegalizeDAG);
7967
7968     // fold (fadd A, 0) -> A
7969     if (N1CFP && N1CFP->isZero())
7970       return N0;
7971
7972     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7973     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7974         isa<ConstantFPSDNode>(N0.getOperand(1)))
7975       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7976                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
7977                                      Flags),
7978                          Flags);
7979
7980     // If allowed, fold (fadd (fneg x), x) -> 0.0
7981     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7982       return DAG.getConstantFP(0.0, DL, VT);
7983
7984     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7985     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7986       return DAG.getConstantFP(0.0, DL, VT);
7987
7988     // We can fold chains of FADD's of the same value into multiplications.
7989     // This transform is not safe in general because we are reducing the number
7990     // of rounding steps.
7991     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7992       if (N0.getOpcode() == ISD::FMUL) {
7993         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7994         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7995
7996         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7997         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7998           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7999                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8000           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8001         }
8002
8003         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8004         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8005             N1.getOperand(0) == N1.getOperand(1) &&
8006             N0.getOperand(0) == N1.getOperand(0)) {
8007           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
8008                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8009           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8010         }
8011       }
8012
8013       if (N1.getOpcode() == ISD::FMUL) {
8014         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8015         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
8016
8017         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8018         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8019           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8020                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8021           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8022         }
8023
8024         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8025         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8026             N0.getOperand(0) == N0.getOperand(1) &&
8027             N1.getOperand(0) == N0.getOperand(0)) {
8028           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8029                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8030           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8031         }
8032       }
8033
8034       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8035         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8036         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8037         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
8038             (N0.getOperand(0) == N1)) {
8039           return DAG.getNode(ISD::FMUL, DL, VT,
8040                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8041         }
8042       }
8043
8044       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8045         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8046         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8047         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8048             N1.getOperand(0) == N0) {
8049           return DAG.getNode(ISD::FMUL, DL, VT,
8050                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8051         }
8052       }
8053
8054       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8055       if (AllowNewConst &&
8056           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8057           N0.getOperand(0) == N0.getOperand(1) &&
8058           N1.getOperand(0) == N1.getOperand(1) &&
8059           N0.getOperand(0) == N1.getOperand(0)) {
8060         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8061                            DAG.getConstantFP(4.0, DL, VT), Flags);
8062       }
8063     }
8064   } // enable-unsafe-fp-math
8065
8066   // FADD -> FMA combines:
8067   if (SDValue Fused = visitFADDForFMACombine(N)) {
8068     AddToWorklist(Fused.getNode());
8069     return Fused;
8070   }
8071
8072   return SDValue();
8073 }
8074
8075 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8076   SDValue N0 = N->getOperand(0);
8077   SDValue N1 = N->getOperand(1);
8078   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8079   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8080   EVT VT = N->getValueType(0);
8081   SDLoc dl(N);
8082   const TargetOptions &Options = DAG.getTarget().Options;
8083   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8084
8085   // fold vector ops
8086   if (VT.isVector())
8087     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8088       return FoldedVOp;
8089
8090   // fold (fsub c1, c2) -> c1-c2
8091   if (N0CFP && N1CFP)
8092     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8093
8094   // fold (fsub A, (fneg B)) -> (fadd A, B)
8095   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8096     return DAG.getNode(ISD::FADD, dl, VT, N0,
8097                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8098
8099   // If 'unsafe math' is enabled, fold lots of things.
8100   if (Options.UnsafeFPMath) {
8101     // (fsub A, 0) -> A
8102     if (N1CFP && N1CFP->isZero())
8103       return N0;
8104
8105     // (fsub 0, B) -> -B
8106     if (N0CFP && N0CFP->isZero()) {
8107       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8108         return GetNegatedExpression(N1, DAG, LegalOperations);
8109       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8110         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8111     }
8112
8113     // (fsub x, x) -> 0.0
8114     if (N0 == N1)
8115       return DAG.getConstantFP(0.0f, dl, VT);
8116
8117     // (fsub x, (fadd x, y)) -> (fneg y)
8118     // (fsub x, (fadd y, x)) -> (fneg y)
8119     if (N1.getOpcode() == ISD::FADD) {
8120       SDValue N10 = N1->getOperand(0);
8121       SDValue N11 = N1->getOperand(1);
8122
8123       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8124         return GetNegatedExpression(N11, DAG, LegalOperations);
8125
8126       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8127         return GetNegatedExpression(N10, DAG, LegalOperations);
8128     }
8129   }
8130
8131   // FSUB -> FMA combines:
8132   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8133     AddToWorklist(Fused.getNode());
8134     return Fused;
8135   }
8136
8137   return SDValue();
8138 }
8139
8140 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8141   SDValue N0 = N->getOperand(0);
8142   SDValue N1 = N->getOperand(1);
8143   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8144   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8145   EVT VT = N->getValueType(0);
8146   SDLoc DL(N);
8147   const TargetOptions &Options = DAG.getTarget().Options;
8148   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8149
8150   // fold vector ops
8151   if (VT.isVector()) {
8152     // This just handles C1 * C2 for vectors. Other vector folds are below.
8153     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8154       return FoldedVOp;
8155   }
8156
8157   // fold (fmul c1, c2) -> c1*c2
8158   if (N0CFP && N1CFP)
8159     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8160
8161   // canonicalize constant to RHS
8162   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8163      !isConstantFPBuildVectorOrConstantFP(N1))
8164     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8165
8166   // fold (fmul A, 1.0) -> A
8167   if (N1CFP && N1CFP->isExactlyValue(1.0))
8168     return N0;
8169
8170   if (Options.UnsafeFPMath) {
8171     // fold (fmul A, 0) -> 0
8172     if (N1CFP && N1CFP->isZero())
8173       return N1;
8174
8175     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8176     if (N0.getOpcode() == ISD::FMUL) {
8177       // Fold scalars or any vector constants (not just splats).
8178       // This fold is done in general by InstCombine, but extra fmul insts
8179       // may have been generated during lowering.
8180       SDValue N00 = N0.getOperand(0);
8181       SDValue N01 = N0.getOperand(1);
8182       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8183       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8184       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8185
8186       // Check 1: Make sure that the first operand of the inner multiply is NOT
8187       // a constant. Otherwise, we may induce infinite looping.
8188       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8189         // Check 2: Make sure that the second operand of the inner multiply and
8190         // the second operand of the outer multiply are constants.
8191         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8192             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8193           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8194           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8195         }
8196       }
8197     }
8198
8199     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8200     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8201     // during an early run of DAGCombiner can prevent folding with fmuls
8202     // inserted during lowering.
8203     if (N0.getOpcode() == ISD::FADD &&
8204         (N0.getOperand(0) == N0.getOperand(1)) &&
8205         N0.hasOneUse()) {
8206       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8207       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8208       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8209     }
8210   }
8211
8212   // fold (fmul X, 2.0) -> (fadd X, X)
8213   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8214     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8215
8216   // fold (fmul X, -1.0) -> (fneg X)
8217   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8218     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8219       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8220
8221   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8222   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8223     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8224       // Both can be negated for free, check to see if at least one is cheaper
8225       // negated.
8226       if (LHSNeg == 2 || RHSNeg == 2)
8227         return DAG.getNode(ISD::FMUL, DL, VT,
8228                            GetNegatedExpression(N0, DAG, LegalOperations),
8229                            GetNegatedExpression(N1, DAG, LegalOperations),
8230                            Flags);
8231     }
8232   }
8233
8234   return SDValue();
8235 }
8236
8237 SDValue DAGCombiner::visitFMA(SDNode *N) {
8238   SDValue N0 = N->getOperand(0);
8239   SDValue N1 = N->getOperand(1);
8240   SDValue N2 = N->getOperand(2);
8241   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8242   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8243   EVT VT = N->getValueType(0);
8244   SDLoc dl(N);
8245   const TargetOptions &Options = DAG.getTarget().Options;
8246
8247   // Constant fold FMA.
8248   if (isa<ConstantFPSDNode>(N0) &&
8249       isa<ConstantFPSDNode>(N1) &&
8250       isa<ConstantFPSDNode>(N2)) {
8251     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8252   }
8253
8254   if (Options.UnsafeFPMath) {
8255     if (N0CFP && N0CFP->isZero())
8256       return N2;
8257     if (N1CFP && N1CFP->isZero())
8258       return N2;
8259   }
8260   // TODO: The FMA node should have flags that propagate to these nodes.
8261   if (N0CFP && N0CFP->isExactlyValue(1.0))
8262     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8263   if (N1CFP && N1CFP->isExactlyValue(1.0))
8264     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8265
8266   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8267   if (N0CFP && !N1CFP)
8268     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8269
8270   // TODO: FMA nodes should have flags that propagate to the created nodes.
8271   // For now, create a Flags object for use with all unsafe math transforms.
8272   SDNodeFlags Flags;
8273   Flags.setUnsafeAlgebra(true);
8274
8275   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8276   if (Options.UnsafeFPMath && N1CFP &&
8277       N2.getOpcode() == ISD::FMUL &&
8278       N0 == N2.getOperand(0) &&
8279       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8280     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8281                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8282                                    &Flags), &Flags);
8283   }
8284
8285
8286   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8287   if (Options.UnsafeFPMath &&
8288       N0.getOpcode() == ISD::FMUL && N1CFP &&
8289       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8290     return DAG.getNode(ISD::FMA, dl, VT,
8291                        N0.getOperand(0),
8292                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8293                                    &Flags),
8294                        N2);
8295   }
8296
8297   // (fma x, 1, y) -> (fadd x, y)
8298   // (fma x, -1, y) -> (fadd (fneg x), y)
8299   if (N1CFP) {
8300     if (N1CFP->isExactlyValue(1.0))
8301       // TODO: The FMA node should have flags that propagate to this node.
8302       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8303
8304     if (N1CFP->isExactlyValue(-1.0) &&
8305         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8306       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8307       AddToWorklist(RHSNeg.getNode());
8308       // TODO: The FMA node should have flags that propagate to this node.
8309       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8310     }
8311   }
8312
8313   // (fma x, c, x) -> (fmul x, (c+1))
8314   if (Options.UnsafeFPMath && N1CFP && N0 == N2) {
8315     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8316                        DAG.getNode(ISD::FADD, dl, VT,
8317                                    N1, DAG.getConstantFP(1.0, dl, VT),
8318                                    &Flags), &Flags);
8319   }
8320   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8321   if (Options.UnsafeFPMath && N1CFP &&
8322       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8323     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8324                        DAG.getNode(ISD::FADD, dl, VT,
8325                                    N1, DAG.getConstantFP(-1.0, dl, VT),
8326                                    &Flags), &Flags);
8327   }
8328
8329   return SDValue();
8330 }
8331
8332 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8333 // reciprocal.
8334 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8335 // Notice that this is not always beneficial. One reason is different target
8336 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8337 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8338 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8339 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8340   if (!DAG.getTarget().Options.UnsafeFPMath)
8341     return SDValue();
8342
8343   // Skip if current node is a reciprocal.
8344   SDValue N0 = N->getOperand(0);
8345   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8346   if (N0CFP && N0CFP->isExactlyValue(1.0))
8347     return SDValue();
8348
8349   // Exit early if the target does not want this transform or if there can't
8350   // possibly be enough uses of the divisor to make the transform worthwhile.
8351   SDValue N1 = N->getOperand(1);
8352   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8353   if (!MinUses || N1->use_size() < MinUses)
8354     return SDValue();
8355
8356   // Find all FDIV users of the same divisor.
8357   // Use a set because duplicates may be present in the user list.
8358   SetVector<SDNode *> Users;
8359   for (auto *U : N1->uses())
8360     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8361       Users.insert(U);
8362
8363   // Now that we have the actual number of divisor uses, make sure it meets
8364   // the minimum threshold specified by the target.
8365   if (Users.size() < MinUses)
8366     return SDValue();
8367
8368   EVT VT = N->getValueType(0);
8369   SDLoc DL(N);
8370   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8371   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8372   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8373
8374   // Dividend / Divisor -> Dividend * Reciprocal
8375   for (auto *U : Users) {
8376     SDValue Dividend = U->getOperand(0);
8377     if (Dividend != FPOne) {
8378       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8379                                     Reciprocal, Flags);
8380       CombineTo(U, NewNode);
8381     } else if (U != Reciprocal.getNode()) {
8382       // In the absence of fast-math-flags, this user node is always the
8383       // same node as Reciprocal, but with FMF they may be different nodes.
8384       CombineTo(U, Reciprocal);
8385     }
8386   }
8387   return SDValue(N, 0);  // N was replaced.
8388 }
8389
8390 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8391   SDValue N0 = N->getOperand(0);
8392   SDValue N1 = N->getOperand(1);
8393   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8394   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8395   EVT VT = N->getValueType(0);
8396   SDLoc DL(N);
8397   const TargetOptions &Options = DAG.getTarget().Options;
8398   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8399
8400   // fold vector ops
8401   if (VT.isVector())
8402     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8403       return FoldedVOp;
8404
8405   // fold (fdiv c1, c2) -> c1/c2
8406   if (N0CFP && N1CFP)
8407     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8408
8409   if (Options.UnsafeFPMath) {
8410     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8411     if (N1CFP) {
8412       // Compute the reciprocal 1.0 / c2.
8413       APFloat N1APF = N1CFP->getValueAPF();
8414       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8415       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8416       // Only do the transform if the reciprocal is a legal fp immediate that
8417       // isn't too nasty (eg NaN, denormal, ...).
8418       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8419           (!LegalOperations ||
8420            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8421            // backend)... we should handle this gracefully after Legalize.
8422            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8423            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8424            TLI.isFPImmLegal(Recip, VT)))
8425         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8426                            DAG.getConstantFP(Recip, DL, VT), Flags);
8427     }
8428
8429     // If this FDIV is part of a reciprocal square root, it may be folded
8430     // into a target-specific square root estimate instruction.
8431     if (N1.getOpcode() == ISD::FSQRT) {
8432       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8433         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8434       }
8435     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8436                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8437       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8438                                           Flags)) {
8439         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8440         AddToWorklist(RV.getNode());
8441         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8442       }
8443     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8444                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8445       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8446                                           Flags)) {
8447         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8448         AddToWorklist(RV.getNode());
8449         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8450       }
8451     } else if (N1.getOpcode() == ISD::FMUL) {
8452       // Look through an FMUL. Even though this won't remove the FDIV directly,
8453       // it's still worthwhile to get rid of the FSQRT if possible.
8454       SDValue SqrtOp;
8455       SDValue OtherOp;
8456       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8457         SqrtOp = N1.getOperand(0);
8458         OtherOp = N1.getOperand(1);
8459       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8460         SqrtOp = N1.getOperand(1);
8461         OtherOp = N1.getOperand(0);
8462       }
8463       if (SqrtOp.getNode()) {
8464         // We found a FSQRT, so try to make this fold:
8465         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8466         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8467           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8468           AddToWorklist(RV.getNode());
8469           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8470         }
8471       }
8472     }
8473
8474     // Fold into a reciprocal estimate and multiply instead of a real divide.
8475     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8476       AddToWorklist(RV.getNode());
8477       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8478     }
8479   }
8480
8481   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8482   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8483     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8484       // Both can be negated for free, check to see if at least one is cheaper
8485       // negated.
8486       if (LHSNeg == 2 || RHSNeg == 2)
8487         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8488                            GetNegatedExpression(N0, DAG, LegalOperations),
8489                            GetNegatedExpression(N1, DAG, LegalOperations),
8490                            Flags);
8491     }
8492   }
8493
8494   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8495     return CombineRepeatedDivisors;
8496
8497   return SDValue();
8498 }
8499
8500 SDValue DAGCombiner::visitFREM(SDNode *N) {
8501   SDValue N0 = N->getOperand(0);
8502   SDValue N1 = N->getOperand(1);
8503   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8504   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8505   EVT VT = N->getValueType(0);
8506
8507   // fold (frem c1, c2) -> fmod(c1,c2)
8508   if (N0CFP && N1CFP)
8509     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8510                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8511
8512   return SDValue();
8513 }
8514
8515 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8516   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8517     return SDValue();
8518
8519   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8520   // For now, create a Flags object for use with all unsafe math transforms.
8521   SDNodeFlags Flags;
8522   Flags.setUnsafeAlgebra(true);
8523
8524   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8525   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8526   if (!RV)
8527     return SDValue();
8528
8529   EVT VT = RV.getValueType();
8530   SDLoc DL(N);
8531   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8532   AddToWorklist(RV.getNode());
8533
8534   // Unfortunately, RV is now NaN if the input was exactly 0.
8535   // Select out this case and force the answer to 0.
8536   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8537   EVT CCVT = getSetCCResultType(VT);
8538   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8539   AddToWorklist(ZeroCmp.getNode());
8540   AddToWorklist(RV.getNode());
8541
8542   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8543                      ZeroCmp, Zero, RV);
8544 }
8545
8546 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8547   SDValue N0 = N->getOperand(0);
8548   SDValue N1 = N->getOperand(1);
8549   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8550   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8551   EVT VT = N->getValueType(0);
8552
8553   if (N0CFP && N1CFP)  // Constant fold
8554     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8555
8556   if (N1CFP) {
8557     const APFloat& V = N1CFP->getValueAPF();
8558     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8559     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8560     if (!V.isNegative()) {
8561       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8562         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8563     } else {
8564       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8565         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8566                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8567     }
8568   }
8569
8570   // copysign(fabs(x), y) -> copysign(x, y)
8571   // copysign(fneg(x), y) -> copysign(x, y)
8572   // copysign(copysign(x,z), y) -> copysign(x, y)
8573   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8574       N0.getOpcode() == ISD::FCOPYSIGN)
8575     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8576                        N0.getOperand(0), N1);
8577
8578   // copysign(x, abs(y)) -> abs(x)
8579   if (N1.getOpcode() == ISD::FABS)
8580     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8581
8582   // copysign(x, copysign(y,z)) -> copysign(x, z)
8583   if (N1.getOpcode() == ISD::FCOPYSIGN)
8584     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8585                        N0, N1.getOperand(1));
8586
8587   // copysign(x, fp_extend(y)) -> copysign(x, y)
8588   // copysign(x, fp_round(y)) -> copysign(x, y)
8589   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8590     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8591                        N0, N1.getOperand(0));
8592
8593   return SDValue();
8594 }
8595
8596 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8597   SDValue N0 = N->getOperand(0);
8598   EVT VT = N->getValueType(0);
8599   EVT OpVT = N0.getValueType();
8600
8601   // fold (sint_to_fp c1) -> c1fp
8602   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8603       // ...but only if the target supports immediate floating-point values
8604       (!LegalOperations ||
8605        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8606     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8607
8608   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8609   // but UINT_TO_FP is legal on this target, try to convert.
8610   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8611       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8612     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8613     if (DAG.SignBitIsZero(N0))
8614       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8615   }
8616
8617   // The next optimizations are desirable only if SELECT_CC can be lowered.
8618   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8619     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8620     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8621         !VT.isVector() &&
8622         (!LegalOperations ||
8623          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8624       SDLoc DL(N);
8625       SDValue Ops[] =
8626         { N0.getOperand(0), N0.getOperand(1),
8627           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8628           N0.getOperand(2) };
8629       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8630     }
8631
8632     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8633     //      (select_cc x, y, 1.0, 0.0,, cc)
8634     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8635         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8636         (!LegalOperations ||
8637          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8638       SDLoc DL(N);
8639       SDValue Ops[] =
8640         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8641           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8642           N0.getOperand(0).getOperand(2) };
8643       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8644     }
8645   }
8646
8647   return SDValue();
8648 }
8649
8650 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8651   SDValue N0 = N->getOperand(0);
8652   EVT VT = N->getValueType(0);
8653   EVT OpVT = N0.getValueType();
8654
8655   // fold (uint_to_fp c1) -> c1fp
8656   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8657       // ...but only if the target supports immediate floating-point values
8658       (!LegalOperations ||
8659        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8660     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8661
8662   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8663   // but SINT_TO_FP is legal on this target, try to convert.
8664   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8665       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8666     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8667     if (DAG.SignBitIsZero(N0))
8668       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8669   }
8670
8671   // The next optimizations are desirable only if SELECT_CC can be lowered.
8672   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8673     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8674
8675     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8676         (!LegalOperations ||
8677          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8678       SDLoc DL(N);
8679       SDValue Ops[] =
8680         { N0.getOperand(0), N0.getOperand(1),
8681           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8682           N0.getOperand(2) };
8683       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8684     }
8685   }
8686
8687   return SDValue();
8688 }
8689
8690 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8691 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8692   SDValue N0 = N->getOperand(0);
8693   EVT VT = N->getValueType(0);
8694
8695   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8696     return SDValue();
8697
8698   SDValue Src = N0.getOperand(0);
8699   EVT SrcVT = Src.getValueType();
8700   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8701   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8702
8703   // We can safely assume the conversion won't overflow the output range,
8704   // because (for example) (uint8_t)18293.f is undefined behavior.
8705
8706   // Since we can assume the conversion won't overflow, our decision as to
8707   // whether the input will fit in the float should depend on the minimum
8708   // of the input range and output range.
8709
8710   // This means this is also safe for a signed input and unsigned output, since
8711   // a negative input would lead to undefined behavior.
8712   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8713   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8714   unsigned ActualSize = std::min(InputSize, OutputSize);
8715   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8716
8717   // We can only fold away the float conversion if the input range can be
8718   // represented exactly in the float range.
8719   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8720     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8721       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8722                                                        : ISD::ZERO_EXTEND;
8723       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8724     }
8725     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8726       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8727     if (SrcVT == VT)
8728       return Src;
8729     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8730   }
8731   return SDValue();
8732 }
8733
8734 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8735   SDValue N0 = N->getOperand(0);
8736   EVT VT = N->getValueType(0);
8737
8738   // fold (fp_to_sint c1fp) -> c1
8739   if (isConstantFPBuildVectorOrConstantFP(N0))
8740     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8741
8742   return FoldIntToFPToInt(N, DAG);
8743 }
8744
8745 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8746   SDValue N0 = N->getOperand(0);
8747   EVT VT = N->getValueType(0);
8748
8749   // fold (fp_to_uint c1fp) -> c1
8750   if (isConstantFPBuildVectorOrConstantFP(N0))
8751     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8752
8753   return FoldIntToFPToInt(N, DAG);
8754 }
8755
8756 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8757   SDValue N0 = N->getOperand(0);
8758   SDValue N1 = N->getOperand(1);
8759   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8760   EVT VT = N->getValueType(0);
8761
8762   // fold (fp_round c1fp) -> c1fp
8763   if (N0CFP)
8764     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8765
8766   // fold (fp_round (fp_extend x)) -> x
8767   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8768     return N0.getOperand(0);
8769
8770   // fold (fp_round (fp_round x)) -> (fp_round x)
8771   if (N0.getOpcode() == ISD::FP_ROUND) {
8772     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8773     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8774     // If the first fp_round isn't a value preserving truncation, it might
8775     // introduce a tie in the second fp_round, that wouldn't occur in the
8776     // single-step fp_round we want to fold to.
8777     // In other words, double rounding isn't the same as rounding.
8778     // Also, this is a value preserving truncation iff both fp_round's are.
8779     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8780       SDLoc DL(N);
8781       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8782                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8783     }
8784   }
8785
8786   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8787   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8788     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8789                               N0.getOperand(0), N1);
8790     AddToWorklist(Tmp.getNode());
8791     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8792                        Tmp, N0.getOperand(1));
8793   }
8794
8795   return SDValue();
8796 }
8797
8798 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8799   SDValue N0 = N->getOperand(0);
8800   EVT VT = N->getValueType(0);
8801   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8802   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8803
8804   // fold (fp_round_inreg c1fp) -> c1fp
8805   if (N0CFP && isTypeLegal(EVT)) {
8806     SDLoc DL(N);
8807     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8808     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8809   }
8810
8811   return SDValue();
8812 }
8813
8814 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8815   SDValue N0 = N->getOperand(0);
8816   EVT VT = N->getValueType(0);
8817
8818   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8819   if (N->hasOneUse() &&
8820       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8821     return SDValue();
8822
8823   // fold (fp_extend c1fp) -> c1fp
8824   if (isConstantFPBuildVectorOrConstantFP(N0))
8825     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8826
8827   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8828   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8829       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8830     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8831
8832   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8833   // value of X.
8834   if (N0.getOpcode() == ISD::FP_ROUND
8835       && N0.getNode()->getConstantOperandVal(1) == 1) {
8836     SDValue In = N0.getOperand(0);
8837     if (In.getValueType() == VT) return In;
8838     if (VT.bitsLT(In.getValueType()))
8839       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8840                          In, N0.getOperand(1));
8841     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8842   }
8843
8844   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8845   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8846        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8847     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8848     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8849                                      LN0->getChain(),
8850                                      LN0->getBasePtr(), N0.getValueType(),
8851                                      LN0->getMemOperand());
8852     CombineTo(N, ExtLoad);
8853     CombineTo(N0.getNode(),
8854               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8855                           N0.getValueType(), ExtLoad,
8856                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8857               ExtLoad.getValue(1));
8858     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8859   }
8860
8861   return SDValue();
8862 }
8863
8864 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8865   SDValue N0 = N->getOperand(0);
8866   EVT VT = N->getValueType(0);
8867
8868   // fold (fceil c1) -> fceil(c1)
8869   if (isConstantFPBuildVectorOrConstantFP(N0))
8870     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8871
8872   return SDValue();
8873 }
8874
8875 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8876   SDValue N0 = N->getOperand(0);
8877   EVT VT = N->getValueType(0);
8878
8879   // fold (ftrunc c1) -> ftrunc(c1)
8880   if (isConstantFPBuildVectorOrConstantFP(N0))
8881     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8882
8883   return SDValue();
8884 }
8885
8886 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8887   SDValue N0 = N->getOperand(0);
8888   EVT VT = N->getValueType(0);
8889
8890   // fold (ffloor c1) -> ffloor(c1)
8891   if (isConstantFPBuildVectorOrConstantFP(N0))
8892     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8893
8894   return SDValue();
8895 }
8896
8897 // FIXME: FNEG and FABS have a lot in common; refactor.
8898 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8899   SDValue N0 = N->getOperand(0);
8900   EVT VT = N->getValueType(0);
8901
8902   // Constant fold FNEG.
8903   if (isConstantFPBuildVectorOrConstantFP(N0))
8904     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8905
8906   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8907                          &DAG.getTarget().Options))
8908     return GetNegatedExpression(N0, DAG, LegalOperations);
8909
8910   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8911   // constant pool values.
8912   if (!TLI.isFNegFree(VT) &&
8913       N0.getOpcode() == ISD::BITCAST &&
8914       N0.getNode()->hasOneUse()) {
8915     SDValue Int = N0.getOperand(0);
8916     EVT IntVT = Int.getValueType();
8917     if (IntVT.isInteger() && !IntVT.isVector()) {
8918       APInt SignMask;
8919       if (N0.getValueType().isVector()) {
8920         // For a vector, get a mask such as 0x80... per scalar element
8921         // and splat it.
8922         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8923         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8924       } else {
8925         // For a scalar, just generate 0x80...
8926         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8927       }
8928       SDLoc DL0(N0);
8929       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8930                         DAG.getConstant(SignMask, DL0, IntVT));
8931       AddToWorklist(Int.getNode());
8932       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8933     }
8934   }
8935
8936   // (fneg (fmul c, x)) -> (fmul -c, x)
8937   if (N0.getOpcode() == ISD::FMUL &&
8938       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8939     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8940     if (CFP1) {
8941       APFloat CVal = CFP1->getValueAPF();
8942       CVal.changeSign();
8943       if (Level >= AfterLegalizeDAG &&
8944           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8945            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8946         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8947                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8948                                        N0.getOperand(1)),
8949                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
8950     }
8951   }
8952
8953   return SDValue();
8954 }
8955
8956 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8957   SDValue N0 = N->getOperand(0);
8958   SDValue N1 = N->getOperand(1);
8959   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8960   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8961
8962   if (N0CFP && N1CFP) {
8963     const APFloat &C0 = N0CFP->getValueAPF();
8964     const APFloat &C1 = N1CFP->getValueAPF();
8965     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8966   }
8967
8968   if (N0CFP) {
8969     EVT VT = N->getValueType(0);
8970     // Canonicalize to constant on RHS.
8971     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8972   }
8973
8974   return SDValue();
8975 }
8976
8977 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8978   SDValue N0 = N->getOperand(0);
8979   SDValue N1 = N->getOperand(1);
8980   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8981   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8982
8983   if (N0CFP && N1CFP) {
8984     const APFloat &C0 = N0CFP->getValueAPF();
8985     const APFloat &C1 = N1CFP->getValueAPF();
8986     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8987   }
8988
8989   if (N0CFP) {
8990     EVT VT = N->getValueType(0);
8991     // Canonicalize to constant on RHS.
8992     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8993   }
8994
8995   return SDValue();
8996 }
8997
8998 SDValue DAGCombiner::visitFABS(SDNode *N) {
8999   SDValue N0 = N->getOperand(0);
9000   EVT VT = N->getValueType(0);
9001
9002   // fold (fabs c1) -> fabs(c1)
9003   if (isConstantFPBuildVectorOrConstantFP(N0))
9004     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9005
9006   // fold (fabs (fabs x)) -> (fabs x)
9007   if (N0.getOpcode() == ISD::FABS)
9008     return N->getOperand(0);
9009
9010   // fold (fabs (fneg x)) -> (fabs x)
9011   // fold (fabs (fcopysign x, y)) -> (fabs x)
9012   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9013     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9014
9015   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9016   // constant pool values.
9017   if (!TLI.isFAbsFree(VT) &&
9018       N0.getOpcode() == ISD::BITCAST &&
9019       N0.getNode()->hasOneUse()) {
9020     SDValue Int = N0.getOperand(0);
9021     EVT IntVT = Int.getValueType();
9022     if (IntVT.isInteger() && !IntVT.isVector()) {
9023       APInt SignMask;
9024       if (N0.getValueType().isVector()) {
9025         // For a vector, get a mask such as 0x7f... per scalar element
9026         // and splat it.
9027         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9028         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9029       } else {
9030         // For a scalar, just generate 0x7f...
9031         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9032       }
9033       SDLoc DL(N0);
9034       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9035                         DAG.getConstant(SignMask, DL, IntVT));
9036       AddToWorklist(Int.getNode());
9037       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9038     }
9039   }
9040
9041   return SDValue();
9042 }
9043
9044 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9045   SDValue Chain = N->getOperand(0);
9046   SDValue N1 = N->getOperand(1);
9047   SDValue N2 = N->getOperand(2);
9048
9049   // If N is a constant we could fold this into a fallthrough or unconditional
9050   // branch. However that doesn't happen very often in normal code, because
9051   // Instcombine/SimplifyCFG should have handled the available opportunities.
9052   // If we did this folding here, it would be necessary to update the
9053   // MachineBasicBlock CFG, which is awkward.
9054
9055   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9056   // on the target.
9057   if (N1.getOpcode() == ISD::SETCC &&
9058       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9059                                    N1.getOperand(0).getValueType())) {
9060     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9061                        Chain, N1.getOperand(2),
9062                        N1.getOperand(0), N1.getOperand(1), N2);
9063   }
9064
9065   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9066       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9067        (N1.getOperand(0).hasOneUse() &&
9068         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9069     SDNode *Trunc = nullptr;
9070     if (N1.getOpcode() == ISD::TRUNCATE) {
9071       // Look pass the truncate.
9072       Trunc = N1.getNode();
9073       N1 = N1.getOperand(0);
9074     }
9075
9076     // Match this pattern so that we can generate simpler code:
9077     //
9078     //   %a = ...
9079     //   %b = and i32 %a, 2
9080     //   %c = srl i32 %b, 1
9081     //   brcond i32 %c ...
9082     //
9083     // into
9084     //
9085     //   %a = ...
9086     //   %b = and i32 %a, 2
9087     //   %c = setcc eq %b, 0
9088     //   brcond %c ...
9089     //
9090     // This applies only when the AND constant value has one bit set and the
9091     // SRL constant is equal to the log2 of the AND constant. The back-end is
9092     // smart enough to convert the result into a TEST/JMP sequence.
9093     SDValue Op0 = N1.getOperand(0);
9094     SDValue Op1 = N1.getOperand(1);
9095
9096     if (Op0.getOpcode() == ISD::AND &&
9097         Op1.getOpcode() == ISD::Constant) {
9098       SDValue AndOp1 = Op0.getOperand(1);
9099
9100       if (AndOp1.getOpcode() == ISD::Constant) {
9101         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9102
9103         if (AndConst.isPowerOf2() &&
9104             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9105           SDLoc DL(N);
9106           SDValue SetCC =
9107             DAG.getSetCC(DL,
9108                          getSetCCResultType(Op0.getValueType()),
9109                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9110                          ISD::SETNE);
9111
9112           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9113                                           MVT::Other, Chain, SetCC, N2);
9114           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9115           // will convert it back to (X & C1) >> C2.
9116           CombineTo(N, NewBRCond, false);
9117           // Truncate is dead.
9118           if (Trunc)
9119             deleteAndRecombine(Trunc);
9120           // Replace the uses of SRL with SETCC
9121           WorklistRemover DeadNodes(*this);
9122           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9123           deleteAndRecombine(N1.getNode());
9124           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9125         }
9126       }
9127     }
9128
9129     if (Trunc)
9130       // Restore N1 if the above transformation doesn't match.
9131       N1 = N->getOperand(1);
9132   }
9133
9134   // Transform br(xor(x, y)) -> br(x != y)
9135   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9136   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9137     SDNode *TheXor = N1.getNode();
9138     SDValue Op0 = TheXor->getOperand(0);
9139     SDValue Op1 = TheXor->getOperand(1);
9140     if (Op0.getOpcode() == Op1.getOpcode()) {
9141       // Avoid missing important xor optimizations.
9142       if (SDValue Tmp = visitXOR(TheXor)) {
9143         if (Tmp.getNode() != TheXor) {
9144           DEBUG(dbgs() << "\nReplacing.8 ";
9145                 TheXor->dump(&DAG);
9146                 dbgs() << "\nWith: ";
9147                 Tmp.getNode()->dump(&DAG);
9148                 dbgs() << '\n');
9149           WorklistRemover DeadNodes(*this);
9150           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9151           deleteAndRecombine(TheXor);
9152           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9153                              MVT::Other, Chain, Tmp, N2);
9154         }
9155
9156         // visitXOR has changed XOR's operands or replaced the XOR completely,
9157         // bail out.
9158         return SDValue(N, 0);
9159       }
9160     }
9161
9162     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9163       bool Equal = false;
9164       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9165           Op0.getOpcode() == ISD::XOR) {
9166         TheXor = Op0.getNode();
9167         Equal = true;
9168       }
9169
9170       EVT SetCCVT = N1.getValueType();
9171       if (LegalTypes)
9172         SetCCVT = getSetCCResultType(SetCCVT);
9173       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9174                                    SetCCVT,
9175                                    Op0, Op1,
9176                                    Equal ? ISD::SETEQ : ISD::SETNE);
9177       // Replace the uses of XOR with SETCC
9178       WorklistRemover DeadNodes(*this);
9179       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9180       deleteAndRecombine(N1.getNode());
9181       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9182                          MVT::Other, Chain, SetCC, N2);
9183     }
9184   }
9185
9186   return SDValue();
9187 }
9188
9189 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9190 //
9191 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9192   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9193   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9194
9195   // If N is a constant we could fold this into a fallthrough or unconditional
9196   // branch. However that doesn't happen very often in normal code, because
9197   // Instcombine/SimplifyCFG should have handled the available opportunities.
9198   // If we did this folding here, it would be necessary to update the
9199   // MachineBasicBlock CFG, which is awkward.
9200
9201   // Use SimplifySetCC to simplify SETCC's.
9202   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9203                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9204                                false);
9205   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9206
9207   // fold to a simpler setcc
9208   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9209     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9210                        N->getOperand(0), Simp.getOperand(2),
9211                        Simp.getOperand(0), Simp.getOperand(1),
9212                        N->getOperand(4));
9213
9214   return SDValue();
9215 }
9216
9217 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9218 /// and that N may be folded in the load / store addressing mode.
9219 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9220                                     SelectionDAG &DAG,
9221                                     const TargetLowering &TLI) {
9222   EVT VT;
9223   unsigned AS;
9224
9225   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9226     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9227       return false;
9228     VT = LD->getMemoryVT();
9229     AS = LD->getAddressSpace();
9230   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9231     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9232       return false;
9233     VT = ST->getMemoryVT();
9234     AS = ST->getAddressSpace();
9235   } else
9236     return false;
9237
9238   TargetLowering::AddrMode AM;
9239   if (N->getOpcode() == ISD::ADD) {
9240     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9241     if (Offset)
9242       // [reg +/- imm]
9243       AM.BaseOffs = Offset->getSExtValue();
9244     else
9245       // [reg +/- reg]
9246       AM.Scale = 1;
9247   } else if (N->getOpcode() == ISD::SUB) {
9248     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9249     if (Offset)
9250       // [reg +/- imm]
9251       AM.BaseOffs = -Offset->getSExtValue();
9252     else
9253       // [reg +/- reg]
9254       AM.Scale = 1;
9255   } else
9256     return false;
9257
9258   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9259                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9260 }
9261
9262 /// Try turning a load/store into a pre-indexed load/store when the base
9263 /// pointer is an add or subtract and it has other uses besides the load/store.
9264 /// After the transformation, the new indexed load/store has effectively folded
9265 /// the add/subtract in and all of its other uses are redirected to the
9266 /// new load/store.
9267 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9268   if (Level < AfterLegalizeDAG)
9269     return false;
9270
9271   bool isLoad = true;
9272   SDValue Ptr;
9273   EVT VT;
9274   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9275     if (LD->isIndexed())
9276       return false;
9277     VT = LD->getMemoryVT();
9278     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9279         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9280       return false;
9281     Ptr = LD->getBasePtr();
9282   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9283     if (ST->isIndexed())
9284       return false;
9285     VT = ST->getMemoryVT();
9286     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9287         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9288       return false;
9289     Ptr = ST->getBasePtr();
9290     isLoad = false;
9291   } else {
9292     return false;
9293   }
9294
9295   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9296   // out.  There is no reason to make this a preinc/predec.
9297   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9298       Ptr.getNode()->hasOneUse())
9299     return false;
9300
9301   // Ask the target to do addressing mode selection.
9302   SDValue BasePtr;
9303   SDValue Offset;
9304   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9305   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9306     return false;
9307
9308   // Backends without true r+i pre-indexed forms may need to pass a
9309   // constant base with a variable offset so that constant coercion
9310   // will work with the patterns in canonical form.
9311   bool Swapped = false;
9312   if (isa<ConstantSDNode>(BasePtr)) {
9313     std::swap(BasePtr, Offset);
9314     Swapped = true;
9315   }
9316
9317   // Don't create a indexed load / store with zero offset.
9318   if (isNullConstant(Offset))
9319     return false;
9320
9321   // Try turning it into a pre-indexed load / store except when:
9322   // 1) The new base ptr is a frame index.
9323   // 2) If N is a store and the new base ptr is either the same as or is a
9324   //    predecessor of the value being stored.
9325   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9326   //    that would create a cycle.
9327   // 4) All uses are load / store ops that use it as old base ptr.
9328
9329   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9330   // (plus the implicit offset) to a register to preinc anyway.
9331   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9332     return false;
9333
9334   // Check #2.
9335   if (!isLoad) {
9336     SDValue Val = cast<StoreSDNode>(N)->getValue();
9337     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9338       return false;
9339   }
9340
9341   // If the offset is a constant, there may be other adds of constants that
9342   // can be folded with this one. We should do this to avoid having to keep
9343   // a copy of the original base pointer.
9344   SmallVector<SDNode *, 16> OtherUses;
9345   if (isa<ConstantSDNode>(Offset))
9346     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9347                               UE = BasePtr.getNode()->use_end();
9348          UI != UE; ++UI) {
9349       SDUse &Use = UI.getUse();
9350       // Skip the use that is Ptr and uses of other results from BasePtr's
9351       // node (important for nodes that return multiple results).
9352       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9353         continue;
9354
9355       if (Use.getUser()->isPredecessorOf(N))
9356         continue;
9357
9358       if (Use.getUser()->getOpcode() != ISD::ADD &&
9359           Use.getUser()->getOpcode() != ISD::SUB) {
9360         OtherUses.clear();
9361         break;
9362       }
9363
9364       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9365       if (!isa<ConstantSDNode>(Op1)) {
9366         OtherUses.clear();
9367         break;
9368       }
9369
9370       // FIXME: In some cases, we can be smarter about this.
9371       if (Op1.getValueType() != Offset.getValueType()) {
9372         OtherUses.clear();
9373         break;
9374       }
9375
9376       OtherUses.push_back(Use.getUser());
9377     }
9378
9379   if (Swapped)
9380     std::swap(BasePtr, Offset);
9381
9382   // Now check for #3 and #4.
9383   bool RealUse = false;
9384
9385   // Caches for hasPredecessorHelper
9386   SmallPtrSet<const SDNode *, 32> Visited;
9387   SmallVector<const SDNode *, 16> Worklist;
9388
9389   for (SDNode *Use : Ptr.getNode()->uses()) {
9390     if (Use == N)
9391       continue;
9392     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9393       return false;
9394
9395     // If Ptr may be folded in addressing mode of other use, then it's
9396     // not profitable to do this transformation.
9397     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9398       RealUse = true;
9399   }
9400
9401   if (!RealUse)
9402     return false;
9403
9404   SDValue Result;
9405   if (isLoad)
9406     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9407                                 BasePtr, Offset, AM);
9408   else
9409     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9410                                  BasePtr, Offset, AM);
9411   ++PreIndexedNodes;
9412   ++NodesCombined;
9413   DEBUG(dbgs() << "\nReplacing.4 ";
9414         N->dump(&DAG);
9415         dbgs() << "\nWith: ";
9416         Result.getNode()->dump(&DAG);
9417         dbgs() << '\n');
9418   WorklistRemover DeadNodes(*this);
9419   if (isLoad) {
9420     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9421     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9422   } else {
9423     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9424   }
9425
9426   // Finally, since the node is now dead, remove it from the graph.
9427   deleteAndRecombine(N);
9428
9429   if (Swapped)
9430     std::swap(BasePtr, Offset);
9431
9432   // Replace other uses of BasePtr that can be updated to use Ptr
9433   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9434     unsigned OffsetIdx = 1;
9435     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9436       OffsetIdx = 0;
9437     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9438            BasePtr.getNode() && "Expected BasePtr operand");
9439
9440     // We need to replace ptr0 in the following expression:
9441     //   x0 * offset0 + y0 * ptr0 = t0
9442     // knowing that
9443     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9444     //
9445     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9446     // indexed load/store and the expresion that needs to be re-written.
9447     //
9448     // Therefore, we have:
9449     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9450
9451     ConstantSDNode *CN =
9452       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9453     int X0, X1, Y0, Y1;
9454     APInt Offset0 = CN->getAPIntValue();
9455     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9456
9457     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9458     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9459     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9460     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9461
9462     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9463
9464     APInt CNV = Offset0;
9465     if (X0 < 0) CNV = -CNV;
9466     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9467     else CNV = CNV - Offset1;
9468
9469     SDLoc DL(OtherUses[i]);
9470
9471     // We can now generate the new expression.
9472     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9473     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9474
9475     SDValue NewUse = DAG.getNode(Opcode,
9476                                  DL,
9477                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9478     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9479     deleteAndRecombine(OtherUses[i]);
9480   }
9481
9482   // Replace the uses of Ptr with uses of the updated base value.
9483   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9484   deleteAndRecombine(Ptr.getNode());
9485
9486   return true;
9487 }
9488
9489 /// Try to combine a load/store with a add/sub of the base pointer node into a
9490 /// post-indexed load/store. The transformation folded the add/subtract into the
9491 /// new indexed load/store effectively and all of its uses are redirected to the
9492 /// new load/store.
9493 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9494   if (Level < AfterLegalizeDAG)
9495     return false;
9496
9497   bool isLoad = true;
9498   SDValue Ptr;
9499   EVT VT;
9500   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9501     if (LD->isIndexed())
9502       return false;
9503     VT = LD->getMemoryVT();
9504     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9505         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9506       return false;
9507     Ptr = LD->getBasePtr();
9508   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9509     if (ST->isIndexed())
9510       return false;
9511     VT = ST->getMemoryVT();
9512     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9513         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9514       return false;
9515     Ptr = ST->getBasePtr();
9516     isLoad = false;
9517   } else {
9518     return false;
9519   }
9520
9521   if (Ptr.getNode()->hasOneUse())
9522     return false;
9523
9524   for (SDNode *Op : Ptr.getNode()->uses()) {
9525     if (Op == N ||
9526         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9527       continue;
9528
9529     SDValue BasePtr;
9530     SDValue Offset;
9531     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9532     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9533       // Don't create a indexed load / store with zero offset.
9534       if (isNullConstant(Offset))
9535         continue;
9536
9537       // Try turning it into a post-indexed load / store except when
9538       // 1) All uses are load / store ops that use it as base ptr (and
9539       //    it may be folded as addressing mmode).
9540       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9541       //    nor a successor of N. Otherwise, if Op is folded that would
9542       //    create a cycle.
9543
9544       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9545         continue;
9546
9547       // Check for #1.
9548       bool TryNext = false;
9549       for (SDNode *Use : BasePtr.getNode()->uses()) {
9550         if (Use == Ptr.getNode())
9551           continue;
9552
9553         // If all the uses are load / store addresses, then don't do the
9554         // transformation.
9555         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9556           bool RealUse = false;
9557           for (SDNode *UseUse : Use->uses()) {
9558             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9559               RealUse = true;
9560           }
9561
9562           if (!RealUse) {
9563             TryNext = true;
9564             break;
9565           }
9566         }
9567       }
9568
9569       if (TryNext)
9570         continue;
9571
9572       // Check for #2
9573       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9574         SDValue Result = isLoad
9575           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9576                                BasePtr, Offset, AM)
9577           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9578                                 BasePtr, Offset, AM);
9579         ++PostIndexedNodes;
9580         ++NodesCombined;
9581         DEBUG(dbgs() << "\nReplacing.5 ";
9582               N->dump(&DAG);
9583               dbgs() << "\nWith: ";
9584               Result.getNode()->dump(&DAG);
9585               dbgs() << '\n');
9586         WorklistRemover DeadNodes(*this);
9587         if (isLoad) {
9588           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9589           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9590         } else {
9591           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9592         }
9593
9594         // Finally, since the node is now dead, remove it from the graph.
9595         deleteAndRecombine(N);
9596
9597         // Replace the uses of Use with uses of the updated base value.
9598         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9599                                       Result.getValue(isLoad ? 1 : 0));
9600         deleteAndRecombine(Op);
9601         return true;
9602       }
9603     }
9604   }
9605
9606   return false;
9607 }
9608
9609 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9610 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9611   ISD::MemIndexedMode AM = LD->getAddressingMode();
9612   assert(AM != ISD::UNINDEXED);
9613   SDValue BP = LD->getOperand(1);
9614   SDValue Inc = LD->getOperand(2);
9615
9616   // Some backends use TargetConstants for load offsets, but don't expect
9617   // TargetConstants in general ADD nodes. We can convert these constants into
9618   // regular Constants (if the constant is not opaque).
9619   assert((Inc.getOpcode() != ISD::TargetConstant ||
9620           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9621          "Cannot split out indexing using opaque target constants");
9622   if (Inc.getOpcode() == ISD::TargetConstant) {
9623     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9624     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9625                           ConstInc->getValueType(0));
9626   }
9627
9628   unsigned Opc =
9629       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9630   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9631 }
9632
9633 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9634   LoadSDNode *LD  = cast<LoadSDNode>(N);
9635   SDValue Chain = LD->getChain();
9636   SDValue Ptr   = LD->getBasePtr();
9637
9638   // If load is not volatile and there are no uses of the loaded value (and
9639   // the updated indexed value in case of indexed loads), change uses of the
9640   // chain value into uses of the chain input (i.e. delete the dead load).
9641   if (!LD->isVolatile()) {
9642     if (N->getValueType(1) == MVT::Other) {
9643       // Unindexed loads.
9644       if (!N->hasAnyUseOfValue(0)) {
9645         // It's not safe to use the two value CombineTo variant here. e.g.
9646         // v1, chain2 = load chain1, loc
9647         // v2, chain3 = load chain2, loc
9648         // v3         = add v2, c
9649         // Now we replace use of chain2 with chain1.  This makes the second load
9650         // isomorphic to the one we are deleting, and thus makes this load live.
9651         DEBUG(dbgs() << "\nReplacing.6 ";
9652               N->dump(&DAG);
9653               dbgs() << "\nWith chain: ";
9654               Chain.getNode()->dump(&DAG);
9655               dbgs() << "\n");
9656         WorklistRemover DeadNodes(*this);
9657         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9658
9659         if (N->use_empty())
9660           deleteAndRecombine(N);
9661
9662         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9663       }
9664     } else {
9665       // Indexed loads.
9666       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9667
9668       // If this load has an opaque TargetConstant offset, then we cannot split
9669       // the indexing into an add/sub directly (that TargetConstant may not be
9670       // valid for a different type of node, and we cannot convert an opaque
9671       // target constant into a regular constant).
9672       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9673                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9674
9675       if (!N->hasAnyUseOfValue(0) &&
9676           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9677         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9678         SDValue Index;
9679         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9680           Index = SplitIndexingFromLoad(LD);
9681           // Try to fold the base pointer arithmetic into subsequent loads and
9682           // stores.
9683           AddUsersToWorklist(N);
9684         } else
9685           Index = DAG.getUNDEF(N->getValueType(1));
9686         DEBUG(dbgs() << "\nReplacing.7 ";
9687               N->dump(&DAG);
9688               dbgs() << "\nWith: ";
9689               Undef.getNode()->dump(&DAG);
9690               dbgs() << " and 2 other values\n");
9691         WorklistRemover DeadNodes(*this);
9692         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9693         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9694         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9695         deleteAndRecombine(N);
9696         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9697       }
9698     }
9699   }
9700
9701   // If this load is directly stored, replace the load value with the stored
9702   // value.
9703   // TODO: Handle store large -> read small portion.
9704   // TODO: Handle TRUNCSTORE/LOADEXT
9705   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9706     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9707       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9708       if (PrevST->getBasePtr() == Ptr &&
9709           PrevST->getValue().getValueType() == N->getValueType(0))
9710       return CombineTo(N, Chain.getOperand(1), Chain);
9711     }
9712   }
9713
9714   // Try to infer better alignment information than the load already has.
9715   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9716     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9717       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9718         SDValue NewLoad =
9719                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9720                               LD->getValueType(0),
9721                               Chain, Ptr, LD->getPointerInfo(),
9722                               LD->getMemoryVT(),
9723                               LD->isVolatile(), LD->isNonTemporal(),
9724                               LD->isInvariant(), Align, LD->getAAInfo());
9725         if (NewLoad.getNode() != N)
9726           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9727       }
9728     }
9729   }
9730
9731   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9732                                                   : DAG.getSubtarget().useAA();
9733 #ifndef NDEBUG
9734   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9735       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9736     UseAA = false;
9737 #endif
9738   if (UseAA && LD->isUnindexed()) {
9739     // Walk up chain skipping non-aliasing memory nodes.
9740     SDValue BetterChain = FindBetterChain(N, Chain);
9741
9742     // If there is a better chain.
9743     if (Chain != BetterChain) {
9744       SDValue ReplLoad;
9745
9746       // Replace the chain to void dependency.
9747       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9748         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9749                                BetterChain, Ptr, LD->getMemOperand());
9750       } else {
9751         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9752                                   LD->getValueType(0),
9753                                   BetterChain, Ptr, LD->getMemoryVT(),
9754                                   LD->getMemOperand());
9755       }
9756
9757       // Create token factor to keep old chain connected.
9758       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9759                                   MVT::Other, Chain, ReplLoad.getValue(1));
9760
9761       // Make sure the new and old chains are cleaned up.
9762       AddToWorklist(Token.getNode());
9763
9764       // Replace uses with load result and token factor. Don't add users
9765       // to work list.
9766       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9767     }
9768   }
9769
9770   // Try transforming N to an indexed load.
9771   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9772     return SDValue(N, 0);
9773
9774   // Try to slice up N to more direct loads if the slices are mapped to
9775   // different register banks or pairing can take place.
9776   if (SliceUpLoad(N))
9777     return SDValue(N, 0);
9778
9779   return SDValue();
9780 }
9781
9782 namespace {
9783 /// \brief Helper structure used to slice a load in smaller loads.
9784 /// Basically a slice is obtained from the following sequence:
9785 /// Origin = load Ty1, Base
9786 /// Shift = srl Ty1 Origin, CstTy Amount
9787 /// Inst = trunc Shift to Ty2
9788 ///
9789 /// Then, it will be rewriten into:
9790 /// Slice = load SliceTy, Base + SliceOffset
9791 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9792 ///
9793 /// SliceTy is deduced from the number of bits that are actually used to
9794 /// build Inst.
9795 struct LoadedSlice {
9796   /// \brief Helper structure used to compute the cost of a slice.
9797   struct Cost {
9798     /// Are we optimizing for code size.
9799     bool ForCodeSize;
9800     /// Various cost.
9801     unsigned Loads;
9802     unsigned Truncates;
9803     unsigned CrossRegisterBanksCopies;
9804     unsigned ZExts;
9805     unsigned Shift;
9806
9807     Cost(bool ForCodeSize = false)
9808         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9809           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9810
9811     /// \brief Get the cost of one isolated slice.
9812     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9813         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9814           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9815       EVT TruncType = LS.Inst->getValueType(0);
9816       EVT LoadedType = LS.getLoadedType();
9817       if (TruncType != LoadedType &&
9818           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9819         ZExts = 1;
9820     }
9821
9822     /// \brief Account for slicing gain in the current cost.
9823     /// Slicing provide a few gains like removing a shift or a
9824     /// truncate. This method allows to grow the cost of the original
9825     /// load with the gain from this slice.
9826     void addSliceGain(const LoadedSlice &LS) {
9827       // Each slice saves a truncate.
9828       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9829       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9830                               LS.Inst->getValueType(0)))
9831         ++Truncates;
9832       // If there is a shift amount, this slice gets rid of it.
9833       if (LS.Shift)
9834         ++Shift;
9835       // If this slice can merge a cross register bank copy, account for it.
9836       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9837         ++CrossRegisterBanksCopies;
9838     }
9839
9840     Cost &operator+=(const Cost &RHS) {
9841       Loads += RHS.Loads;
9842       Truncates += RHS.Truncates;
9843       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9844       ZExts += RHS.ZExts;
9845       Shift += RHS.Shift;
9846       return *this;
9847     }
9848
9849     bool operator==(const Cost &RHS) const {
9850       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9851              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9852              ZExts == RHS.ZExts && Shift == RHS.Shift;
9853     }
9854
9855     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9856
9857     bool operator<(const Cost &RHS) const {
9858       // Assume cross register banks copies are as expensive as loads.
9859       // FIXME: Do we want some more target hooks?
9860       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9861       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9862       // Unless we are optimizing for code size, consider the
9863       // expensive operation first.
9864       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9865         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9866       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9867              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9868     }
9869
9870     bool operator>(const Cost &RHS) const { return RHS < *this; }
9871
9872     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9873
9874     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9875   };
9876   // The last instruction that represent the slice. This should be a
9877   // truncate instruction.
9878   SDNode *Inst;
9879   // The original load instruction.
9880   LoadSDNode *Origin;
9881   // The right shift amount in bits from the original load.
9882   unsigned Shift;
9883   // The DAG from which Origin came from.
9884   // This is used to get some contextual information about legal types, etc.
9885   SelectionDAG *DAG;
9886
9887   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9888               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9889       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9890
9891   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9892   /// \return Result is \p BitWidth and has used bits set to 1 and
9893   ///         not used bits set to 0.
9894   APInt getUsedBits() const {
9895     // Reproduce the trunc(lshr) sequence:
9896     // - Start from the truncated value.
9897     // - Zero extend to the desired bit width.
9898     // - Shift left.
9899     assert(Origin && "No original load to compare against.");
9900     unsigned BitWidth = Origin->getValueSizeInBits(0);
9901     assert(Inst && "This slice is not bound to an instruction");
9902     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9903            "Extracted slice is bigger than the whole type!");
9904     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9905     UsedBits.setAllBits();
9906     UsedBits = UsedBits.zext(BitWidth);
9907     UsedBits <<= Shift;
9908     return UsedBits;
9909   }
9910
9911   /// \brief Get the size of the slice to be loaded in bytes.
9912   unsigned getLoadedSize() const {
9913     unsigned SliceSize = getUsedBits().countPopulation();
9914     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9915     return SliceSize / 8;
9916   }
9917
9918   /// \brief Get the type that will be loaded for this slice.
9919   /// Note: This may not be the final type for the slice.
9920   EVT getLoadedType() const {
9921     assert(DAG && "Missing context");
9922     LLVMContext &Ctxt = *DAG->getContext();
9923     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9924   }
9925
9926   /// \brief Get the alignment of the load used for this slice.
9927   unsigned getAlignment() const {
9928     unsigned Alignment = Origin->getAlignment();
9929     unsigned Offset = getOffsetFromBase();
9930     if (Offset != 0)
9931       Alignment = MinAlign(Alignment, Alignment + Offset);
9932     return Alignment;
9933   }
9934
9935   /// \brief Check if this slice can be rewritten with legal operations.
9936   bool isLegal() const {
9937     // An invalid slice is not legal.
9938     if (!Origin || !Inst || !DAG)
9939       return false;
9940
9941     // Offsets are for indexed load only, we do not handle that.
9942     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9943       return false;
9944
9945     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9946
9947     // Check that the type is legal.
9948     EVT SliceType = getLoadedType();
9949     if (!TLI.isTypeLegal(SliceType))
9950       return false;
9951
9952     // Check that the load is legal for this type.
9953     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9954       return false;
9955
9956     // Check that the offset can be computed.
9957     // 1. Check its type.
9958     EVT PtrType = Origin->getBasePtr().getValueType();
9959     if (PtrType == MVT::Untyped || PtrType.isExtended())
9960       return false;
9961
9962     // 2. Check that it fits in the immediate.
9963     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9964       return false;
9965
9966     // 3. Check that the computation is legal.
9967     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9968       return false;
9969
9970     // Check that the zext is legal if it needs one.
9971     EVT TruncateType = Inst->getValueType(0);
9972     if (TruncateType != SliceType &&
9973         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9974       return false;
9975
9976     return true;
9977   }
9978
9979   /// \brief Get the offset in bytes of this slice in the original chunk of
9980   /// bits.
9981   /// \pre DAG != nullptr.
9982   uint64_t getOffsetFromBase() const {
9983     assert(DAG && "Missing context.");
9984     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9985     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9986     uint64_t Offset = Shift / 8;
9987     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9988     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9989            "The size of the original loaded type is not a multiple of a"
9990            " byte.");
9991     // If Offset is bigger than TySizeInBytes, it means we are loading all
9992     // zeros. This should have been optimized before in the process.
9993     assert(TySizeInBytes > Offset &&
9994            "Invalid shift amount for given loaded size");
9995     if (IsBigEndian)
9996       Offset = TySizeInBytes - Offset - getLoadedSize();
9997     return Offset;
9998   }
9999
10000   /// \brief Generate the sequence of instructions to load the slice
10001   /// represented by this object and redirect the uses of this slice to
10002   /// this new sequence of instructions.
10003   /// \pre this->Inst && this->Origin are valid Instructions and this
10004   /// object passed the legal check: LoadedSlice::isLegal returned true.
10005   /// \return The last instruction of the sequence used to load the slice.
10006   SDValue loadSlice() const {
10007     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10008     const SDValue &OldBaseAddr = Origin->getBasePtr();
10009     SDValue BaseAddr = OldBaseAddr;
10010     // Get the offset in that chunk of bytes w.r.t. the endianess.
10011     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10012     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10013     if (Offset) {
10014       // BaseAddr = BaseAddr + Offset.
10015       EVT ArithType = BaseAddr.getValueType();
10016       SDLoc DL(Origin);
10017       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10018                               DAG->getConstant(Offset, DL, ArithType));
10019     }
10020
10021     // Create the type of the loaded slice according to its size.
10022     EVT SliceType = getLoadedType();
10023
10024     // Create the load for the slice.
10025     SDValue LastInst = DAG->getLoad(
10026         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10027         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10028         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10029     // If the final type is not the same as the loaded type, this means that
10030     // we have to pad with zero. Create a zero extend for that.
10031     EVT FinalType = Inst->getValueType(0);
10032     if (SliceType != FinalType)
10033       LastInst =
10034           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10035     return LastInst;
10036   }
10037
10038   /// \brief Check if this slice can be merged with an expensive cross register
10039   /// bank copy. E.g.,
10040   /// i = load i32
10041   /// f = bitcast i32 i to float
10042   bool canMergeExpensiveCrossRegisterBankCopy() const {
10043     if (!Inst || !Inst->hasOneUse())
10044       return false;
10045     SDNode *Use = *Inst->use_begin();
10046     if (Use->getOpcode() != ISD::BITCAST)
10047       return false;
10048     assert(DAG && "Missing context");
10049     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10050     EVT ResVT = Use->getValueType(0);
10051     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10052     const TargetRegisterClass *ArgRC =
10053         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10054     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10055       return false;
10056
10057     // At this point, we know that we perform a cross-register-bank copy.
10058     // Check if it is expensive.
10059     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10060     // Assume bitcasts are cheap, unless both register classes do not
10061     // explicitly share a common sub class.
10062     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10063       return false;
10064
10065     // Check if it will be merged with the load.
10066     // 1. Check the alignment constraint.
10067     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10068         ResVT.getTypeForEVT(*DAG->getContext()));
10069
10070     if (RequiredAlignment > getAlignment())
10071       return false;
10072
10073     // 2. Check that the load is a legal operation for that type.
10074     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10075       return false;
10076
10077     // 3. Check that we do not have a zext in the way.
10078     if (Inst->getValueType(0) != getLoadedType())
10079       return false;
10080
10081     return true;
10082   }
10083 };
10084 }
10085
10086 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10087 /// \p UsedBits looks like 0..0 1..1 0..0.
10088 static bool areUsedBitsDense(const APInt &UsedBits) {
10089   // If all the bits are one, this is dense!
10090   if (UsedBits.isAllOnesValue())
10091     return true;
10092
10093   // Get rid of the unused bits on the right.
10094   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10095   // Get rid of the unused bits on the left.
10096   if (NarrowedUsedBits.countLeadingZeros())
10097     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10098   // Check that the chunk of bits is completely used.
10099   return NarrowedUsedBits.isAllOnesValue();
10100 }
10101
10102 /// \brief Check whether or not \p First and \p Second are next to each other
10103 /// in memory. This means that there is no hole between the bits loaded
10104 /// by \p First and the bits loaded by \p Second.
10105 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10106                                      const LoadedSlice &Second) {
10107   assert(First.Origin == Second.Origin && First.Origin &&
10108          "Unable to match different memory origins.");
10109   APInt UsedBits = First.getUsedBits();
10110   assert((UsedBits & Second.getUsedBits()) == 0 &&
10111          "Slices are not supposed to overlap.");
10112   UsedBits |= Second.getUsedBits();
10113   return areUsedBitsDense(UsedBits);
10114 }
10115
10116 /// \brief Adjust the \p GlobalLSCost according to the target
10117 /// paring capabilities and the layout of the slices.
10118 /// \pre \p GlobalLSCost should account for at least as many loads as
10119 /// there is in the slices in \p LoadedSlices.
10120 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10121                                  LoadedSlice::Cost &GlobalLSCost) {
10122   unsigned NumberOfSlices = LoadedSlices.size();
10123   // If there is less than 2 elements, no pairing is possible.
10124   if (NumberOfSlices < 2)
10125     return;
10126
10127   // Sort the slices so that elements that are likely to be next to each
10128   // other in memory are next to each other in the list.
10129   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10130             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10131     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10132     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10133   });
10134   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10135   // First (resp. Second) is the first (resp. Second) potentially candidate
10136   // to be placed in a paired load.
10137   const LoadedSlice *First = nullptr;
10138   const LoadedSlice *Second = nullptr;
10139   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10140                 // Set the beginning of the pair.
10141                                                            First = Second) {
10142
10143     Second = &LoadedSlices[CurrSlice];
10144
10145     // If First is NULL, it means we start a new pair.
10146     // Get to the next slice.
10147     if (!First)
10148       continue;
10149
10150     EVT LoadedType = First->getLoadedType();
10151
10152     // If the types of the slices are different, we cannot pair them.
10153     if (LoadedType != Second->getLoadedType())
10154       continue;
10155
10156     // Check if the target supplies paired loads for this type.
10157     unsigned RequiredAlignment = 0;
10158     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10159       // move to the next pair, this type is hopeless.
10160       Second = nullptr;
10161       continue;
10162     }
10163     // Check if we meet the alignment requirement.
10164     if (RequiredAlignment > First->getAlignment())
10165       continue;
10166
10167     // Check that both loads are next to each other in memory.
10168     if (!areSlicesNextToEachOther(*First, *Second))
10169       continue;
10170
10171     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10172     --GlobalLSCost.Loads;
10173     // Move to the next pair.
10174     Second = nullptr;
10175   }
10176 }
10177
10178 /// \brief Check the profitability of all involved LoadedSlice.
10179 /// Currently, it is considered profitable if there is exactly two
10180 /// involved slices (1) which are (2) next to each other in memory, and
10181 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10182 ///
10183 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10184 /// the elements themselves.
10185 ///
10186 /// FIXME: When the cost model will be mature enough, we can relax
10187 /// constraints (1) and (2).
10188 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10189                                 const APInt &UsedBits, bool ForCodeSize) {
10190   unsigned NumberOfSlices = LoadedSlices.size();
10191   if (StressLoadSlicing)
10192     return NumberOfSlices > 1;
10193
10194   // Check (1).
10195   if (NumberOfSlices != 2)
10196     return false;
10197
10198   // Check (2).
10199   if (!areUsedBitsDense(UsedBits))
10200     return false;
10201
10202   // Check (3).
10203   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10204   // The original code has one big load.
10205   OrigCost.Loads = 1;
10206   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10207     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10208     // Accumulate the cost of all the slices.
10209     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10210     GlobalSlicingCost += SliceCost;
10211
10212     // Account as cost in the original configuration the gain obtained
10213     // with the current slices.
10214     OrigCost.addSliceGain(LS);
10215   }
10216
10217   // If the target supports paired load, adjust the cost accordingly.
10218   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10219   return OrigCost > GlobalSlicingCost;
10220 }
10221
10222 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10223 /// operations, split it in the various pieces being extracted.
10224 ///
10225 /// This sort of thing is introduced by SROA.
10226 /// This slicing takes care not to insert overlapping loads.
10227 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10228 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10229   if (Level < AfterLegalizeDAG)
10230     return false;
10231
10232   LoadSDNode *LD = cast<LoadSDNode>(N);
10233   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10234       !LD->getValueType(0).isInteger())
10235     return false;
10236
10237   // Keep track of already used bits to detect overlapping values.
10238   // In that case, we will just abort the transformation.
10239   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10240
10241   SmallVector<LoadedSlice, 4> LoadedSlices;
10242
10243   // Check if this load is used as several smaller chunks of bits.
10244   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10245   // of computation for each trunc.
10246   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10247        UI != UIEnd; ++UI) {
10248     // Skip the uses of the chain.
10249     if (UI.getUse().getResNo() != 0)
10250       continue;
10251
10252     SDNode *User = *UI;
10253     unsigned Shift = 0;
10254
10255     // Check if this is a trunc(lshr).
10256     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10257         isa<ConstantSDNode>(User->getOperand(1))) {
10258       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10259       User = *User->use_begin();
10260     }
10261
10262     // At this point, User is a Truncate, iff we encountered, trunc or
10263     // trunc(lshr).
10264     if (User->getOpcode() != ISD::TRUNCATE)
10265       return false;
10266
10267     // The width of the type must be a power of 2 and greater than 8-bits.
10268     // Otherwise the load cannot be represented in LLVM IR.
10269     // Moreover, if we shifted with a non-8-bits multiple, the slice
10270     // will be across several bytes. We do not support that.
10271     unsigned Width = User->getValueSizeInBits(0);
10272     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10273       return 0;
10274
10275     // Build the slice for this chain of computations.
10276     LoadedSlice LS(User, LD, Shift, &DAG);
10277     APInt CurrentUsedBits = LS.getUsedBits();
10278
10279     // Check if this slice overlaps with another.
10280     if ((CurrentUsedBits & UsedBits) != 0)
10281       return false;
10282     // Update the bits used globally.
10283     UsedBits |= CurrentUsedBits;
10284
10285     // Check if the new slice would be legal.
10286     if (!LS.isLegal())
10287       return false;
10288
10289     // Record the slice.
10290     LoadedSlices.push_back(LS);
10291   }
10292
10293   // Abort slicing if it does not seem to be profitable.
10294   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10295     return false;
10296
10297   ++SlicedLoads;
10298
10299   // Rewrite each chain to use an independent load.
10300   // By construction, each chain can be represented by a unique load.
10301
10302   // Prepare the argument for the new token factor for all the slices.
10303   SmallVector<SDValue, 8> ArgChains;
10304   for (SmallVectorImpl<LoadedSlice>::const_iterator
10305            LSIt = LoadedSlices.begin(),
10306            LSItEnd = LoadedSlices.end();
10307        LSIt != LSItEnd; ++LSIt) {
10308     SDValue SliceInst = LSIt->loadSlice();
10309     CombineTo(LSIt->Inst, SliceInst, true);
10310     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10311       SliceInst = SliceInst.getOperand(0);
10312     assert(SliceInst->getOpcode() == ISD::LOAD &&
10313            "It takes more than a zext to get to the loaded slice!!");
10314     ArgChains.push_back(SliceInst.getValue(1));
10315   }
10316
10317   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10318                               ArgChains);
10319   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10320   return true;
10321 }
10322
10323 /// Check to see if V is (and load (ptr), imm), where the load is having
10324 /// specific bytes cleared out.  If so, return the byte size being masked out
10325 /// and the shift amount.
10326 static std::pair<unsigned, unsigned>
10327 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10328   std::pair<unsigned, unsigned> Result(0, 0);
10329
10330   // Check for the structure we're looking for.
10331   if (V->getOpcode() != ISD::AND ||
10332       !isa<ConstantSDNode>(V->getOperand(1)) ||
10333       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10334     return Result;
10335
10336   // Check the chain and pointer.
10337   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10338   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10339
10340   // The store should be chained directly to the load or be an operand of a
10341   // tokenfactor.
10342   if (LD == Chain.getNode())
10343     ; // ok.
10344   else if (Chain->getOpcode() != ISD::TokenFactor)
10345     return Result; // Fail.
10346   else {
10347     bool isOk = false;
10348     for (const SDValue &ChainOp : Chain->op_values())
10349       if (ChainOp.getNode() == LD) {
10350         isOk = true;
10351         break;
10352       }
10353     if (!isOk) return Result;
10354   }
10355
10356   // This only handles simple types.
10357   if (V.getValueType() != MVT::i16 &&
10358       V.getValueType() != MVT::i32 &&
10359       V.getValueType() != MVT::i64)
10360     return Result;
10361
10362   // Check the constant mask.  Invert it so that the bits being masked out are
10363   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10364   // follow the sign bit for uniformity.
10365   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10366   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10367   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10368   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10369   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10370   if (NotMaskLZ == 64) return Result;  // All zero mask.
10371
10372   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10373   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10374     return Result;
10375
10376   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10377   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10378     NotMaskLZ -= 64-V.getValueSizeInBits();
10379
10380   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10381   switch (MaskedBytes) {
10382   case 1:
10383   case 2:
10384   case 4: break;
10385   default: return Result; // All one mask, or 5-byte mask.
10386   }
10387
10388   // Verify that the first bit starts at a multiple of mask so that the access
10389   // is aligned the same as the access width.
10390   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10391
10392   Result.first = MaskedBytes;
10393   Result.second = NotMaskTZ/8;
10394   return Result;
10395 }
10396
10397
10398 /// Check to see if IVal is something that provides a value as specified by
10399 /// MaskInfo. If so, replace the specified store with a narrower store of
10400 /// truncated IVal.
10401 static SDNode *
10402 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10403                                 SDValue IVal, StoreSDNode *St,
10404                                 DAGCombiner *DC) {
10405   unsigned NumBytes = MaskInfo.first;
10406   unsigned ByteShift = MaskInfo.second;
10407   SelectionDAG &DAG = DC->getDAG();
10408
10409   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10410   // that uses this.  If not, this is not a replacement.
10411   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10412                                   ByteShift*8, (ByteShift+NumBytes)*8);
10413   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10414
10415   // Check that it is legal on the target to do this.  It is legal if the new
10416   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10417   // legalization.
10418   MVT VT = MVT::getIntegerVT(NumBytes*8);
10419   if (!DC->isTypeLegal(VT))
10420     return nullptr;
10421
10422   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10423   // shifted by ByteShift and truncated down to NumBytes.
10424   if (ByteShift) {
10425     SDLoc DL(IVal);
10426     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10427                        DAG.getConstant(ByteShift*8, DL,
10428                                     DC->getShiftAmountTy(IVal.getValueType())));
10429   }
10430
10431   // Figure out the offset for the store and the alignment of the access.
10432   unsigned StOffset;
10433   unsigned NewAlign = St->getAlignment();
10434
10435   if (DAG.getDataLayout().isLittleEndian())
10436     StOffset = ByteShift;
10437   else
10438     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10439
10440   SDValue Ptr = St->getBasePtr();
10441   if (StOffset) {
10442     SDLoc DL(IVal);
10443     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10444                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10445     NewAlign = MinAlign(NewAlign, StOffset);
10446   }
10447
10448   // Truncate down to the new size.
10449   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10450
10451   ++OpsNarrowed;
10452   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10453                       St->getPointerInfo().getWithOffset(StOffset),
10454                       false, false, NewAlign).getNode();
10455 }
10456
10457
10458 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10459 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10460 /// narrowing the load and store if it would end up being a win for performance
10461 /// or code size.
10462 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10463   StoreSDNode *ST  = cast<StoreSDNode>(N);
10464   if (ST->isVolatile())
10465     return SDValue();
10466
10467   SDValue Chain = ST->getChain();
10468   SDValue Value = ST->getValue();
10469   SDValue Ptr   = ST->getBasePtr();
10470   EVT VT = Value.getValueType();
10471
10472   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10473     return SDValue();
10474
10475   unsigned Opc = Value.getOpcode();
10476
10477   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10478   // is a byte mask indicating a consecutive number of bytes, check to see if
10479   // Y is known to provide just those bytes.  If so, we try to replace the
10480   // load + replace + store sequence with a single (narrower) store, which makes
10481   // the load dead.
10482   if (Opc == ISD::OR) {
10483     std::pair<unsigned, unsigned> MaskedLoad;
10484     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10485     if (MaskedLoad.first)
10486       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10487                                                   Value.getOperand(1), ST,this))
10488         return SDValue(NewST, 0);
10489
10490     // Or is commutative, so try swapping X and Y.
10491     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10492     if (MaskedLoad.first)
10493       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10494                                                   Value.getOperand(0), ST,this))
10495         return SDValue(NewST, 0);
10496   }
10497
10498   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10499       Value.getOperand(1).getOpcode() != ISD::Constant)
10500     return SDValue();
10501
10502   SDValue N0 = Value.getOperand(0);
10503   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10504       Chain == SDValue(N0.getNode(), 1)) {
10505     LoadSDNode *LD = cast<LoadSDNode>(N0);
10506     if (LD->getBasePtr() != Ptr ||
10507         LD->getPointerInfo().getAddrSpace() !=
10508         ST->getPointerInfo().getAddrSpace())
10509       return SDValue();
10510
10511     // Find the type to narrow it the load / op / store to.
10512     SDValue N1 = Value.getOperand(1);
10513     unsigned BitWidth = N1.getValueSizeInBits();
10514     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10515     if (Opc == ISD::AND)
10516       Imm ^= APInt::getAllOnesValue(BitWidth);
10517     if (Imm == 0 || Imm.isAllOnesValue())
10518       return SDValue();
10519     unsigned ShAmt = Imm.countTrailingZeros();
10520     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10521     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10522     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10523     // The narrowing should be profitable, the load/store operation should be
10524     // legal (or custom) and the store size should be equal to the NewVT width.
10525     while (NewBW < BitWidth &&
10526            (NewVT.getStoreSizeInBits() != NewBW ||
10527             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10528             !TLI.isNarrowingProfitable(VT, NewVT))) {
10529       NewBW = NextPowerOf2(NewBW);
10530       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10531     }
10532     if (NewBW >= BitWidth)
10533       return SDValue();
10534
10535     // If the lsb changed does not start at the type bitwidth boundary,
10536     // start at the previous one.
10537     if (ShAmt % NewBW)
10538       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10539     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10540                                    std::min(BitWidth, ShAmt + NewBW));
10541     if ((Imm & Mask) == Imm) {
10542       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10543       if (Opc == ISD::AND)
10544         NewImm ^= APInt::getAllOnesValue(NewBW);
10545       uint64_t PtrOff = ShAmt / 8;
10546       // For big endian targets, we need to adjust the offset to the pointer to
10547       // load the correct bytes.
10548       if (DAG.getDataLayout().isBigEndian())
10549         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10550
10551       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10552       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10553       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10554         return SDValue();
10555
10556       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10557                                    Ptr.getValueType(), Ptr,
10558                                    DAG.getConstant(PtrOff, SDLoc(LD),
10559                                                    Ptr.getValueType()));
10560       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10561                                   LD->getChain(), NewPtr,
10562                                   LD->getPointerInfo().getWithOffset(PtrOff),
10563                                   LD->isVolatile(), LD->isNonTemporal(),
10564                                   LD->isInvariant(), NewAlign,
10565                                   LD->getAAInfo());
10566       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10567                                    DAG.getConstant(NewImm, SDLoc(Value),
10568                                                    NewVT));
10569       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10570                                    NewVal, NewPtr,
10571                                    ST->getPointerInfo().getWithOffset(PtrOff),
10572                                    false, false, NewAlign);
10573
10574       AddToWorklist(NewPtr.getNode());
10575       AddToWorklist(NewLD.getNode());
10576       AddToWorklist(NewVal.getNode());
10577       WorklistRemover DeadNodes(*this);
10578       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10579       ++OpsNarrowed;
10580       return NewST;
10581     }
10582   }
10583
10584   return SDValue();
10585 }
10586
10587 /// For a given floating point load / store pair, if the load value isn't used
10588 /// by any other operations, then consider transforming the pair to integer
10589 /// load / store operations if the target deems the transformation profitable.
10590 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10591   StoreSDNode *ST  = cast<StoreSDNode>(N);
10592   SDValue Chain = ST->getChain();
10593   SDValue Value = ST->getValue();
10594   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10595       Value.hasOneUse() &&
10596       Chain == SDValue(Value.getNode(), 1)) {
10597     LoadSDNode *LD = cast<LoadSDNode>(Value);
10598     EVT VT = LD->getMemoryVT();
10599     if (!VT.isFloatingPoint() ||
10600         VT != ST->getMemoryVT() ||
10601         LD->isNonTemporal() ||
10602         ST->isNonTemporal() ||
10603         LD->getPointerInfo().getAddrSpace() != 0 ||
10604         ST->getPointerInfo().getAddrSpace() != 0)
10605       return SDValue();
10606
10607     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10608     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10609         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10610         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10611         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10612       return SDValue();
10613
10614     unsigned LDAlign = LD->getAlignment();
10615     unsigned STAlign = ST->getAlignment();
10616     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10617     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10618     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10619       return SDValue();
10620
10621     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10622                                 LD->getChain(), LD->getBasePtr(),
10623                                 LD->getPointerInfo(),
10624                                 false, false, false, LDAlign);
10625
10626     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10627                                  NewLD, ST->getBasePtr(),
10628                                  ST->getPointerInfo(),
10629                                  false, false, STAlign);
10630
10631     AddToWorklist(NewLD.getNode());
10632     AddToWorklist(NewST.getNode());
10633     WorklistRemover DeadNodes(*this);
10634     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10635     ++LdStFP2Int;
10636     return NewST;
10637   }
10638
10639   return SDValue();
10640 }
10641
10642 namespace {
10643 /// Helper struct to parse and store a memory address as base + index + offset.
10644 /// We ignore sign extensions when it is safe to do so.
10645 /// The following two expressions are not equivalent. To differentiate we need
10646 /// to store whether there was a sign extension involved in the index
10647 /// computation.
10648 ///  (load (i64 add (i64 copyfromreg %c)
10649 ///                 (i64 signextend (add (i8 load %index)
10650 ///                                      (i8 1))))
10651 /// vs
10652 ///
10653 /// (load (i64 add (i64 copyfromreg %c)
10654 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10655 ///                                         (i32 1)))))
10656 struct BaseIndexOffset {
10657   SDValue Base;
10658   SDValue Index;
10659   int64_t Offset;
10660   bool IsIndexSignExt;
10661
10662   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10663
10664   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10665                   bool IsIndexSignExt) :
10666     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10667
10668   bool equalBaseIndex(const BaseIndexOffset &Other) {
10669     return Other.Base == Base && Other.Index == Index &&
10670       Other.IsIndexSignExt == IsIndexSignExt;
10671   }
10672
10673   /// Parses tree in Ptr for base, index, offset addresses.
10674   static BaseIndexOffset match(SDValue Ptr) {
10675     bool IsIndexSignExt = false;
10676
10677     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10678     // instruction, then it could be just the BASE or everything else we don't
10679     // know how to handle. Just use Ptr as BASE and give up.
10680     if (Ptr->getOpcode() != ISD::ADD)
10681       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10682
10683     // We know that we have at least an ADD instruction. Try to pattern match
10684     // the simple case of BASE + OFFSET.
10685     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10686       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10687       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10688                               IsIndexSignExt);
10689     }
10690
10691     // Inside a loop the current BASE pointer is calculated using an ADD and a
10692     // MUL instruction. In this case Ptr is the actual BASE pointer.
10693     // (i64 add (i64 %array_ptr)
10694     //          (i64 mul (i64 %induction_var)
10695     //                   (i64 %element_size)))
10696     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10697       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10698
10699     // Look at Base + Index + Offset cases.
10700     SDValue Base = Ptr->getOperand(0);
10701     SDValue IndexOffset = Ptr->getOperand(1);
10702
10703     // Skip signextends.
10704     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10705       IndexOffset = IndexOffset->getOperand(0);
10706       IsIndexSignExt = true;
10707     }
10708
10709     // Either the case of Base + Index (no offset) or something else.
10710     if (IndexOffset->getOpcode() != ISD::ADD)
10711       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10712
10713     // Now we have the case of Base + Index + offset.
10714     SDValue Index = IndexOffset->getOperand(0);
10715     SDValue Offset = IndexOffset->getOperand(1);
10716
10717     if (!isa<ConstantSDNode>(Offset))
10718       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10719
10720     // Ignore signextends.
10721     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10722       Index = Index->getOperand(0);
10723       IsIndexSignExt = true;
10724     } else IsIndexSignExt = false;
10725
10726     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10727     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10728   }
10729 };
10730 } // namespace
10731
10732 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10733                                                   SDLoc SL,
10734                                                   ArrayRef<MemOpLink> Stores,
10735                                                   EVT Ty) const {
10736   SmallVector<SDValue, 8> BuildVector;
10737
10738   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10739     BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10740
10741   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10742 }
10743
10744 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10745                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10746                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10747   // Make sure we have something to merge.
10748   if (NumStores < 2)
10749     return false;
10750
10751   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10752   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10753   unsigned LatestNodeUsed = 0;
10754
10755   for (unsigned i=0; i < NumStores; ++i) {
10756     // Find a chain for the new wide-store operand. Notice that some
10757     // of the store nodes that we found may not be selected for inclusion
10758     // in the wide store. The chain we use needs to be the chain of the
10759     // latest store node which is *used* and replaced by the wide store.
10760     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10761       LatestNodeUsed = i;
10762   }
10763
10764   // The latest Node in the DAG.
10765   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10766   SDLoc DL(StoreNodes[0].MemNode);
10767
10768   SDValue StoredVal;
10769   if (UseVector) {
10770     bool IsVec = MemVT.isVector();
10771     unsigned Elts = NumStores;
10772     if (IsVec) {
10773       // When merging vector stores, get the total number of elements.
10774       Elts *= MemVT.getVectorNumElements();
10775     }
10776     // Get the type for the merged vector store.
10777     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10778     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10779
10780     if (IsConstantSrc) {
10781       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10782     } else {
10783       SmallVector<SDValue, 8> Ops;
10784       for (unsigned i = 0; i < NumStores; ++i) {
10785         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10786         SDValue Val = St->getValue();
10787         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10788         if (Val.getValueType() != MemVT)
10789           return false;
10790         Ops.push_back(Val);
10791       }
10792
10793       // Build the extracted vector elements back into a vector.
10794       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10795                               DL, Ty, Ops);    }
10796   } else {
10797     // We should always use a vector store when merging extracted vector
10798     // elements, so this path implies a store of constants.
10799     assert(IsConstantSrc && "Merged vector elements should use vector store");
10800
10801     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10802     APInt StoreInt(SizeInBits, 0);
10803
10804     // Construct a single integer constant which is made of the smaller
10805     // constant inputs.
10806     bool IsLE = DAG.getDataLayout().isLittleEndian();
10807     for (unsigned i = 0; i < NumStores; ++i) {
10808       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10809       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10810       SDValue Val = St->getValue();
10811       StoreInt <<= ElementSizeBytes * 8;
10812       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10813         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10814       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10815         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10816       } else {
10817         llvm_unreachable("Invalid constant element type");
10818       }
10819     }
10820
10821     // Create the new Load and Store operations.
10822     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10823     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10824   }
10825
10826   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10827                                   FirstInChain->getBasePtr(),
10828                                   FirstInChain->getPointerInfo(),
10829                                   false, false,
10830                                   FirstInChain->getAlignment());
10831
10832   // Replace the last store with the new store
10833   CombineTo(LatestOp, NewStore);
10834   // Erase all other stores.
10835   for (unsigned i = 0; i < NumStores; ++i) {
10836     if (StoreNodes[i].MemNode == LatestOp)
10837       continue;
10838     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10839     // ReplaceAllUsesWith will replace all uses that existed when it was
10840     // called, but graph optimizations may cause new ones to appear. For
10841     // example, the case in pr14333 looks like
10842     //
10843     //  St's chain -> St -> another store -> X
10844     //
10845     // And the only difference from St to the other store is the chain.
10846     // When we change it's chain to be St's chain they become identical,
10847     // get CSEed and the net result is that X is now a use of St.
10848     // Since we know that St is redundant, just iterate.
10849     while (!St->use_empty())
10850       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10851     deleteAndRecombine(St);
10852   }
10853
10854   return true;
10855 }
10856
10857 void DAGCombiner::getStoreMergeAndAliasCandidates(
10858     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10859     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10860   // This holds the base pointer, index, and the offset in bytes from the base
10861   // pointer.
10862   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10863
10864   // We must have a base and an offset.
10865   if (!BasePtr.Base.getNode())
10866     return;
10867
10868   // Do not handle stores to undef base pointers.
10869   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10870     return;
10871
10872   // Walk up the chain and look for nodes with offsets from the same
10873   // base pointer. Stop when reaching an instruction with a different kind
10874   // or instruction which has a different base pointer.
10875   EVT MemVT = St->getMemoryVT();
10876   unsigned Seq = 0;
10877   StoreSDNode *Index = St;
10878
10879
10880   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10881                                                   : DAG.getSubtarget().useAA();
10882
10883   if (UseAA) {
10884     // Look at other users of the same chain. Stores on the same chain do not
10885     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10886     // to be on the same chain, so don't bother looking at adjacent chains.
10887
10888     SDValue Chain = St->getChain();
10889     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10890       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10891
10892         if (OtherST->isVolatile() || OtherST->isIndexed())
10893           continue;
10894
10895         if (OtherST->getMemoryVT() != MemVT)
10896           continue;
10897
10898         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10899
10900         if (Ptr.equalBaseIndex(BasePtr))
10901           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
10902       }
10903     }
10904
10905     return;
10906   }
10907
10908   while (Index) {
10909     // If the chain has more than one use, then we can't reorder the mem ops.
10910     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10911       break;
10912
10913     // Find the base pointer and offset for this memory node.
10914     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10915
10916     // Check that the base pointer is the same as the original one.
10917     if (!Ptr.equalBaseIndex(BasePtr))
10918       break;
10919
10920     // The memory operands must not be volatile.
10921     if (Index->isVolatile() || Index->isIndexed())
10922       break;
10923
10924     // No truncation.
10925     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10926       if (St->isTruncatingStore())
10927         break;
10928
10929     // The stored memory type must be the same.
10930     if (Index->getMemoryVT() != MemVT)
10931       break;
10932
10933     // We found a potential memory operand to merge.
10934     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10935
10936     // Find the next memory operand in the chain. If the next operand in the
10937     // chain is a store then move up and continue the scan with the next
10938     // memory operand. If the next operand is a load save it and use alias
10939     // information to check if it interferes with anything.
10940     SDNode *NextInChain = Index->getChain().getNode();
10941     while (1) {
10942       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10943         // We found a store node. Use it for the next iteration.
10944         Index = STn;
10945         break;
10946       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10947         if (Ldn->isVolatile()) {
10948           Index = nullptr;
10949           break;
10950         }
10951
10952         // Save the load node for later. Continue the scan.
10953         AliasLoadNodes.push_back(Ldn);
10954         NextInChain = Ldn->getChain().getNode();
10955         continue;
10956       } else {
10957         Index = nullptr;
10958         break;
10959       }
10960     }
10961   }
10962 }
10963
10964 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10965   if (OptLevel == CodeGenOpt::None)
10966     return false;
10967
10968   EVT MemVT = St->getMemoryVT();
10969   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10970   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10971       Attribute::NoImplicitFloat);
10972
10973   // This function cannot currently deal with non-byte-sized memory sizes.
10974   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10975     return false;
10976
10977   // Don't merge vectors into wider inputs.
10978   if (MemVT.isVector() || !MemVT.isSimple())
10979     return false;
10980
10981   // Perform an early exit check. Do not bother looking at stored values that
10982   // are not constants, loads, or extracted vector elements.
10983   SDValue StoredVal = St->getValue();
10984   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10985   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10986                        isa<ConstantFPSDNode>(StoredVal);
10987   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10988
10989   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10990     return false;
10991
10992   // Only look at ends of store sequences.
10993   SDValue Chain = SDValue(St, 0);
10994   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10995     return false;
10996
10997   // Save the LoadSDNodes that we find in the chain.
10998   // We need to make sure that these nodes do not interfere with
10999   // any of the store nodes.
11000   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11001
11002   // Save the StoreSDNodes that we find in the chain.
11003   SmallVector<MemOpLink, 8> StoreNodes;
11004
11005   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11006
11007   // Check if there is anything to merge.
11008   if (StoreNodes.size() < 2)
11009     return false;
11010
11011   // Sort the memory operands according to their distance from the base pointer.
11012   std::sort(StoreNodes.begin(), StoreNodes.end(),
11013             [](MemOpLink LHS, MemOpLink RHS) {
11014     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11015            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11016             LHS.SequenceNum > RHS.SequenceNum);
11017   });
11018
11019   // Scan the memory operations on the chain and find the first non-consecutive
11020   // store memory address.
11021   unsigned LastConsecutiveStore = 0;
11022   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11023   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11024
11025     // Check that the addresses are consecutive starting from the second
11026     // element in the list of stores.
11027     if (i > 0) {
11028       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11029       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11030         break;
11031     }
11032
11033     bool Alias = false;
11034     // Check if this store interferes with any of the loads that we found.
11035     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11036       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11037         Alias = true;
11038         break;
11039       }
11040     // We found a load that alias with this store. Stop the sequence.
11041     if (Alias)
11042       break;
11043
11044     // Mark this node as useful.
11045     LastConsecutiveStore = i;
11046   }
11047
11048   // The node with the lowest store address.
11049   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11050   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11051   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11052   LLVMContext &Context = *DAG.getContext();
11053   const DataLayout &DL = DAG.getDataLayout();
11054
11055   // Store the constants into memory as one consecutive store.
11056   if (IsConstantSrc) {
11057     unsigned LastLegalType = 0;
11058     unsigned LastLegalVectorType = 0;
11059     bool NonZero = false;
11060     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11061       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11062       SDValue StoredVal = St->getValue();
11063
11064       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11065         NonZero |= !C->isNullValue();
11066       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11067         NonZero |= !C->getConstantFPValue()->isNullValue();
11068       } else {
11069         // Non-constant.
11070         break;
11071       }
11072
11073       // Find a legal type for the constant store.
11074       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11075       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11076       bool IsFast;
11077       if (TLI.isTypeLegal(StoreTy) &&
11078           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11079                                  FirstStoreAlign, &IsFast) && IsFast) {
11080         LastLegalType = i+1;
11081       // Or check whether a truncstore is legal.
11082       } else if (TLI.getTypeAction(Context, StoreTy) ==
11083                  TargetLowering::TypePromoteInteger) {
11084         EVT LegalizedStoredValueTy =
11085           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11086         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11087             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11088                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11089             IsFast) {
11090           LastLegalType = i + 1;
11091         }
11092       }
11093
11094       // We only use vectors if the constant is known to be zero or the target
11095       // allows it and the function is not marked with the noimplicitfloat
11096       // attribute.
11097       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11098                                                         FirstStoreAS)) &&
11099           !NoVectors) {
11100         // Find a legal type for the vector store.
11101         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11102         if (TLI.isTypeLegal(Ty) &&
11103             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11104                                    FirstStoreAlign, &IsFast) && IsFast)
11105           LastLegalVectorType = i + 1;
11106       }
11107     }
11108
11109     // Check if we found a legal integer type to store.
11110     if (LastLegalType == 0 && LastLegalVectorType == 0)
11111       return false;
11112
11113     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11114     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11115
11116     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11117                                            true, UseVector);
11118   }
11119
11120   // When extracting multiple vector elements, try to store them
11121   // in one vector store rather than a sequence of scalar stores.
11122   if (IsExtractVecEltSrc) {
11123     unsigned NumElem = 0;
11124     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11125       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11126       SDValue StoredVal = St->getValue();
11127       // This restriction could be loosened.
11128       // Bail out if any stored values are not elements extracted from a vector.
11129       // It should be possible to handle mixed sources, but load sources need
11130       // more careful handling (see the block of code below that handles
11131       // consecutive loads).
11132       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11133         return false;
11134
11135       // Find a legal type for the vector store.
11136       EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11137       bool IsFast;
11138       if (TLI.isTypeLegal(Ty) &&
11139           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11140                                  FirstStoreAlign, &IsFast) && IsFast)
11141         NumElem = i + 1;
11142     }
11143
11144     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11145                                            false, true);
11146   }
11147
11148   // Below we handle the case of multiple consecutive stores that
11149   // come from multiple consecutive loads. We merge them into a single
11150   // wide load and a single wide store.
11151
11152   // Look for load nodes which are used by the stored values.
11153   SmallVector<MemOpLink, 8> LoadNodes;
11154
11155   // Find acceptable loads. Loads need to have the same chain (token factor),
11156   // must not be zext, volatile, indexed, and they must be consecutive.
11157   BaseIndexOffset LdBasePtr;
11158   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11159     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11160     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11161     if (!Ld) break;
11162
11163     // Loads must only have one use.
11164     if (!Ld->hasNUsesOfValue(1, 0))
11165       break;
11166
11167     // The memory operands must not be volatile.
11168     if (Ld->isVolatile() || Ld->isIndexed())
11169       break;
11170
11171     // We do not accept ext loads.
11172     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11173       break;
11174
11175     // The stored memory type must be the same.
11176     if (Ld->getMemoryVT() != MemVT)
11177       break;
11178
11179     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11180     // If this is not the first ptr that we check.
11181     if (LdBasePtr.Base.getNode()) {
11182       // The base ptr must be the same.
11183       if (!LdPtr.equalBaseIndex(LdBasePtr))
11184         break;
11185     } else {
11186       // Check that all other base pointers are the same as this one.
11187       LdBasePtr = LdPtr;
11188     }
11189
11190     // We found a potential memory operand to merge.
11191     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11192   }
11193
11194   if (LoadNodes.size() < 2)
11195     return false;
11196
11197   // If we have load/store pair instructions and we only have two values,
11198   // don't bother.
11199   unsigned RequiredAlignment;
11200   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11201       St->getAlignment() >= RequiredAlignment)
11202     return false;
11203
11204   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11205   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11206   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11207
11208   // Scan the memory operations on the chain and find the first non-consecutive
11209   // load memory address. These variables hold the index in the store node
11210   // array.
11211   unsigned LastConsecutiveLoad = 0;
11212   // This variable refers to the size and not index in the array.
11213   unsigned LastLegalVectorType = 0;
11214   unsigned LastLegalIntegerType = 0;
11215   StartAddress = LoadNodes[0].OffsetFromBase;
11216   SDValue FirstChain = FirstLoad->getChain();
11217   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11218     // All loads much share the same chain.
11219     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11220       break;
11221
11222     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11223     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11224       break;
11225     LastConsecutiveLoad = i;
11226     // Find a legal type for the vector store.
11227     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11228     bool IsFastSt, IsFastLd;
11229     if (TLI.isTypeLegal(StoreTy) &&
11230         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11231                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11232         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11233                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11234       LastLegalVectorType = i + 1;
11235     }
11236
11237     // Find a legal type for the integer store.
11238     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11239     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11240     if (TLI.isTypeLegal(StoreTy) &&
11241         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11242                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11243         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11244                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11245       LastLegalIntegerType = i + 1;
11246     // Or check whether a truncstore and extload is legal.
11247     else if (TLI.getTypeAction(Context, StoreTy) ==
11248              TargetLowering::TypePromoteInteger) {
11249       EVT LegalizedStoredValueTy =
11250         TLI.getTypeToTransformTo(Context, StoreTy);
11251       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11252           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11253           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11254           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11255           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11256                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11257           IsFastSt &&
11258           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11259                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11260           IsFastLd)
11261         LastLegalIntegerType = i+1;
11262     }
11263   }
11264
11265   // Only use vector types if the vector type is larger than the integer type.
11266   // If they are the same, use integers.
11267   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11268   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11269
11270   // We add +1 here because the LastXXX variables refer to location while
11271   // the NumElem refers to array/index size.
11272   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11273   NumElem = std::min(LastLegalType, NumElem);
11274
11275   if (NumElem < 2)
11276     return false;
11277
11278   // The latest Node in the DAG.
11279   unsigned LatestNodeUsed = 0;
11280   for (unsigned i=1; i<NumElem; ++i) {
11281     // Find a chain for the new wide-store operand. Notice that some
11282     // of the store nodes that we found may not be selected for inclusion
11283     // in the wide store. The chain we use needs to be the chain of the
11284     // latest store node which is *used* and replaced by the wide store.
11285     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11286       LatestNodeUsed = i;
11287   }
11288
11289   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11290
11291   // Find if it is better to use vectors or integers to load and store
11292   // to memory.
11293   EVT JointMemOpVT;
11294   if (UseVectorTy) {
11295     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11296   } else {
11297     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11298     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11299   }
11300
11301   SDLoc LoadDL(LoadNodes[0].MemNode);
11302   SDLoc StoreDL(StoreNodes[0].MemNode);
11303
11304   SDValue NewLoad = DAG.getLoad(
11305       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11306       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11307
11308   SDValue NewStore = DAG.getStore(
11309       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11310       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11311
11312   // Replace one of the loads with the new load.
11313   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11314   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11315                                 SDValue(NewLoad.getNode(), 1));
11316
11317   // Remove the rest of the load chains.
11318   for (unsigned i = 1; i < NumElem ; ++i) {
11319     // Replace all chain users of the old load nodes with the chain of the new
11320     // load node.
11321     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11322     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11323   }
11324
11325   // Replace the last store with the new store.
11326   CombineTo(LatestOp, NewStore);
11327   // Erase all other stores.
11328   for (unsigned i = 0; i < NumElem ; ++i) {
11329     // Remove all Store nodes.
11330     if (StoreNodes[i].MemNode == LatestOp)
11331       continue;
11332     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11333     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11334     deleteAndRecombine(St);
11335   }
11336
11337   return true;
11338 }
11339
11340 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11341   SDLoc SL(ST);
11342   SDValue ReplStore;
11343
11344   // Replace the chain to avoid dependency.
11345   if (ST->isTruncatingStore()) {
11346     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11347                                   ST->getBasePtr(), ST->getMemoryVT(),
11348                                   ST->getMemOperand());
11349   } else {
11350     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11351                              ST->getMemOperand());
11352   }
11353
11354   // Create token to keep both nodes around.
11355   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11356                               MVT::Other, ST->getChain(), ReplStore);
11357
11358   // Make sure the new and old chains are cleaned up.
11359   AddToWorklist(Token.getNode());
11360
11361   // Don't add users to work list.
11362   return CombineTo(ST, Token, false);
11363 }
11364
11365 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11366   SDValue Value = ST->getValue();
11367   if (Value.getOpcode() == ISD::TargetConstantFP)
11368     return SDValue();
11369
11370   SDLoc DL(ST);
11371
11372   SDValue Chain = ST->getChain();
11373   SDValue Ptr = ST->getBasePtr();
11374
11375   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11376
11377   // NOTE: If the original store is volatile, this transform must not increase
11378   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11379   // processor operation but an i64 (which is not legal) requires two.  So the
11380   // transform should not be done in this case.
11381
11382   SDValue Tmp;
11383   switch (CFP->getSimpleValueType(0).SimpleTy) {
11384   default:
11385     llvm_unreachable("Unknown FP type");
11386   case MVT::f16:    // We don't do this for these yet.
11387   case MVT::f80:
11388   case MVT::f128:
11389   case MVT::ppcf128:
11390     return SDValue();
11391   case MVT::f32:
11392     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11393         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11394       ;
11395       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11396                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11397                             MVT::i32);
11398       SDValue NewSt = DAG.getStore(Chain, DL, Tmp,
11399                                    Ptr, ST->getMemOperand());
11400
11401       dbgs() << "Replacing FP constant: ";
11402       Value->dump(&DAG);
11403
11404       if (cast<StoreSDNode>(NewSt)->getMemoryVT() != MVT::i32) {
11405         dbgs() << "Different memoryvt\n";
11406       } else {
11407         dbgs() << "same memoryvt\n";
11408       }
11409
11410
11411       return NewSt;
11412     }
11413
11414     return SDValue();
11415   case MVT::f64:
11416     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11417          !ST->isVolatile()) ||
11418         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11419       ;
11420       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11421                             getZExtValue(), SDLoc(CFP), MVT::i64);
11422       return DAG.getStore(Chain, DL, Tmp,
11423                           Ptr, ST->getMemOperand());
11424     }
11425
11426     if (!ST->isVolatile() &&
11427         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11428       // Many FP stores are not made apparent until after legalize, e.g. for
11429       // argument passing.  Since this is so common, custom legalize the
11430       // 64-bit integer store into two 32-bit stores.
11431       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11432       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11433       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11434       if (DAG.getDataLayout().isBigEndian())
11435         std::swap(Lo, Hi);
11436
11437       unsigned Alignment = ST->getAlignment();
11438       bool isVolatile = ST->isVolatile();
11439       bool isNonTemporal = ST->isNonTemporal();
11440       AAMDNodes AAInfo = ST->getAAInfo();
11441
11442       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11443                                  Ptr, ST->getPointerInfo(),
11444                                  isVolatile, isNonTemporal,
11445                                  ST->getAlignment(), AAInfo);
11446       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11447                         DAG.getConstant(4, DL, Ptr.getValueType()));
11448       Alignment = MinAlign(Alignment, 4U);
11449       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11450                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11451                                  isVolatile, isNonTemporal,
11452                                  Alignment, AAInfo);
11453       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11454                          St0, St1);
11455     }
11456
11457     return SDValue();
11458   }
11459 }
11460
11461 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11462   StoreSDNode *ST  = cast<StoreSDNode>(N);
11463   SDValue Chain = ST->getChain();
11464   SDValue Value = ST->getValue();
11465   SDValue Ptr   = ST->getBasePtr();
11466
11467   // If this is a store of a bit convert, store the input value if the
11468   // resultant store does not need a higher alignment than the original.
11469   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11470       ST->isUnindexed()) {
11471     unsigned OrigAlign = ST->getAlignment();
11472     EVT SVT = Value.getOperand(0).getValueType();
11473     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11474         SVT.getTypeForEVT(*DAG.getContext()));
11475     if (Align <= OrigAlign &&
11476         ((!LegalOperations && !ST->isVolatile()) ||
11477          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11478       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11479                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11480                           ST->isNonTemporal(), OrigAlign,
11481                           ST->getAAInfo());
11482   }
11483
11484   // Turn 'store undef, Ptr' -> nothing.
11485   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11486     return Chain;
11487
11488   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11489   //
11490   // Make sure to do this only after attempting to merge stores in order to
11491   //  avoid changing the types of some subset of stores due to visit order,
11492   //  preventing their merging.
11493   if (isa<ConstantFPSDNode>(Value)) {
11494     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11495       return NewSt;
11496   }
11497
11498   // Try to infer better alignment information than the store already has.
11499   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11500     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11501       if (Align > ST->getAlignment()) {
11502         SDValue NewStore =
11503                DAG.getTruncStore(Chain, SDLoc(N), Value,
11504                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11505                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11506                                  ST->getAAInfo());
11507         if (NewStore.getNode() != N)
11508           return CombineTo(ST, NewStore, true);
11509       }
11510     }
11511   }
11512
11513   // Try transforming a pair floating point load / store ops to integer
11514   // load / store ops.
11515   if (SDValue NewST = TransformFPLoadStorePair(N))
11516     return NewST;
11517
11518   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11519                                                   : DAG.getSubtarget().useAA();
11520 #ifndef NDEBUG
11521   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11522       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11523     UseAA = false;
11524 #endif
11525   if (UseAA && ST->isUnindexed()) {
11526     // FIXME: We should do this even without AA enabled. AA will just allow
11527     // FindBetterChain to work in more situations. The problem with this is that
11528     // any combine that expects memory operations to be on consecutive chains
11529     // first needs to be updated to look for users of the same chain.
11530
11531     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11532     // adjacent stores.
11533     if (findBetterNeighborChains(ST)) {
11534       // replaceStoreChain uses CombineTo, which handled all of the worklist
11535       // manipulation. Return the original node to not do anything else.
11536       return SDValue(ST, 0);
11537     }
11538   }
11539
11540   // Try transforming N to an indexed store.
11541   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11542     return SDValue(N, 0);
11543
11544   // FIXME: is there such a thing as a truncating indexed store?
11545   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11546       Value.getValueType().isInteger()) {
11547     // See if we can simplify the input to this truncstore with knowledge that
11548     // only the low bits are being used.  For example:
11549     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11550     SDValue Shorter =
11551       GetDemandedBits(Value,
11552                       APInt::getLowBitsSet(
11553                         Value.getValueType().getScalarType().getSizeInBits(),
11554                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11555     AddToWorklist(Value.getNode());
11556     if (Shorter.getNode())
11557       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11558                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11559
11560     // Otherwise, see if we can simplify the operation with
11561     // SimplifyDemandedBits, which only works if the value has a single use.
11562     if (SimplifyDemandedBits(Value,
11563                         APInt::getLowBitsSet(
11564                           Value.getValueType().getScalarType().getSizeInBits(),
11565                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11566       return SDValue(N, 0);
11567   }
11568
11569   // If this is a load followed by a store to the same location, then the store
11570   // is dead/noop.
11571   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11572     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11573         ST->isUnindexed() && !ST->isVolatile() &&
11574         // There can't be any side effects between the load and store, such as
11575         // a call or store.
11576         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11577       // The store is dead, remove it.
11578       return Chain;
11579     }
11580   }
11581
11582   // If this is a store followed by a store with the same value to the same
11583   // location, then the store is dead/noop.
11584   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11585     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11586         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11587         ST1->isUnindexed() && !ST1->isVolatile()) {
11588       // The store is dead, remove it.
11589       return Chain;
11590     }
11591   }
11592
11593   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11594   // truncating store.  We can do this even if this is already a truncstore.
11595   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11596       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11597       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11598                             ST->getMemoryVT())) {
11599     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11600                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11601   }
11602
11603   // Only perform this optimization before the types are legal, because we
11604   // don't want to perform this optimization on every DAGCombine invocation.
11605   if (!LegalTypes) {
11606     bool EverChanged = false;
11607
11608     do {
11609       // There can be multiple store sequences on the same chain.
11610       // Keep trying to merge store sequences until we are unable to do so
11611       // or until we merge the last store on the chain.
11612       bool Changed = MergeConsecutiveStores(ST);
11613       EverChanged |= Changed;
11614       if (!Changed) break;
11615     } while (ST->getOpcode() != ISD::DELETED_NODE);
11616
11617     if (EverChanged)
11618       return SDValue(N, 0);
11619   }
11620
11621   return ReduceLoadOpStoreWidth(N);
11622 }
11623
11624 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11625   SDValue InVec = N->getOperand(0);
11626   SDValue InVal = N->getOperand(1);
11627   SDValue EltNo = N->getOperand(2);
11628   SDLoc dl(N);
11629
11630   // If the inserted element is an UNDEF, just use the input vector.
11631   if (InVal.getOpcode() == ISD::UNDEF)
11632     return InVec;
11633
11634   EVT VT = InVec.getValueType();
11635
11636   // If we can't generate a legal BUILD_VECTOR, exit
11637   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11638     return SDValue();
11639
11640   // Check that we know which element is being inserted
11641   if (!isa<ConstantSDNode>(EltNo))
11642     return SDValue();
11643   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11644
11645   // Canonicalize insert_vector_elt dag nodes.
11646   // Example:
11647   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11648   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11649   //
11650   // Do this only if the child insert_vector node has one use; also
11651   // do this only if indices are both constants and Idx1 < Idx0.
11652   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11653       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11654     unsigned OtherElt =
11655       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11656     if (Elt < OtherElt) {
11657       // Swap nodes.
11658       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11659                                   InVec.getOperand(0), InVal, EltNo);
11660       AddToWorklist(NewOp.getNode());
11661       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11662                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11663     }
11664   }
11665
11666   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11667   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11668   // vector elements.
11669   SmallVector<SDValue, 8> Ops;
11670   // Do not combine these two vectors if the output vector will not replace
11671   // the input vector.
11672   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11673     Ops.append(InVec.getNode()->op_begin(),
11674                InVec.getNode()->op_end());
11675   } else if (InVec.getOpcode() == ISD::UNDEF) {
11676     unsigned NElts = VT.getVectorNumElements();
11677     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11678   } else {
11679     return SDValue();
11680   }
11681
11682   // Insert the element
11683   if (Elt < Ops.size()) {
11684     // All the operands of BUILD_VECTOR must have the same type;
11685     // we enforce that here.
11686     EVT OpVT = Ops[0].getValueType();
11687     if (InVal.getValueType() != OpVT)
11688       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11689                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11690                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11691     Ops[Elt] = InVal;
11692   }
11693
11694   // Return the new vector
11695   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11696 }
11697
11698 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11699     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11700   EVT ResultVT = EVE->getValueType(0);
11701   EVT VecEltVT = InVecVT.getVectorElementType();
11702   unsigned Align = OriginalLoad->getAlignment();
11703   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11704       VecEltVT.getTypeForEVT(*DAG.getContext()));
11705
11706   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11707     return SDValue();
11708
11709   Align = NewAlign;
11710
11711   SDValue NewPtr = OriginalLoad->getBasePtr();
11712   SDValue Offset;
11713   EVT PtrType = NewPtr.getValueType();
11714   MachinePointerInfo MPI;
11715   SDLoc DL(EVE);
11716   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11717     int Elt = ConstEltNo->getZExtValue();
11718     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11719     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11720     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11721   } else {
11722     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11723     Offset = DAG.getNode(
11724         ISD::MUL, DL, PtrType, Offset,
11725         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11726     MPI = OriginalLoad->getPointerInfo();
11727   }
11728   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11729
11730   // The replacement we need to do here is a little tricky: we need to
11731   // replace an extractelement of a load with a load.
11732   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11733   // Note that this replacement assumes that the extractvalue is the only
11734   // use of the load; that's okay because we don't want to perform this
11735   // transformation in other cases anyway.
11736   SDValue Load;
11737   SDValue Chain;
11738   if (ResultVT.bitsGT(VecEltVT)) {
11739     // If the result type of vextract is wider than the load, then issue an
11740     // extending load instead.
11741     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11742                                                   VecEltVT)
11743                                    ? ISD::ZEXTLOAD
11744                                    : ISD::EXTLOAD;
11745     Load = DAG.getExtLoad(
11746         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11747         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11748         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11749     Chain = Load.getValue(1);
11750   } else {
11751     Load = DAG.getLoad(
11752         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11753         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11754         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11755     Chain = Load.getValue(1);
11756     if (ResultVT.bitsLT(VecEltVT))
11757       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11758     else
11759       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11760   }
11761   WorklistRemover DeadNodes(*this);
11762   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11763   SDValue To[] = { Load, Chain };
11764   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11765   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11766   // worklist explicitly as well.
11767   AddToWorklist(Load.getNode());
11768   AddUsersToWorklist(Load.getNode()); // Add users too
11769   // Make sure to revisit this node to clean it up; it will usually be dead.
11770   AddToWorklist(EVE);
11771   ++OpsNarrowed;
11772   return SDValue(EVE, 0);
11773 }
11774
11775 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11776   // (vextract (scalar_to_vector val, 0) -> val
11777   SDValue InVec = N->getOperand(0);
11778   EVT VT = InVec.getValueType();
11779   EVT NVT = N->getValueType(0);
11780
11781   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11782     // Check if the result type doesn't match the inserted element type. A
11783     // SCALAR_TO_VECTOR may truncate the inserted element and the
11784     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11785     SDValue InOp = InVec.getOperand(0);
11786     if (InOp.getValueType() != NVT) {
11787       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11788       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11789     }
11790     return InOp;
11791   }
11792
11793   SDValue EltNo = N->getOperand(1);
11794   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11795
11796   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11797   // We only perform this optimization before the op legalization phase because
11798   // we may introduce new vector instructions which are not backed by TD
11799   // patterns. For example on AVX, extracting elements from a wide vector
11800   // without using extract_subvector. However, if we can find an underlying
11801   // scalar value, then we can always use that.
11802   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11803       && ConstEltNo) {
11804     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11805     int NumElem = VT.getVectorNumElements();
11806     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11807     // Find the new index to extract from.
11808     int OrigElt = SVOp->getMaskElt(Elt);
11809
11810     // Extracting an undef index is undef.
11811     if (OrigElt == -1)
11812       return DAG.getUNDEF(NVT);
11813
11814     // Select the right vector half to extract from.
11815     SDValue SVInVec;
11816     if (OrigElt < NumElem) {
11817       SVInVec = InVec->getOperand(0);
11818     } else {
11819       SVInVec = InVec->getOperand(1);
11820       OrigElt -= NumElem;
11821     }
11822
11823     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11824       SDValue InOp = SVInVec.getOperand(OrigElt);
11825       if (InOp.getValueType() != NVT) {
11826         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11827         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11828       }
11829
11830       return InOp;
11831     }
11832
11833     // FIXME: We should handle recursing on other vector shuffles and
11834     // scalar_to_vector here as well.
11835
11836     if (!LegalOperations) {
11837       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11838       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11839                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11840     }
11841   }
11842
11843   bool BCNumEltsChanged = false;
11844   EVT ExtVT = VT.getVectorElementType();
11845   EVT LVT = ExtVT;
11846
11847   // If the result of load has to be truncated, then it's not necessarily
11848   // profitable.
11849   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11850     return SDValue();
11851
11852   if (InVec.getOpcode() == ISD::BITCAST) {
11853     // Don't duplicate a load with other uses.
11854     if (!InVec.hasOneUse())
11855       return SDValue();
11856
11857     EVT BCVT = InVec.getOperand(0).getValueType();
11858     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11859       return SDValue();
11860     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11861       BCNumEltsChanged = true;
11862     InVec = InVec.getOperand(0);
11863     ExtVT = BCVT.getVectorElementType();
11864   }
11865
11866   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11867   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11868       ISD::isNormalLoad(InVec.getNode()) &&
11869       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11870     SDValue Index = N->getOperand(1);
11871     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11872       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11873                                                            OrigLoad);
11874   }
11875
11876   // Perform only after legalization to ensure build_vector / vector_shuffle
11877   // optimizations have already been done.
11878   if (!LegalOperations) return SDValue();
11879
11880   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11881   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11882   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11883
11884   if (ConstEltNo) {
11885     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11886
11887     LoadSDNode *LN0 = nullptr;
11888     const ShuffleVectorSDNode *SVN = nullptr;
11889     if (ISD::isNormalLoad(InVec.getNode())) {
11890       LN0 = cast<LoadSDNode>(InVec);
11891     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11892                InVec.getOperand(0).getValueType() == ExtVT &&
11893                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11894       // Don't duplicate a load with other uses.
11895       if (!InVec.hasOneUse())
11896         return SDValue();
11897
11898       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11899     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11900       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11901       // =>
11902       // (load $addr+1*size)
11903
11904       // Don't duplicate a load with other uses.
11905       if (!InVec.hasOneUse())
11906         return SDValue();
11907
11908       // If the bit convert changed the number of elements, it is unsafe
11909       // to examine the mask.
11910       if (BCNumEltsChanged)
11911         return SDValue();
11912
11913       // Select the input vector, guarding against out of range extract vector.
11914       unsigned NumElems = VT.getVectorNumElements();
11915       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11916       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11917
11918       if (InVec.getOpcode() == ISD::BITCAST) {
11919         // Don't duplicate a load with other uses.
11920         if (!InVec.hasOneUse())
11921           return SDValue();
11922
11923         InVec = InVec.getOperand(0);
11924       }
11925       if (ISD::isNormalLoad(InVec.getNode())) {
11926         LN0 = cast<LoadSDNode>(InVec);
11927         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11928         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11929       }
11930     }
11931
11932     // Make sure we found a non-volatile load and the extractelement is
11933     // the only use.
11934     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11935       return SDValue();
11936
11937     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11938     if (Elt == -1)
11939       return DAG.getUNDEF(LVT);
11940
11941     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11942   }
11943
11944   return SDValue();
11945 }
11946
11947 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11948 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11949   // We perform this optimization post type-legalization because
11950   // the type-legalizer often scalarizes integer-promoted vectors.
11951   // Performing this optimization before may create bit-casts which
11952   // will be type-legalized to complex code sequences.
11953   // We perform this optimization only before the operation legalizer because we
11954   // may introduce illegal operations.
11955   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11956     return SDValue();
11957
11958   unsigned NumInScalars = N->getNumOperands();
11959   SDLoc dl(N);
11960   EVT VT = N->getValueType(0);
11961
11962   // Check to see if this is a BUILD_VECTOR of a bunch of values
11963   // which come from any_extend or zero_extend nodes. If so, we can create
11964   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11965   // optimizations. We do not handle sign-extend because we can't fill the sign
11966   // using shuffles.
11967   EVT SourceType = MVT::Other;
11968   bool AllAnyExt = true;
11969
11970   for (unsigned i = 0; i != NumInScalars; ++i) {
11971     SDValue In = N->getOperand(i);
11972     // Ignore undef inputs.
11973     if (In.getOpcode() == ISD::UNDEF) continue;
11974
11975     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11976     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11977
11978     // Abort if the element is not an extension.
11979     if (!ZeroExt && !AnyExt) {
11980       SourceType = MVT::Other;
11981       break;
11982     }
11983
11984     // The input is a ZeroExt or AnyExt. Check the original type.
11985     EVT InTy = In.getOperand(0).getValueType();
11986
11987     // Check that all of the widened source types are the same.
11988     if (SourceType == MVT::Other)
11989       // First time.
11990       SourceType = InTy;
11991     else if (InTy != SourceType) {
11992       // Multiple income types. Abort.
11993       SourceType = MVT::Other;
11994       break;
11995     }
11996
11997     // Check if all of the extends are ANY_EXTENDs.
11998     AllAnyExt &= AnyExt;
11999   }
12000
12001   // In order to have valid types, all of the inputs must be extended from the
12002   // same source type and all of the inputs must be any or zero extend.
12003   // Scalar sizes must be a power of two.
12004   EVT OutScalarTy = VT.getScalarType();
12005   bool ValidTypes = SourceType != MVT::Other &&
12006                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12007                  isPowerOf2_32(SourceType.getSizeInBits());
12008
12009   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12010   // turn into a single shuffle instruction.
12011   if (!ValidTypes)
12012     return SDValue();
12013
12014   bool isLE = DAG.getDataLayout().isLittleEndian();
12015   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12016   assert(ElemRatio > 1 && "Invalid element size ratio");
12017   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12018                                DAG.getConstant(0, SDLoc(N), SourceType);
12019
12020   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12021   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12022
12023   // Populate the new build_vector
12024   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12025     SDValue Cast = N->getOperand(i);
12026     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12027             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12028             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12029     SDValue In;
12030     if (Cast.getOpcode() == ISD::UNDEF)
12031       In = DAG.getUNDEF(SourceType);
12032     else
12033       In = Cast->getOperand(0);
12034     unsigned Index = isLE ? (i * ElemRatio) :
12035                             (i * ElemRatio + (ElemRatio - 1));
12036
12037     assert(Index < Ops.size() && "Invalid index");
12038     Ops[Index] = In;
12039   }
12040
12041   // The type of the new BUILD_VECTOR node.
12042   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12043   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12044          "Invalid vector size");
12045   // Check if the new vector type is legal.
12046   if (!isTypeLegal(VecVT)) return SDValue();
12047
12048   // Make the new BUILD_VECTOR.
12049   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12050
12051   // The new BUILD_VECTOR node has the potential to be further optimized.
12052   AddToWorklist(BV.getNode());
12053   // Bitcast to the desired type.
12054   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12055 }
12056
12057 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12058   EVT VT = N->getValueType(0);
12059
12060   unsigned NumInScalars = N->getNumOperands();
12061   SDLoc dl(N);
12062
12063   EVT SrcVT = MVT::Other;
12064   unsigned Opcode = ISD::DELETED_NODE;
12065   unsigned NumDefs = 0;
12066
12067   for (unsigned i = 0; i != NumInScalars; ++i) {
12068     SDValue In = N->getOperand(i);
12069     unsigned Opc = In.getOpcode();
12070
12071     if (Opc == ISD::UNDEF)
12072       continue;
12073
12074     // If all scalar values are floats and converted from integers.
12075     if (Opcode == ISD::DELETED_NODE &&
12076         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12077       Opcode = Opc;
12078     }
12079
12080     if (Opc != Opcode)
12081       return SDValue();
12082
12083     EVT InVT = In.getOperand(0).getValueType();
12084
12085     // If all scalar values are typed differently, bail out. It's chosen to
12086     // simplify BUILD_VECTOR of integer types.
12087     if (SrcVT == MVT::Other)
12088       SrcVT = InVT;
12089     if (SrcVT != InVT)
12090       return SDValue();
12091     NumDefs++;
12092   }
12093
12094   // If the vector has just one element defined, it's not worth to fold it into
12095   // a vectorized one.
12096   if (NumDefs < 2)
12097     return SDValue();
12098
12099   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12100          && "Should only handle conversion from integer to float.");
12101   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12102
12103   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12104
12105   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12106     return SDValue();
12107
12108   // Just because the floating-point vector type is legal does not necessarily
12109   // mean that the corresponding integer vector type is.
12110   if (!isTypeLegal(NVT))
12111     return SDValue();
12112
12113   SmallVector<SDValue, 8> Opnds;
12114   for (unsigned i = 0; i != NumInScalars; ++i) {
12115     SDValue In = N->getOperand(i);
12116
12117     if (In.getOpcode() == ISD::UNDEF)
12118       Opnds.push_back(DAG.getUNDEF(SrcVT));
12119     else
12120       Opnds.push_back(In.getOperand(0));
12121   }
12122   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12123   AddToWorklist(BV.getNode());
12124
12125   return DAG.getNode(Opcode, dl, VT, BV);
12126 }
12127
12128 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12129   unsigned NumInScalars = N->getNumOperands();
12130   SDLoc dl(N);
12131   EVT VT = N->getValueType(0);
12132
12133   // A vector built entirely of undefs is undef.
12134   if (ISD::allOperandsUndef(N))
12135     return DAG.getUNDEF(VT);
12136
12137   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12138     return V;
12139
12140   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12141     return V;
12142
12143   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12144   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12145   // at most two distinct vectors, turn this into a shuffle node.
12146
12147   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12148   if (!isTypeLegal(VT))
12149     return SDValue();
12150
12151   // May only combine to shuffle after legalize if shuffle is legal.
12152   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12153     return SDValue();
12154
12155   SDValue VecIn1, VecIn2;
12156   bool UsesZeroVector = false;
12157   for (unsigned i = 0; i != NumInScalars; ++i) {
12158     SDValue Op = N->getOperand(i);
12159     // Ignore undef inputs.
12160     if (Op.getOpcode() == ISD::UNDEF) continue;
12161
12162     // See if we can combine this build_vector into a blend with a zero vector.
12163     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12164       UsesZeroVector = true;
12165       continue;
12166     }
12167
12168     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12169     // constant index, bail out.
12170     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12171         !isa<ConstantSDNode>(Op.getOperand(1))) {
12172       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12173       break;
12174     }
12175
12176     // We allow up to two distinct input vectors.
12177     SDValue ExtractedFromVec = Op.getOperand(0);
12178     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12179       continue;
12180
12181     if (!VecIn1.getNode()) {
12182       VecIn1 = ExtractedFromVec;
12183     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12184       VecIn2 = ExtractedFromVec;
12185     } else {
12186       // Too many inputs.
12187       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12188       break;
12189     }
12190   }
12191
12192   // If everything is good, we can make a shuffle operation.
12193   if (VecIn1.getNode()) {
12194     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12195     SmallVector<int, 8> Mask;
12196     for (unsigned i = 0; i != NumInScalars; ++i) {
12197       unsigned Opcode = N->getOperand(i).getOpcode();
12198       if (Opcode == ISD::UNDEF) {
12199         Mask.push_back(-1);
12200         continue;
12201       }
12202
12203       // Operands can also be zero.
12204       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12205         assert(UsesZeroVector &&
12206                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12207                "Unexpected node found!");
12208         Mask.push_back(NumInScalars+i);
12209         continue;
12210       }
12211
12212       // If extracting from the first vector, just use the index directly.
12213       SDValue Extract = N->getOperand(i);
12214       SDValue ExtVal = Extract.getOperand(1);
12215       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12216       if (Extract.getOperand(0) == VecIn1) {
12217         Mask.push_back(ExtIndex);
12218         continue;
12219       }
12220
12221       // Otherwise, use InIdx + InputVecSize
12222       Mask.push_back(InNumElements + ExtIndex);
12223     }
12224
12225     // Avoid introducing illegal shuffles with zero.
12226     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12227       return SDValue();
12228
12229     // We can't generate a shuffle node with mismatched input and output types.
12230     // Attempt to transform a single input vector to the correct type.
12231     if ((VT != VecIn1.getValueType())) {
12232       // If the input vector type has a different base type to the output
12233       // vector type, bail out.
12234       EVT VTElemType = VT.getVectorElementType();
12235       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12236           (VecIn2.getNode() &&
12237            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12238         return SDValue();
12239
12240       // If the input vector is too small, widen it.
12241       // We only support widening of vectors which are half the size of the
12242       // output registers. For example XMM->YMM widening on X86 with AVX.
12243       EVT VecInT = VecIn1.getValueType();
12244       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12245         // If we only have one small input, widen it by adding undef values.
12246         if (!VecIn2.getNode())
12247           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12248                                DAG.getUNDEF(VecIn1.getValueType()));
12249         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12250           // If we have two small inputs of the same type, try to concat them.
12251           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12252           VecIn2 = SDValue(nullptr, 0);
12253         } else
12254           return SDValue();
12255       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12256         // If the input vector is too large, try to split it.
12257         // We don't support having two input vectors that are too large.
12258         // If the zero vector was used, we can not split the vector,
12259         // since we'd need 3 inputs.
12260         if (UsesZeroVector || VecIn2.getNode())
12261           return SDValue();
12262
12263         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12264           return SDValue();
12265
12266         // Try to replace VecIn1 with two extract_subvectors
12267         // No need to update the masks, they should still be correct.
12268         VecIn2 = DAG.getNode(
12269             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12270             DAG.getConstant(VT.getVectorNumElements(), dl,
12271                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12272         VecIn1 = DAG.getNode(
12273             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12274             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12275       } else
12276         return SDValue();
12277     }
12278
12279     if (UsesZeroVector)
12280       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12281                                 DAG.getConstantFP(0.0, dl, VT);
12282     else
12283       // If VecIn2 is unused then change it to undef.
12284       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12285
12286     // Check that we were able to transform all incoming values to the same
12287     // type.
12288     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12289         VecIn1.getValueType() != VT)
12290           return SDValue();
12291
12292     // Return the new VECTOR_SHUFFLE node.
12293     SDValue Ops[2];
12294     Ops[0] = VecIn1;
12295     Ops[1] = VecIn2;
12296     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12297   }
12298
12299   return SDValue();
12300 }
12301
12302 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12303   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12304   EVT OpVT = N->getOperand(0).getValueType();
12305
12306   // If the operands are legal vectors, leave them alone.
12307   if (TLI.isTypeLegal(OpVT))
12308     return SDValue();
12309
12310   SDLoc DL(N);
12311   EVT VT = N->getValueType(0);
12312   SmallVector<SDValue, 8> Ops;
12313
12314   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12315   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12316
12317   // Keep track of what we encounter.
12318   bool AnyInteger = false;
12319   bool AnyFP = false;
12320   for (const SDValue &Op : N->ops()) {
12321     if (ISD::BITCAST == Op.getOpcode() &&
12322         !Op.getOperand(0).getValueType().isVector())
12323       Ops.push_back(Op.getOperand(0));
12324     else if (ISD::UNDEF == Op.getOpcode())
12325       Ops.push_back(ScalarUndef);
12326     else
12327       return SDValue();
12328
12329     // Note whether we encounter an integer or floating point scalar.
12330     // If it's neither, bail out, it could be something weird like x86mmx.
12331     EVT LastOpVT = Ops.back().getValueType();
12332     if (LastOpVT.isFloatingPoint())
12333       AnyFP = true;
12334     else if (LastOpVT.isInteger())
12335       AnyInteger = true;
12336     else
12337       return SDValue();
12338   }
12339
12340   // If any of the operands is a floating point scalar bitcast to a vector,
12341   // use floating point types throughout, and bitcast everything.
12342   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12343   if (AnyFP) {
12344     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12345     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12346     if (AnyInteger) {
12347       for (SDValue &Op : Ops) {
12348         if (Op.getValueType() == SVT)
12349           continue;
12350         if (Op.getOpcode() == ISD::UNDEF)
12351           Op = ScalarUndef;
12352         else
12353           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12354       }
12355     }
12356   }
12357
12358   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12359                                VT.getSizeInBits() / SVT.getSizeInBits());
12360   return DAG.getNode(ISD::BITCAST, DL, VT,
12361                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12362 }
12363
12364 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12365 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12366 // most two distinct vectors the same size as the result, attempt to turn this
12367 // into a legal shuffle.
12368 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12369   EVT VT = N->getValueType(0);
12370   EVT OpVT = N->getOperand(0).getValueType();
12371   int NumElts = VT.getVectorNumElements();
12372   int NumOpElts = OpVT.getVectorNumElements();
12373
12374   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12375   SmallVector<int, 8> Mask;
12376
12377   for (SDValue Op : N->ops()) {
12378     // Peek through any bitcast.
12379     while (Op.getOpcode() == ISD::BITCAST)
12380       Op = Op.getOperand(0);
12381
12382     // UNDEF nodes convert to UNDEF shuffle mask values.
12383     if (Op.getOpcode() == ISD::UNDEF) {
12384       Mask.append((unsigned)NumOpElts, -1);
12385       continue;
12386     }
12387
12388     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12389       return SDValue();
12390
12391     // What vector are we extracting the subvector from and at what index?
12392     SDValue ExtVec = Op.getOperand(0);
12393
12394     // We want the EVT of the original extraction to correctly scale the
12395     // extraction index.
12396     EVT ExtVT = ExtVec.getValueType();
12397
12398     // Peek through any bitcast.
12399     while (ExtVec.getOpcode() == ISD::BITCAST)
12400       ExtVec = ExtVec.getOperand(0);
12401
12402     // UNDEF nodes convert to UNDEF shuffle mask values.
12403     if (ExtVec.getOpcode() == ISD::UNDEF) {
12404       Mask.append((unsigned)NumOpElts, -1);
12405       continue;
12406     }
12407
12408     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12409       return SDValue();
12410     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12411
12412     // Ensure that we are extracting a subvector from a vector the same
12413     // size as the result.
12414     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12415       return SDValue();
12416
12417     // Scale the subvector index to account for any bitcast.
12418     int NumExtElts = ExtVT.getVectorNumElements();
12419     if (0 == (NumExtElts % NumElts))
12420       ExtIdx /= (NumExtElts / NumElts);
12421     else if (0 == (NumElts % NumExtElts))
12422       ExtIdx *= (NumElts / NumExtElts);
12423     else
12424       return SDValue();
12425
12426     // At most we can reference 2 inputs in the final shuffle.
12427     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12428       SV0 = ExtVec;
12429       for (int i = 0; i != NumOpElts; ++i)
12430         Mask.push_back(i + ExtIdx);
12431     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12432       SV1 = ExtVec;
12433       for (int i = 0; i != NumOpElts; ++i)
12434         Mask.push_back(i + ExtIdx + NumElts);
12435     } else {
12436       return SDValue();
12437     }
12438   }
12439
12440   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12441     return SDValue();
12442
12443   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12444                               DAG.getBitcast(VT, SV1), Mask);
12445 }
12446
12447 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12448   // If we only have one input vector, we don't need to do any concatenation.
12449   if (N->getNumOperands() == 1)
12450     return N->getOperand(0);
12451
12452   // Check if all of the operands are undefs.
12453   EVT VT = N->getValueType(0);
12454   if (ISD::allOperandsUndef(N))
12455     return DAG.getUNDEF(VT);
12456
12457   // Optimize concat_vectors where all but the first of the vectors are undef.
12458   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12459         return Op.getOpcode() == ISD::UNDEF;
12460       })) {
12461     SDValue In = N->getOperand(0);
12462     assert(In.getValueType().isVector() && "Must concat vectors");
12463
12464     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12465     if (In->getOpcode() == ISD::BITCAST &&
12466         !In->getOperand(0)->getValueType(0).isVector()) {
12467       SDValue Scalar = In->getOperand(0);
12468
12469       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12470       // look through the trunc so we can still do the transform:
12471       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12472       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12473           !TLI.isTypeLegal(Scalar.getValueType()) &&
12474           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12475         Scalar = Scalar->getOperand(0);
12476
12477       EVT SclTy = Scalar->getValueType(0);
12478
12479       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12480         return SDValue();
12481
12482       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12483                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12484       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12485         return SDValue();
12486
12487       SDLoc dl = SDLoc(N);
12488       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12489       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12490     }
12491   }
12492
12493   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12494   // We have already tested above for an UNDEF only concatenation.
12495   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12496   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12497   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12498     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12499   };
12500   bool AllBuildVectorsOrUndefs =
12501       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12502   if (AllBuildVectorsOrUndefs) {
12503     SmallVector<SDValue, 8> Opnds;
12504     EVT SVT = VT.getScalarType();
12505
12506     EVT MinVT = SVT;
12507     if (!SVT.isFloatingPoint()) {
12508       // If BUILD_VECTOR are from built from integer, they may have different
12509       // operand types. Get the smallest type and truncate all operands to it.
12510       bool FoundMinVT = false;
12511       for (const SDValue &Op : N->ops())
12512         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12513           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12514           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12515           FoundMinVT = true;
12516         }
12517       assert(FoundMinVT && "Concat vector type mismatch");
12518     }
12519
12520     for (const SDValue &Op : N->ops()) {
12521       EVT OpVT = Op.getValueType();
12522       unsigned NumElts = OpVT.getVectorNumElements();
12523
12524       if (ISD::UNDEF == Op.getOpcode())
12525         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12526
12527       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12528         if (SVT.isFloatingPoint()) {
12529           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12530           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12531         } else {
12532           for (unsigned i = 0; i != NumElts; ++i)
12533             Opnds.push_back(
12534                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12535         }
12536       }
12537     }
12538
12539     assert(VT.getVectorNumElements() == Opnds.size() &&
12540            "Concat vector type mismatch");
12541     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12542   }
12543
12544   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12545   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12546     return V;
12547
12548   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12549   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12550     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12551       return V;
12552
12553   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12554   // nodes often generate nop CONCAT_VECTOR nodes.
12555   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12556   // place the incoming vectors at the exact same location.
12557   SDValue SingleSource = SDValue();
12558   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12559
12560   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12561     SDValue Op = N->getOperand(i);
12562
12563     if (Op.getOpcode() == ISD::UNDEF)
12564       continue;
12565
12566     // Check if this is the identity extract:
12567     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12568       return SDValue();
12569
12570     // Find the single incoming vector for the extract_subvector.
12571     if (SingleSource.getNode()) {
12572       if (Op.getOperand(0) != SingleSource)
12573         return SDValue();
12574     } else {
12575       SingleSource = Op.getOperand(0);
12576
12577       // Check the source type is the same as the type of the result.
12578       // If not, this concat may extend the vector, so we can not
12579       // optimize it away.
12580       if (SingleSource.getValueType() != N->getValueType(0))
12581         return SDValue();
12582     }
12583
12584     unsigned IdentityIndex = i * PartNumElem;
12585     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12586     // The extract index must be constant.
12587     if (!CS)
12588       return SDValue();
12589
12590     // Check that we are reading from the identity index.
12591     if (CS->getZExtValue() != IdentityIndex)
12592       return SDValue();
12593   }
12594
12595   if (SingleSource.getNode())
12596     return SingleSource;
12597
12598   return SDValue();
12599 }
12600
12601 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12602   EVT NVT = N->getValueType(0);
12603   SDValue V = N->getOperand(0);
12604
12605   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12606     // Combine:
12607     //    (extract_subvec (concat V1, V2, ...), i)
12608     // Into:
12609     //    Vi if possible
12610     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12611     // type.
12612     if (V->getOperand(0).getValueType() != NVT)
12613       return SDValue();
12614     unsigned Idx = N->getConstantOperandVal(1);
12615     unsigned NumElems = NVT.getVectorNumElements();
12616     assert((Idx % NumElems) == 0 &&
12617            "IDX in concat is not a multiple of the result vector length.");
12618     return V->getOperand(Idx / NumElems);
12619   }
12620
12621   // Skip bitcasting
12622   if (V->getOpcode() == ISD::BITCAST)
12623     V = V.getOperand(0);
12624
12625   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12626     SDLoc dl(N);
12627     // Handle only simple case where vector being inserted and vector
12628     // being extracted are of same type, and are half size of larger vectors.
12629     EVT BigVT = V->getOperand(0).getValueType();
12630     EVT SmallVT = V->getOperand(1).getValueType();
12631     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12632       return SDValue();
12633
12634     // Only handle cases where both indexes are constants with the same type.
12635     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12636     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12637
12638     if (InsIdx && ExtIdx &&
12639         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12640         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12641       // Combine:
12642       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12643       // Into:
12644       //    indices are equal or bit offsets are equal => V1
12645       //    otherwise => (extract_subvec V1, ExtIdx)
12646       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12647           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12648         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12649       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12650                          DAG.getNode(ISD::BITCAST, dl,
12651                                      N->getOperand(0).getValueType(),
12652                                      V->getOperand(0)), N->getOperand(1));
12653     }
12654   }
12655
12656   return SDValue();
12657 }
12658
12659 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12660                                                  SDValue V, SelectionDAG &DAG) {
12661   SDLoc DL(V);
12662   EVT VT = V.getValueType();
12663
12664   switch (V.getOpcode()) {
12665   default:
12666     return V;
12667
12668   case ISD::CONCAT_VECTORS: {
12669     EVT OpVT = V->getOperand(0).getValueType();
12670     int OpSize = OpVT.getVectorNumElements();
12671     SmallBitVector OpUsedElements(OpSize, false);
12672     bool FoundSimplification = false;
12673     SmallVector<SDValue, 4> NewOps;
12674     NewOps.reserve(V->getNumOperands());
12675     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12676       SDValue Op = V->getOperand(i);
12677       bool OpUsed = false;
12678       for (int j = 0; j < OpSize; ++j)
12679         if (UsedElements[i * OpSize + j]) {
12680           OpUsedElements[j] = true;
12681           OpUsed = true;
12682         }
12683       NewOps.push_back(
12684           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12685                  : DAG.getUNDEF(OpVT));
12686       FoundSimplification |= Op == NewOps.back();
12687       OpUsedElements.reset();
12688     }
12689     if (FoundSimplification)
12690       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12691     return V;
12692   }
12693
12694   case ISD::INSERT_SUBVECTOR: {
12695     SDValue BaseV = V->getOperand(0);
12696     SDValue SubV = V->getOperand(1);
12697     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12698     if (!IdxN)
12699       return V;
12700
12701     int SubSize = SubV.getValueType().getVectorNumElements();
12702     int Idx = IdxN->getZExtValue();
12703     bool SubVectorUsed = false;
12704     SmallBitVector SubUsedElements(SubSize, false);
12705     for (int i = 0; i < SubSize; ++i)
12706       if (UsedElements[i + Idx]) {
12707         SubVectorUsed = true;
12708         SubUsedElements[i] = true;
12709         UsedElements[i + Idx] = false;
12710       }
12711
12712     // Now recurse on both the base and sub vectors.
12713     SDValue SimplifiedSubV =
12714         SubVectorUsed
12715             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12716             : DAG.getUNDEF(SubV.getValueType());
12717     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12718     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12719       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12720                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12721     return V;
12722   }
12723   }
12724 }
12725
12726 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12727                                        SDValue N1, SelectionDAG &DAG) {
12728   EVT VT = SVN->getValueType(0);
12729   int NumElts = VT.getVectorNumElements();
12730   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12731   for (int M : SVN->getMask())
12732     if (M >= 0 && M < NumElts)
12733       N0UsedElements[M] = true;
12734     else if (M >= NumElts)
12735       N1UsedElements[M - NumElts] = true;
12736
12737   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12738   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12739   if (S0 == N0 && S1 == N1)
12740     return SDValue();
12741
12742   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12743 }
12744
12745 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12746 // or turn a shuffle of a single concat into simpler shuffle then concat.
12747 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12748   EVT VT = N->getValueType(0);
12749   unsigned NumElts = VT.getVectorNumElements();
12750
12751   SDValue N0 = N->getOperand(0);
12752   SDValue N1 = N->getOperand(1);
12753   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12754
12755   SmallVector<SDValue, 4> Ops;
12756   EVT ConcatVT = N0.getOperand(0).getValueType();
12757   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12758   unsigned NumConcats = NumElts / NumElemsPerConcat;
12759
12760   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12761   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12762   // half vector elements.
12763   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12764       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12765                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12766     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12767                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
12768     N1 = DAG.getUNDEF(ConcatVT);
12769     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12770   }
12771
12772   // Look at every vector that's inserted. We're looking for exact
12773   // subvector-sized copies from a concatenated vector
12774   for (unsigned I = 0; I != NumConcats; ++I) {
12775     // Make sure we're dealing with a copy.
12776     unsigned Begin = I * NumElemsPerConcat;
12777     bool AllUndef = true, NoUndef = true;
12778     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12779       if (SVN->getMaskElt(J) >= 0)
12780         AllUndef = false;
12781       else
12782         NoUndef = false;
12783     }
12784
12785     if (NoUndef) {
12786       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12787         return SDValue();
12788
12789       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12790         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12791           return SDValue();
12792
12793       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12794       if (FirstElt < N0.getNumOperands())
12795         Ops.push_back(N0.getOperand(FirstElt));
12796       else
12797         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12798
12799     } else if (AllUndef) {
12800       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12801     } else { // Mixed with general masks and undefs, can't do optimization.
12802       return SDValue();
12803     }
12804   }
12805
12806   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12807 }
12808
12809 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12810   EVT VT = N->getValueType(0);
12811   unsigned NumElts = VT.getVectorNumElements();
12812
12813   SDValue N0 = N->getOperand(0);
12814   SDValue N1 = N->getOperand(1);
12815
12816   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12817
12818   // Canonicalize shuffle undef, undef -> undef
12819   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12820     return DAG.getUNDEF(VT);
12821
12822   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12823
12824   // Canonicalize shuffle v, v -> v, undef
12825   if (N0 == N1) {
12826     SmallVector<int, 8> NewMask;
12827     for (unsigned i = 0; i != NumElts; ++i) {
12828       int Idx = SVN->getMaskElt(i);
12829       if (Idx >= (int)NumElts) Idx -= NumElts;
12830       NewMask.push_back(Idx);
12831     }
12832     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12833                                 &NewMask[0]);
12834   }
12835
12836   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12837   if (N0.getOpcode() == ISD::UNDEF) {
12838     SmallVector<int, 8> NewMask;
12839     for (unsigned i = 0; i != NumElts; ++i) {
12840       int Idx = SVN->getMaskElt(i);
12841       if (Idx >= 0) {
12842         if (Idx >= (int)NumElts)
12843           Idx -= NumElts;
12844         else
12845           Idx = -1; // remove reference to lhs
12846       }
12847       NewMask.push_back(Idx);
12848     }
12849     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12850                                 &NewMask[0]);
12851   }
12852
12853   // Remove references to rhs if it is undef
12854   if (N1.getOpcode() == ISD::UNDEF) {
12855     bool Changed = false;
12856     SmallVector<int, 8> NewMask;
12857     for (unsigned i = 0; i != NumElts; ++i) {
12858       int Idx = SVN->getMaskElt(i);
12859       if (Idx >= (int)NumElts) {
12860         Idx = -1;
12861         Changed = true;
12862       }
12863       NewMask.push_back(Idx);
12864     }
12865     if (Changed)
12866       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12867   }
12868
12869   // If it is a splat, check if the argument vector is another splat or a
12870   // build_vector.
12871   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12872     SDNode *V = N0.getNode();
12873
12874     // If this is a bit convert that changes the element type of the vector but
12875     // not the number of vector elements, look through it.  Be careful not to
12876     // look though conversions that change things like v4f32 to v2f64.
12877     if (V->getOpcode() == ISD::BITCAST) {
12878       SDValue ConvInput = V->getOperand(0);
12879       if (ConvInput.getValueType().isVector() &&
12880           ConvInput.getValueType().getVectorNumElements() == NumElts)
12881         V = ConvInput.getNode();
12882     }
12883
12884     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12885       assert(V->getNumOperands() == NumElts &&
12886              "BUILD_VECTOR has wrong number of operands");
12887       SDValue Base;
12888       bool AllSame = true;
12889       for (unsigned i = 0; i != NumElts; ++i) {
12890         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12891           Base = V->getOperand(i);
12892           break;
12893         }
12894       }
12895       // Splat of <u, u, u, u>, return <u, u, u, u>
12896       if (!Base.getNode())
12897         return N0;
12898       for (unsigned i = 0; i != NumElts; ++i) {
12899         if (V->getOperand(i) != Base) {
12900           AllSame = false;
12901           break;
12902         }
12903       }
12904       // Splat of <x, x, x, x>, return <x, x, x, x>
12905       if (AllSame)
12906         return N0;
12907
12908       // Canonicalize any other splat as a build_vector.
12909       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12910       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12911       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12912                                   V->getValueType(0), Ops);
12913
12914       // We may have jumped through bitcasts, so the type of the
12915       // BUILD_VECTOR may not match the type of the shuffle.
12916       if (V->getValueType(0) != VT)
12917         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12918       return NewBV;
12919     }
12920   }
12921
12922   // There are various patterns used to build up a vector from smaller vectors,
12923   // subvectors, or elements. Scan chains of these and replace unused insertions
12924   // or components with undef.
12925   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12926     return S;
12927
12928   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12929       Level < AfterLegalizeVectorOps &&
12930       (N1.getOpcode() == ISD::UNDEF ||
12931       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12932        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12933     SDValue V = partitionShuffleOfConcats(N, DAG);
12934
12935     if (V.getNode())
12936       return V;
12937   }
12938
12939   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12940   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12941   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12942     SmallVector<SDValue, 8> Ops;
12943     for (int M : SVN->getMask()) {
12944       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12945       if (M >= 0) {
12946         int Idx = M % NumElts;
12947         SDValue &S = (M < (int)NumElts ? N0 : N1);
12948         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12949           Op = S.getOperand(Idx);
12950         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12951           if (Idx == 0)
12952             Op = S.getOperand(0);
12953         } else {
12954           // Operand can't be combined - bail out.
12955           break;
12956         }
12957       }
12958       Ops.push_back(Op);
12959     }
12960     if (Ops.size() == VT.getVectorNumElements()) {
12961       // BUILD_VECTOR requires all inputs to be of the same type, find the
12962       // maximum type and extend them all.
12963       EVT SVT = VT.getScalarType();
12964       if (SVT.isInteger())
12965         for (SDValue &Op : Ops)
12966           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12967       if (SVT != VT.getScalarType())
12968         for (SDValue &Op : Ops)
12969           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12970                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12971                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12972       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12973     }
12974   }
12975
12976   // If this shuffle only has a single input that is a bitcasted shuffle,
12977   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12978   // back to their original types.
12979   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12980       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12981       TLI.isTypeLegal(VT)) {
12982
12983     // Peek through the bitcast only if there is one user.
12984     SDValue BC0 = N0;
12985     while (BC0.getOpcode() == ISD::BITCAST) {
12986       if (!BC0.hasOneUse())
12987         break;
12988       BC0 = BC0.getOperand(0);
12989     }
12990
12991     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12992       if (Scale == 1)
12993         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12994
12995       SmallVector<int, 8> NewMask;
12996       for (int M : Mask)
12997         for (int s = 0; s != Scale; ++s)
12998           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12999       return NewMask;
13000     };
13001
13002     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13003       EVT SVT = VT.getScalarType();
13004       EVT InnerVT = BC0->getValueType(0);
13005       EVT InnerSVT = InnerVT.getScalarType();
13006
13007       // Determine which shuffle works with the smaller scalar type.
13008       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13009       EVT ScaleSVT = ScaleVT.getScalarType();
13010
13011       if (TLI.isTypeLegal(ScaleVT) &&
13012           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13013           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13014
13015         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13016         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13017
13018         // Scale the shuffle masks to the smaller scalar type.
13019         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13020         SmallVector<int, 8> InnerMask =
13021             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13022         SmallVector<int, 8> OuterMask =
13023             ScaleShuffleMask(SVN->getMask(), OuterScale);
13024
13025         // Merge the shuffle masks.
13026         SmallVector<int, 8> NewMask;
13027         for (int M : OuterMask)
13028           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13029
13030         // Test for shuffle mask legality over both commutations.
13031         SDValue SV0 = BC0->getOperand(0);
13032         SDValue SV1 = BC0->getOperand(1);
13033         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13034         if (!LegalMask) {
13035           std::swap(SV0, SV1);
13036           ShuffleVectorSDNode::commuteMask(NewMask);
13037           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13038         }
13039
13040         if (LegalMask) {
13041           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13042           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13043           return DAG.getNode(
13044               ISD::BITCAST, SDLoc(N), VT,
13045               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13046         }
13047       }
13048     }
13049   }
13050
13051   // Canonicalize shuffles according to rules:
13052   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13053   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13054   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13055   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13056       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13057       TLI.isTypeLegal(VT)) {
13058     // The incoming shuffle must be of the same type as the result of the
13059     // current shuffle.
13060     assert(N1->getOperand(0).getValueType() == VT &&
13061            "Shuffle types don't match");
13062
13063     SDValue SV0 = N1->getOperand(0);
13064     SDValue SV1 = N1->getOperand(1);
13065     bool HasSameOp0 = N0 == SV0;
13066     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13067     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13068       // Commute the operands of this shuffle so that next rule
13069       // will trigger.
13070       return DAG.getCommutedVectorShuffle(*SVN);
13071   }
13072
13073   // Try to fold according to rules:
13074   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13075   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13076   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13077   // Don't try to fold shuffles with illegal type.
13078   // Only fold if this shuffle is the only user of the other shuffle.
13079   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13080       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13081     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13082
13083     // The incoming shuffle must be of the same type as the result of the
13084     // current shuffle.
13085     assert(OtherSV->getOperand(0).getValueType() == VT &&
13086            "Shuffle types don't match");
13087
13088     SDValue SV0, SV1;
13089     SmallVector<int, 4> Mask;
13090     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13091     // operand, and SV1 as the second operand.
13092     for (unsigned i = 0; i != NumElts; ++i) {
13093       int Idx = SVN->getMaskElt(i);
13094       if (Idx < 0) {
13095         // Propagate Undef.
13096         Mask.push_back(Idx);
13097         continue;
13098       }
13099
13100       SDValue CurrentVec;
13101       if (Idx < (int)NumElts) {
13102         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13103         // shuffle mask to identify which vector is actually referenced.
13104         Idx = OtherSV->getMaskElt(Idx);
13105         if (Idx < 0) {
13106           // Propagate Undef.
13107           Mask.push_back(Idx);
13108           continue;
13109         }
13110
13111         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13112                                            : OtherSV->getOperand(1);
13113       } else {
13114         // This shuffle index references an element within N1.
13115         CurrentVec = N1;
13116       }
13117
13118       // Simple case where 'CurrentVec' is UNDEF.
13119       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13120         Mask.push_back(-1);
13121         continue;
13122       }
13123
13124       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13125       // will be the first or second operand of the combined shuffle.
13126       Idx = Idx % NumElts;
13127       if (!SV0.getNode() || SV0 == CurrentVec) {
13128         // Ok. CurrentVec is the left hand side.
13129         // Update the mask accordingly.
13130         SV0 = CurrentVec;
13131         Mask.push_back(Idx);
13132         continue;
13133       }
13134
13135       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13136       if (SV1.getNode() && SV1 != CurrentVec)
13137         return SDValue();
13138
13139       // Ok. CurrentVec is the right hand side.
13140       // Update the mask accordingly.
13141       SV1 = CurrentVec;
13142       Mask.push_back(Idx + NumElts);
13143     }
13144
13145     // Check if all indices in Mask are Undef. In case, propagate Undef.
13146     bool isUndefMask = true;
13147     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13148       isUndefMask &= Mask[i] < 0;
13149
13150     if (isUndefMask)
13151       return DAG.getUNDEF(VT);
13152
13153     if (!SV0.getNode())
13154       SV0 = DAG.getUNDEF(VT);
13155     if (!SV1.getNode())
13156       SV1 = DAG.getUNDEF(VT);
13157
13158     // Avoid introducing shuffles with illegal mask.
13159     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13160       ShuffleVectorSDNode::commuteMask(Mask);
13161
13162       if (!TLI.isShuffleMaskLegal(Mask, VT))
13163         return SDValue();
13164
13165       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13166       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13167       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13168       std::swap(SV0, SV1);
13169     }
13170
13171     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13172     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13173     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13174     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13175   }
13176
13177   return SDValue();
13178 }
13179
13180 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13181   SDValue InVal = N->getOperand(0);
13182   EVT VT = N->getValueType(0);
13183
13184   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13185   // with a VECTOR_SHUFFLE.
13186   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13187     SDValue InVec = InVal->getOperand(0);
13188     SDValue EltNo = InVal->getOperand(1);
13189
13190     // FIXME: We could support implicit truncation if the shuffle can be
13191     // scaled to a smaller vector scalar type.
13192     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13193     if (C0 && VT == InVec.getValueType() &&
13194         VT.getScalarType() == InVal.getValueType()) {
13195       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13196       int Elt = C0->getZExtValue();
13197       NewMask[0] = Elt;
13198
13199       if (TLI.isShuffleMaskLegal(NewMask, VT))
13200         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13201                                     NewMask);
13202     }
13203   }
13204
13205   return SDValue();
13206 }
13207
13208 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13209   SDValue N0 = N->getOperand(0);
13210   SDValue N2 = N->getOperand(2);
13211
13212   // If the input vector is a concatenation, and the insert replaces
13213   // one of the halves, we can optimize into a single concat_vectors.
13214   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13215       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13216     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13217     EVT VT = N->getValueType(0);
13218
13219     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13220     // (concat_vectors Z, Y)
13221     if (InsIdx == 0)
13222       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13223                          N->getOperand(1), N0.getOperand(1));
13224
13225     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13226     // (concat_vectors X, Z)
13227     if (InsIdx == VT.getVectorNumElements()/2)
13228       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13229                          N0.getOperand(0), N->getOperand(1));
13230   }
13231
13232   return SDValue();
13233 }
13234
13235 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13236   SDValue N0 = N->getOperand(0);
13237
13238   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13239   if (N0->getOpcode() == ISD::FP16_TO_FP)
13240     return N0->getOperand(0);
13241
13242   return SDValue();
13243 }
13244
13245 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13246   SDValue N0 = N->getOperand(0);
13247
13248   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13249   if (N0->getOpcode() == ISD::AND) {
13250     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13251     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13252       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13253                          N0.getOperand(0));
13254     }
13255   }
13256
13257   return SDValue();
13258 }
13259
13260 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13261 /// with the destination vector and a zero vector.
13262 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13263 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13264 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13265   EVT VT = N->getValueType(0);
13266   SDValue LHS = N->getOperand(0);
13267   SDValue RHS = N->getOperand(1);
13268   SDLoc dl(N);
13269
13270   // Make sure we're not running after operation legalization where it
13271   // may have custom lowered the vector shuffles.
13272   if (LegalOperations)
13273     return SDValue();
13274
13275   if (N->getOpcode() != ISD::AND)
13276     return SDValue();
13277
13278   if (RHS.getOpcode() == ISD::BITCAST)
13279     RHS = RHS.getOperand(0);
13280
13281   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13282     return SDValue();
13283
13284   EVT RVT = RHS.getValueType();
13285   unsigned NumElts = RHS.getNumOperands();
13286
13287   // Attempt to create a valid clear mask, splitting the mask into
13288   // sub elements and checking to see if each is
13289   // all zeros or all ones - suitable for shuffle masking.
13290   auto BuildClearMask = [&](int Split) {
13291     int NumSubElts = NumElts * Split;
13292     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13293
13294     SmallVector<int, 8> Indices;
13295     for (int i = 0; i != NumSubElts; ++i) {
13296       int EltIdx = i / Split;
13297       int SubIdx = i % Split;
13298       SDValue Elt = RHS.getOperand(EltIdx);
13299       if (Elt.getOpcode() == ISD::UNDEF) {
13300         Indices.push_back(-1);
13301         continue;
13302       }
13303
13304       APInt Bits;
13305       if (isa<ConstantSDNode>(Elt))
13306         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13307       else if (isa<ConstantFPSDNode>(Elt))
13308         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13309       else
13310         return SDValue();
13311
13312       // Extract the sub element from the constant bit mask.
13313       if (DAG.getDataLayout().isBigEndian()) {
13314         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13315       } else {
13316         Bits = Bits.lshr(SubIdx * NumSubBits);
13317       }
13318
13319       if (Split > 1)
13320         Bits = Bits.trunc(NumSubBits);
13321
13322       if (Bits.isAllOnesValue())
13323         Indices.push_back(i);
13324       else if (Bits == 0)
13325         Indices.push_back(i + NumSubElts);
13326       else
13327         return SDValue();
13328     }
13329
13330     // Let's see if the target supports this vector_shuffle.
13331     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13332     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13333     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13334       return SDValue();
13335
13336     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13337     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13338                                                    DAG.getBitcast(ClearVT, LHS),
13339                                                    Zero, &Indices[0]));
13340   };
13341
13342   // Determine maximum split level (byte level masking).
13343   int MaxSplit = 1;
13344   if (RVT.getScalarSizeInBits() % 8 == 0)
13345     MaxSplit = RVT.getScalarSizeInBits() / 8;
13346
13347   for (int Split = 1; Split <= MaxSplit; ++Split)
13348     if (RVT.getScalarSizeInBits() % Split == 0)
13349       if (SDValue S = BuildClearMask(Split))
13350         return S;
13351
13352   return SDValue();
13353 }
13354
13355 /// Visit a binary vector operation, like ADD.
13356 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13357   assert(N->getValueType(0).isVector() &&
13358          "SimplifyVBinOp only works on vectors!");
13359
13360   SDValue LHS = N->getOperand(0);
13361   SDValue RHS = N->getOperand(1);
13362
13363   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13364   // this operation.
13365   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13366       RHS.getOpcode() == ISD::BUILD_VECTOR) {
13367     // Check if both vectors are constants. If not bail out.
13368     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13369           cast<BuildVectorSDNode>(RHS)->isConstant()))
13370       return SDValue();
13371
13372     SmallVector<SDValue, 8> Ops;
13373     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13374       SDValue LHSOp = LHS.getOperand(i);
13375       SDValue RHSOp = RHS.getOperand(i);
13376
13377       // Can't fold divide by zero.
13378       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13379           N->getOpcode() == ISD::FDIV) {
13380         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13381              cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13382           break;
13383       }
13384
13385       EVT VT = LHSOp.getValueType();
13386       EVT RVT = RHSOp.getValueType();
13387       EVT ST = VT;
13388
13389       if (RVT.getSizeInBits() < VT.getSizeInBits())
13390         ST = RVT;
13391
13392       // Integer BUILD_VECTOR operands may have types larger than the element
13393       // size (e.g., when the element type is not legal).  Prior to type
13394       // legalization, the types may not match between the two BUILD_VECTORS.
13395       // Truncate the operands to make them match.
13396       if (VT.getSizeInBits() != LHS.getValueType().getScalarSizeInBits()) {
13397         EVT ScalarT = LHS.getValueType().getScalarType();
13398         LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, LHSOp);
13399         VT = LHSOp.getValueType();
13400       }
13401       if (RVT.getSizeInBits() != RHS.getValueType().getScalarSizeInBits()) {
13402         EVT ScalarT = RHS.getValueType().getScalarType();
13403         RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, RHSOp);
13404         RVT = RHSOp.getValueType();
13405       }
13406
13407       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13408                                    LHSOp, RHSOp, N->getFlags());
13409
13410       // We need the resulting constant to be legal if we are in a phase after
13411       // legalization, so zero extend to the smallest operand type if required.
13412       if (ST != VT && Level != BeforeLegalizeTypes)
13413         FoldOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LHS), ST, FoldOp);
13414
13415       if (FoldOp.getOpcode() != ISD::UNDEF &&
13416           FoldOp.getOpcode() != ISD::Constant &&
13417           FoldOp.getOpcode() != ISD::ConstantFP)
13418         break;
13419       Ops.push_back(FoldOp);
13420       AddToWorklist(FoldOp.getNode());
13421     }
13422
13423     if (Ops.size() == LHS.getNumOperands())
13424       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13425   }
13426
13427   // Try to convert a constant mask AND into a shuffle clear mask.
13428   if (SDValue Shuffle = XformToShuffleWithZero(N))
13429     return Shuffle;
13430
13431   // Type legalization might introduce new shuffles in the DAG.
13432   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13433   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13434   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13435       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13436       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13437       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13438     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13439     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13440
13441     if (SVN0->getMask().equals(SVN1->getMask())) {
13442       EVT VT = N->getValueType(0);
13443       SDValue UndefVector = LHS.getOperand(1);
13444       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13445                                      LHS.getOperand(0), RHS.getOperand(0),
13446                                      N->getFlags());
13447       AddUsersToWorklist(N);
13448       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13449                                   &SVN0->getMask()[0]);
13450     }
13451   }
13452
13453   return SDValue();
13454 }
13455
13456 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13457                                     SDValue N1, SDValue N2){
13458   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13459
13460   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13461                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13462
13463   // If we got a simplified select_cc node back from SimplifySelectCC, then
13464   // break it down into a new SETCC node, and a new SELECT node, and then return
13465   // the SELECT node, since we were called with a SELECT node.
13466   if (SCC.getNode()) {
13467     // Check to see if we got a select_cc back (to turn into setcc/select).
13468     // Otherwise, just return whatever node we got back, like fabs.
13469     if (SCC.getOpcode() == ISD::SELECT_CC) {
13470       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13471                                   N0.getValueType(),
13472                                   SCC.getOperand(0), SCC.getOperand(1),
13473                                   SCC.getOperand(4));
13474       AddToWorklist(SETCC.getNode());
13475       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13476                            SCC.getOperand(2), SCC.getOperand(3));
13477     }
13478
13479     return SCC;
13480   }
13481   return SDValue();
13482 }
13483
13484 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13485 /// being selected between, see if we can simplify the select.  Callers of this
13486 /// should assume that TheSelect is deleted if this returns true.  As such, they
13487 /// should return the appropriate thing (e.g. the node) back to the top-level of
13488 /// the DAG combiner loop to avoid it being looked at.
13489 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13490                                     SDValue RHS) {
13491
13492   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13493   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13494   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13495     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13496       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13497       SDValue Sqrt = RHS;
13498       ISD::CondCode CC;
13499       SDValue CmpLHS;
13500       const ConstantFPSDNode *NegZero = nullptr;
13501
13502       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13503         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13504         CmpLHS = TheSelect->getOperand(0);
13505         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13506       } else {
13507         // SELECT or VSELECT
13508         SDValue Cmp = TheSelect->getOperand(0);
13509         if (Cmp.getOpcode() == ISD::SETCC) {
13510           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13511           CmpLHS = Cmp.getOperand(0);
13512           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13513         }
13514       }
13515       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13516           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13517           CC == ISD::SETULT || CC == ISD::SETLT)) {
13518         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13519         CombineTo(TheSelect, Sqrt);
13520         return true;
13521       }
13522     }
13523   }
13524   // Cannot simplify select with vector condition
13525   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13526
13527   // If this is a select from two identical things, try to pull the operation
13528   // through the select.
13529   if (LHS.getOpcode() != RHS.getOpcode() ||
13530       !LHS.hasOneUse() || !RHS.hasOneUse())
13531     return false;
13532
13533   // If this is a load and the token chain is identical, replace the select
13534   // of two loads with a load through a select of the address to load from.
13535   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13536   // constants have been dropped into the constant pool.
13537   if (LHS.getOpcode() == ISD::LOAD) {
13538     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13539     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13540
13541     // Token chains must be identical.
13542     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13543         // Do not let this transformation reduce the number of volatile loads.
13544         LLD->isVolatile() || RLD->isVolatile() ||
13545         // FIXME: If either is a pre/post inc/dec load,
13546         // we'd need to split out the address adjustment.
13547         LLD->isIndexed() || RLD->isIndexed() ||
13548         // If this is an EXTLOAD, the VT's must match.
13549         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13550         // If this is an EXTLOAD, the kind of extension must match.
13551         (LLD->getExtensionType() != RLD->getExtensionType() &&
13552          // The only exception is if one of the extensions is anyext.
13553          LLD->getExtensionType() != ISD::EXTLOAD &&
13554          RLD->getExtensionType() != ISD::EXTLOAD) ||
13555         // FIXME: this discards src value information.  This is
13556         // over-conservative. It would be beneficial to be able to remember
13557         // both potential memory locations.  Since we are discarding
13558         // src value info, don't do the transformation if the memory
13559         // locations are not in the default address space.
13560         LLD->getPointerInfo().getAddrSpace() != 0 ||
13561         RLD->getPointerInfo().getAddrSpace() != 0 ||
13562         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13563                                       LLD->getBasePtr().getValueType()))
13564       return false;
13565
13566     // Check that the select condition doesn't reach either load.  If so,
13567     // folding this will induce a cycle into the DAG.  If not, this is safe to
13568     // xform, so create a select of the addresses.
13569     SDValue Addr;
13570     if (TheSelect->getOpcode() == ISD::SELECT) {
13571       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13572       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13573           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13574         return false;
13575       // The loads must not depend on one another.
13576       if (LLD->isPredecessorOf(RLD) ||
13577           RLD->isPredecessorOf(LLD))
13578         return false;
13579       Addr = DAG.getSelect(SDLoc(TheSelect),
13580                            LLD->getBasePtr().getValueType(),
13581                            TheSelect->getOperand(0), LLD->getBasePtr(),
13582                            RLD->getBasePtr());
13583     } else {  // Otherwise SELECT_CC
13584       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13585       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13586
13587       if ((LLD->hasAnyUseOfValue(1) &&
13588            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13589           (RLD->hasAnyUseOfValue(1) &&
13590            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13591         return false;
13592
13593       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13594                          LLD->getBasePtr().getValueType(),
13595                          TheSelect->getOperand(0),
13596                          TheSelect->getOperand(1),
13597                          LLD->getBasePtr(), RLD->getBasePtr(),
13598                          TheSelect->getOperand(4));
13599     }
13600
13601     SDValue Load;
13602     // It is safe to replace the two loads if they have different alignments,
13603     // but the new load must be the minimum (most restrictive) alignment of the
13604     // inputs.
13605     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13606     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13607     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13608       Load = DAG.getLoad(TheSelect->getValueType(0),
13609                          SDLoc(TheSelect),
13610                          // FIXME: Discards pointer and AA info.
13611                          LLD->getChain(), Addr, MachinePointerInfo(),
13612                          LLD->isVolatile(), LLD->isNonTemporal(),
13613                          isInvariant, Alignment);
13614     } else {
13615       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13616                             RLD->getExtensionType() : LLD->getExtensionType(),
13617                             SDLoc(TheSelect),
13618                             TheSelect->getValueType(0),
13619                             // FIXME: Discards pointer and AA info.
13620                             LLD->getChain(), Addr, MachinePointerInfo(),
13621                             LLD->getMemoryVT(), LLD->isVolatile(),
13622                             LLD->isNonTemporal(), isInvariant, Alignment);
13623     }
13624
13625     // Users of the select now use the result of the load.
13626     CombineTo(TheSelect, Load);
13627
13628     // Users of the old loads now use the new load's chain.  We know the
13629     // old-load value is dead now.
13630     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13631     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13632     return true;
13633   }
13634
13635   return false;
13636 }
13637
13638 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13639 /// where 'cond' is the comparison specified by CC.
13640 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13641                                       SDValue N2, SDValue N3,
13642                                       ISD::CondCode CC, bool NotExtCompare) {
13643   // (x ? y : y) -> y.
13644   if (N2 == N3) return N2;
13645
13646   EVT VT = N2.getValueType();
13647   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13648   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13649
13650   // Determine if the condition we're dealing with is constant
13651   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13652                               N0, N1, CC, DL, false);
13653   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13654
13655   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13656     // fold select_cc true, x, y -> x
13657     // fold select_cc false, x, y -> y
13658     return !SCCC->isNullValue() ? N2 : N3;
13659   }
13660
13661   // Check to see if we can simplify the select into an fabs node
13662   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13663     // Allow either -0.0 or 0.0
13664     if (CFP->isZero()) {
13665       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13666       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13667           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13668           N2 == N3.getOperand(0))
13669         return DAG.getNode(ISD::FABS, DL, VT, N0);
13670
13671       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13672       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13673           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13674           N2.getOperand(0) == N3)
13675         return DAG.getNode(ISD::FABS, DL, VT, N3);
13676     }
13677   }
13678
13679   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13680   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13681   // in it.  This is a win when the constant is not otherwise available because
13682   // it replaces two constant pool loads with one.  We only do this if the FP
13683   // type is known to be legal, because if it isn't, then we are before legalize
13684   // types an we want the other legalization to happen first (e.g. to avoid
13685   // messing with soft float) and if the ConstantFP is not legal, because if
13686   // it is legal, we may not need to store the FP constant in a constant pool.
13687   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13688     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13689       if (TLI.isTypeLegal(N2.getValueType()) &&
13690           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13691                TargetLowering::Legal &&
13692            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13693            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13694           // If both constants have multiple uses, then we won't need to do an
13695           // extra load, they are likely around in registers for other users.
13696           (TV->hasOneUse() || FV->hasOneUse())) {
13697         Constant *Elts[] = {
13698           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13699           const_cast<ConstantFP*>(TV->getConstantFPValue())
13700         };
13701         Type *FPTy = Elts[0]->getType();
13702         const DataLayout &TD = DAG.getDataLayout();
13703
13704         // Create a ConstantArray of the two constants.
13705         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13706         SDValue CPIdx =
13707             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13708                                 TD.getPrefTypeAlignment(FPTy));
13709         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13710
13711         // Get the offsets to the 0 and 1 element of the array so that we can
13712         // select between them.
13713         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13714         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13715         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13716
13717         SDValue Cond = DAG.getSetCC(DL,
13718                                     getSetCCResultType(N0.getValueType()),
13719                                     N0, N1, CC);
13720         AddToWorklist(Cond.getNode());
13721         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13722                                           Cond, One, Zero);
13723         AddToWorklist(CstOffset.getNode());
13724         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13725                             CstOffset);
13726         AddToWorklist(CPIdx.getNode());
13727         return DAG.getLoad(
13728             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13729             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13730             false, false, false, Alignment);
13731       }
13732     }
13733
13734   // Check to see if we can perform the "gzip trick", transforming
13735   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13736   if (isNullConstant(N3) && CC == ISD::SETLT &&
13737       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13738        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13739     EVT XType = N0.getValueType();
13740     EVT AType = N2.getValueType();
13741     if (XType.bitsGE(AType)) {
13742       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13743       // single-bit constant.
13744       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13745         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13746         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13747         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13748                                        getShiftAmountTy(N0.getValueType()));
13749         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13750                                     XType, N0, ShCt);
13751         AddToWorklist(Shift.getNode());
13752
13753         if (XType.bitsGT(AType)) {
13754           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13755           AddToWorklist(Shift.getNode());
13756         }
13757
13758         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13759       }
13760
13761       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13762                                   XType, N0,
13763                                   DAG.getConstant(XType.getSizeInBits() - 1,
13764                                                   SDLoc(N0),
13765                                          getShiftAmountTy(N0.getValueType())));
13766       AddToWorklist(Shift.getNode());
13767
13768       if (XType.bitsGT(AType)) {
13769         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13770         AddToWorklist(Shift.getNode());
13771       }
13772
13773       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13774     }
13775   }
13776
13777   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13778   // where y is has a single bit set.
13779   // A plaintext description would be, we can turn the SELECT_CC into an AND
13780   // when the condition can be materialized as an all-ones register.  Any
13781   // single bit-test can be materialized as an all-ones register with
13782   // shift-left and shift-right-arith.
13783   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13784       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13785     SDValue AndLHS = N0->getOperand(0);
13786     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13787     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13788       // Shift the tested bit over the sign bit.
13789       APInt AndMask = ConstAndRHS->getAPIntValue();
13790       SDValue ShlAmt =
13791         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13792                         getShiftAmountTy(AndLHS.getValueType()));
13793       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13794
13795       // Now arithmetic right shift it all the way over, so the result is either
13796       // all-ones, or zero.
13797       SDValue ShrAmt =
13798         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13799                         getShiftAmountTy(Shl.getValueType()));
13800       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13801
13802       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13803     }
13804   }
13805
13806   // fold select C, 16, 0 -> shl C, 4
13807   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13808       TLI.getBooleanContents(N0.getValueType()) ==
13809           TargetLowering::ZeroOrOneBooleanContent) {
13810
13811     // If the caller doesn't want us to simplify this into a zext of a compare,
13812     // don't do it.
13813     if (NotExtCompare && N2C->isOne())
13814       return SDValue();
13815
13816     // Get a SetCC of the condition
13817     // NOTE: Don't create a SETCC if it's not legal on this target.
13818     if (!LegalOperations ||
13819         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13820       SDValue Temp, SCC;
13821       // cast from setcc result type to select result type
13822       if (LegalTypes) {
13823         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13824                             N0, N1, CC);
13825         if (N2.getValueType().bitsLT(SCC.getValueType()))
13826           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13827                                         N2.getValueType());
13828         else
13829           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13830                              N2.getValueType(), SCC);
13831       } else {
13832         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13833         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13834                            N2.getValueType(), SCC);
13835       }
13836
13837       AddToWorklist(SCC.getNode());
13838       AddToWorklist(Temp.getNode());
13839
13840       if (N2C->isOne())
13841         return Temp;
13842
13843       // shl setcc result by log2 n2c
13844       return DAG.getNode(
13845           ISD::SHL, DL, N2.getValueType(), Temp,
13846           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13847                           getShiftAmountTy(Temp.getValueType())));
13848     }
13849   }
13850
13851   // Check to see if this is an integer abs.
13852   // select_cc setg[te] X,  0,  X, -X ->
13853   // select_cc setgt    X, -1,  X, -X ->
13854   // select_cc setl[te] X,  0, -X,  X ->
13855   // select_cc setlt    X,  1, -X,  X ->
13856   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13857   if (N1C) {
13858     ConstantSDNode *SubC = nullptr;
13859     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13860          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13861         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13862       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13863     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13864               (N1C->isOne() && CC == ISD::SETLT)) &&
13865              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13866       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13867
13868     EVT XType = N0.getValueType();
13869     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13870       SDLoc DL(N0);
13871       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13872                                   N0,
13873                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13874                                          getShiftAmountTy(N0.getValueType())));
13875       SDValue Add = DAG.getNode(ISD::ADD, DL,
13876                                 XType, N0, Shift);
13877       AddToWorklist(Shift.getNode());
13878       AddToWorklist(Add.getNode());
13879       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13880     }
13881   }
13882
13883   return SDValue();
13884 }
13885
13886 /// This is a stub for TargetLowering::SimplifySetCC.
13887 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13888                                    SDValue N1, ISD::CondCode Cond,
13889                                    SDLoc DL, bool foldBooleans) {
13890   TargetLowering::DAGCombinerInfo
13891     DagCombineInfo(DAG, Level, false, this);
13892   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13893 }
13894
13895 /// Given an ISD::SDIV node expressing a divide by constant, return
13896 /// a DAG expression to select that will generate the same value by multiplying
13897 /// by a magic number.
13898 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13899 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13900   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13901   if (!C)
13902     return SDValue();
13903
13904   // Avoid division by zero.
13905   if (C->isNullValue())
13906     return SDValue();
13907
13908   std::vector<SDNode*> Built;
13909   SDValue S =
13910       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13911
13912   for (SDNode *N : Built)
13913     AddToWorklist(N);
13914   return S;
13915 }
13916
13917 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13918 /// DAG expression that will generate the same value by right shifting.
13919 SDValue DAGCombiner::BuildSDIVPow2(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 = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13930
13931   for (SDNode *N : Built)
13932     AddToWorklist(N);
13933   return S;
13934 }
13935
13936 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13937 /// expression that will generate the same value by multiplying by a magic
13938 /// number.
13939 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13940 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13941   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13942   if (!C)
13943     return SDValue();
13944
13945   // Avoid division by zero.
13946   if (C->isNullValue())
13947     return SDValue();
13948
13949   std::vector<SDNode*> Built;
13950   SDValue S =
13951       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13952
13953   for (SDNode *N : Built)
13954     AddToWorklist(N);
13955   return S;
13956 }
13957
13958 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
13959   if (Level >= AfterLegalizeDAG)
13960     return SDValue();
13961
13962   // Expose the DAG combiner to the target combiner implementations.
13963   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13964
13965   unsigned Iterations = 0;
13966   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13967     if (Iterations) {
13968       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13969       // For the reciprocal, we need to find the zero of the function:
13970       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13971       //     =>
13972       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13973       //     does not require additional intermediate precision]
13974       EVT VT = Op.getValueType();
13975       SDLoc DL(Op);
13976       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13977
13978       AddToWorklist(Est.getNode());
13979
13980       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13981       for (unsigned i = 0; i < Iterations; ++i) {
13982         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
13983         AddToWorklist(NewEst.getNode());
13984
13985         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
13986         AddToWorklist(NewEst.getNode());
13987
13988         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
13989         AddToWorklist(NewEst.getNode());
13990
13991         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
13992         AddToWorklist(Est.getNode());
13993       }
13994     }
13995     return Est;
13996   }
13997
13998   return SDValue();
13999 }
14000
14001 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14002 /// For the reciprocal sqrt, we need to find the zero of the function:
14003 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14004 ///     =>
14005 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14006 /// As a result, we precompute A/2 prior to the iteration loop.
14007 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14008                                           unsigned Iterations,
14009                                           SDNodeFlags *Flags) {
14010   EVT VT = Arg.getValueType();
14011   SDLoc DL(Arg);
14012   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14013
14014   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14015   // this entire sequence requires only one FP constant.
14016   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14017   AddToWorklist(HalfArg.getNode());
14018
14019   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14020   AddToWorklist(HalfArg.getNode());
14021
14022   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14023   for (unsigned i = 0; i < Iterations; ++i) {
14024     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14025     AddToWorklist(NewEst.getNode());
14026
14027     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14028     AddToWorklist(NewEst.getNode());
14029
14030     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14031     AddToWorklist(NewEst.getNode());
14032
14033     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14034     AddToWorklist(Est.getNode());
14035   }
14036   return Est;
14037 }
14038
14039 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14040 /// For the reciprocal sqrt, we need to find the zero of the function:
14041 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14042 ///     =>
14043 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14044 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14045                                           unsigned Iterations,
14046                                           SDNodeFlags *Flags) {
14047   EVT VT = Arg.getValueType();
14048   SDLoc DL(Arg);
14049   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14050   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14051
14052   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14053   for (unsigned i = 0; i < Iterations; ++i) {
14054     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14055     AddToWorklist(HalfEst.getNode());
14056
14057     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14058     AddToWorklist(Est.getNode());
14059
14060     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14061     AddToWorklist(Est.getNode());
14062
14063     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14064     AddToWorklist(Est.getNode());
14065
14066     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14067     AddToWorklist(Est.getNode());
14068   }
14069   return Est;
14070 }
14071
14072 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14073   if (Level >= AfterLegalizeDAG)
14074     return SDValue();
14075
14076   // Expose the DAG combiner to the target combiner implementations.
14077   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14078   unsigned Iterations = 0;
14079   bool UseOneConstNR = false;
14080   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14081     AddToWorklist(Est.getNode());
14082     if (Iterations) {
14083       Est = UseOneConstNR ?
14084         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14085         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14086     }
14087     return Est;
14088   }
14089
14090   return SDValue();
14091 }
14092
14093 /// Return true if base is a frame index, which is known not to alias with
14094 /// anything but itself.  Provides base object and offset as results.
14095 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14096                            const GlobalValue *&GV, const void *&CV) {
14097   // Assume it is a primitive operation.
14098   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14099
14100   // If it's an adding a simple constant then integrate the offset.
14101   if (Base.getOpcode() == ISD::ADD) {
14102     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14103       Base = Base.getOperand(0);
14104       Offset += C->getZExtValue();
14105     }
14106   }
14107
14108   // Return the underlying GlobalValue, and update the Offset.  Return false
14109   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14110   // by multiple nodes with different offsets.
14111   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14112     GV = G->getGlobal();
14113     Offset += G->getOffset();
14114     return false;
14115   }
14116
14117   // Return the underlying Constant value, and update the Offset.  Return false
14118   // for ConstantSDNodes since the same constant pool entry may be represented
14119   // by multiple nodes with different offsets.
14120   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14121     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14122                                          : (const void *)C->getConstVal();
14123     Offset += C->getOffset();
14124     return false;
14125   }
14126   // If it's any of the following then it can't alias with anything but itself.
14127   return isa<FrameIndexSDNode>(Base);
14128 }
14129
14130 /// Return true if there is any possibility that the two addresses overlap.
14131 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14132   // If they are the same then they must be aliases.
14133   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14134
14135   // If they are both volatile then they cannot be reordered.
14136   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14137
14138   // If one operation reads from invariant memory, and the other may store, they
14139   // cannot alias. These should really be checking the equivalent of mayWrite,
14140   // but it only matters for memory nodes other than load /store.
14141   if (Op0->isInvariant() && Op1->writeMem())
14142     return false;
14143
14144   if (Op1->isInvariant() && Op0->writeMem())
14145     return false;
14146
14147   // Gather base node and offset information.
14148   SDValue Base1, Base2;
14149   int64_t Offset1, Offset2;
14150   const GlobalValue *GV1, *GV2;
14151   const void *CV1, *CV2;
14152   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14153                                       Base1, Offset1, GV1, CV1);
14154   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14155                                       Base2, Offset2, GV2, CV2);
14156
14157   // If they have a same base address then check to see if they overlap.
14158   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14159     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14160              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14161
14162   // It is possible for different frame indices to alias each other, mostly
14163   // when tail call optimization reuses return address slots for arguments.
14164   // To catch this case, look up the actual index of frame indices to compute
14165   // the real alias relationship.
14166   if (isFrameIndex1 && isFrameIndex2) {
14167     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14168     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14169     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14170     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14171              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14172   }
14173
14174   // Otherwise, if we know what the bases are, and they aren't identical, then
14175   // we know they cannot alias.
14176   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14177     return false;
14178
14179   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14180   // compared to the size and offset of the access, we may be able to prove they
14181   // do not alias.  This check is conservative for now to catch cases created by
14182   // splitting vector types.
14183   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14184       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14185       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14186        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14187       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14188     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14189     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14190
14191     // There is no overlap between these relatively aligned accesses of similar
14192     // size, return no alias.
14193     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14194         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14195       return false;
14196   }
14197
14198   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14199                    ? CombinerGlobalAA
14200                    : DAG.getSubtarget().useAA();
14201 #ifndef NDEBUG
14202   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14203       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14204     UseAA = false;
14205 #endif
14206   if (UseAA &&
14207       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14208     // Use alias analysis information.
14209     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14210                                  Op1->getSrcValueOffset());
14211     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14212         Op0->getSrcValueOffset() - MinOffset;
14213     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14214         Op1->getSrcValueOffset() - MinOffset;
14215     AliasResult AAResult =
14216         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14217                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14218                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14219                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14220     if (AAResult == NoAlias)
14221       return false;
14222   }
14223
14224   // Otherwise we have to assume they alias.
14225   return true;
14226 }
14227
14228 /// Walk up chain skipping non-aliasing memory nodes,
14229 /// looking for aliasing nodes and adding them to the Aliases vector.
14230 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14231                                    SmallVectorImpl<SDValue> &Aliases) {
14232   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14233   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14234
14235   // Get alias information for node.
14236   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14237
14238   // Starting off.
14239   Chains.push_back(OriginalChain);
14240   unsigned Depth = 0;
14241
14242   // Look at each chain and determine if it is an alias.  If so, add it to the
14243   // aliases list.  If not, then continue up the chain looking for the next
14244   // candidate.
14245   while (!Chains.empty()) {
14246     SDValue Chain = Chains.pop_back_val();
14247
14248     // For TokenFactor nodes, look at each operand and only continue up the
14249     // chain until we find two aliases.  If we've seen two aliases, assume we'll
14250     // find more and revert to original chain since the xform is unlikely to be
14251     // profitable.
14252     //
14253     // FIXME: The depth check could be made to return the last non-aliasing
14254     // chain we found before we hit a tokenfactor rather than the original
14255     // chain.
14256     if (Depth > 6 || Aliases.size() == 2) {
14257       Aliases.clear();
14258       Aliases.push_back(OriginalChain);
14259       return;
14260     }
14261
14262     // Don't bother if we've been before.
14263     if (!Visited.insert(Chain.getNode()).second)
14264       continue;
14265
14266     switch (Chain.getOpcode()) {
14267     case ISD::EntryToken:
14268       // Entry token is ideal chain operand, but handled in FindBetterChain.
14269       break;
14270
14271     case ISD::LOAD:
14272     case ISD::STORE: {
14273       // Get alias information for Chain.
14274       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14275           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14276
14277       // If chain is alias then stop here.
14278       if (!(IsLoad && IsOpLoad) &&
14279           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14280         Aliases.push_back(Chain);
14281       } else {
14282         // Look further up the chain.
14283         Chains.push_back(Chain.getOperand(0));
14284         ++Depth;
14285       }
14286       break;
14287     }
14288
14289     case ISD::TokenFactor:
14290       // We have to check each of the operands of the token factor for "small"
14291       // token factors, so we queue them up.  Adding the operands to the queue
14292       // (stack) in reverse order maintains the original order and increases the
14293       // likelihood that getNode will find a matching token factor (CSE.)
14294       if (Chain.getNumOperands() > 16) {
14295         Aliases.push_back(Chain);
14296         break;
14297       }
14298       for (unsigned n = Chain.getNumOperands(); n;)
14299         Chains.push_back(Chain.getOperand(--n));
14300       ++Depth;
14301       break;
14302
14303     default:
14304       // For all other instructions we will just have to take what we can get.
14305       Aliases.push_back(Chain);
14306       break;
14307     }
14308   }
14309
14310   // We need to be careful here to also search for aliases through the
14311   // value operand of a store, etc. Consider the following situation:
14312   //   Token1 = ...
14313   //   L1 = load Token1, %52
14314   //   S1 = store Token1, L1, %51
14315   //   L2 = load Token1, %52+8
14316   //   S2 = store Token1, L2, %51+8
14317   //   Token2 = Token(S1, S2)
14318   //   L3 = load Token2, %53
14319   //   S3 = store Token2, L3, %52
14320   //   L4 = load Token2, %53+8
14321   //   S4 = store Token2, L4, %52+8
14322   // If we search for aliases of S3 (which loads address %52), and we look
14323   // only through the chain, then we'll miss the trivial dependence on L1
14324   // (which also loads from %52). We then might change all loads and
14325   // stores to use Token1 as their chain operand, which could result in
14326   // copying %53 into %52 before copying %52 into %51 (which should
14327   // happen first).
14328   //
14329   // The problem is, however, that searching for such data dependencies
14330   // can become expensive, and the cost is not directly related to the
14331   // chain depth. Instead, we'll rule out such configurations here by
14332   // insisting that we've visited all chain users (except for users
14333   // of the original chain, which is not necessary). When doing this,
14334   // we need to look through nodes we don't care about (otherwise, things
14335   // like register copies will interfere with trivial cases).
14336
14337   SmallVector<const SDNode *, 16> Worklist;
14338   for (const SDNode *N : Visited)
14339     if (N != OriginalChain.getNode())
14340       Worklist.push_back(N);
14341
14342   while (!Worklist.empty()) {
14343     const SDNode *M = Worklist.pop_back_val();
14344
14345     // We have already visited M, and want to make sure we've visited any uses
14346     // of M that we care about. For uses that we've not visisted, and don't
14347     // care about, queue them to the worklist.
14348
14349     for (SDNode::use_iterator UI = M->use_begin(),
14350          UIE = M->use_end(); UI != UIE; ++UI)
14351       if (UI.getUse().getValueType() == MVT::Other &&
14352           Visited.insert(*UI).second) {
14353         if (isa<MemSDNode>(*UI)) {
14354           // We've not visited this use, and we care about it (it could have an
14355           // ordering dependency with the original node).
14356           Aliases.clear();
14357           Aliases.push_back(OriginalChain);
14358           return;
14359         }
14360
14361         // We've not visited this use, but we don't care about it. Mark it as
14362         // visited and enqueue it to the worklist.
14363         Worklist.push_back(*UI);
14364       }
14365   }
14366 }
14367
14368 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14369 /// (aliasing node.)
14370 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14371   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14372
14373   // Accumulate all the aliases to this node.
14374   GatherAllAliases(N, OldChain, Aliases);
14375
14376   // If no operands then chain to entry token.
14377   if (Aliases.size() == 0)
14378     return DAG.getEntryNode();
14379
14380   // If a single operand then chain to it.  We don't need to revisit it.
14381   if (Aliases.size() == 1)
14382     return Aliases[0];
14383
14384   // Construct a custom tailored token factor.
14385   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14386 }
14387
14388 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14389   // This holds the base pointer, index, and the offset in bytes from the base
14390   // pointer.
14391   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14392
14393   // We must have a base and an offset.
14394   if (!BasePtr.Base.getNode())
14395     return false;
14396
14397   // Do not handle stores to undef base pointers.
14398   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14399     return false;
14400
14401   SmallVector<StoreSDNode *, 8> ChainedStores;
14402   ChainedStores.push_back(St);
14403
14404   // Walk up the chain and look for nodes with offsets from the same
14405   // base pointer. Stop when reaching an instruction with a different kind
14406   // or instruction which has a different base pointer.
14407   StoreSDNode *Index = St;
14408   while (Index) {
14409     // If the chain has more than one use, then we can't reorder the mem ops.
14410     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14411       break;
14412
14413     // Find the base pointer and offset for this memory node.
14414     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14415
14416     // Check that the base pointer is the same as the original one.
14417     if (!Ptr.equalBaseIndex(BasePtr))
14418       break;
14419
14420     if (Index->isVolatile() || Index->isIndexed())
14421       break;
14422
14423     // Find the next memory operand in the chain. If the next operand in the
14424     // chain is a store then move up and continue the scan with the next
14425     // memory operand. If the next operand is a load save it and use alias
14426     // information to check if it interferes with anything.
14427     SDNode *NextInChain = Index->getChain().getNode();
14428     while (true) {
14429       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14430         // We found a store node. Use it for the next iteration.
14431         ChainedStores.push_back(STn);
14432         Index = STn;
14433         break;
14434       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14435         NextInChain = Ldn->getChain().getNode();
14436         continue;
14437       } else {
14438         Index = nullptr;
14439         break;
14440       }
14441     }
14442   }
14443
14444   bool MadeChange = false;
14445   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14446
14447   for (StoreSDNode *ChainedStore : ChainedStores) {
14448     SDValue Chain = ChainedStore->getChain();
14449     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14450
14451     if (Chain != BetterChain) {
14452       MadeChange = true;
14453       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14454     }
14455   }
14456
14457   // Do all replacements after finding the replacements to make to avoid making
14458   // the chains more complicated by introducing new TokenFactors.
14459   for (auto Replacement : BetterChains)
14460     replaceStoreChain(Replacement.first, Replacement.second);
14461
14462   return MadeChange;
14463 }
14464
14465 /// This is the entry point for the file.
14466 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14467                            CodeGenOpt::Level OptLevel) {
14468   /// This is the main entry point to this class.
14469   DAGCombiner(*this, AA, OptLevel).Run(Level);
14470 }