A doccomment for CombineTo, and some NFC refactorings
[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     /// Replaces all uses of the results of one DAG node with new values.
160     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
161                       bool AddTo = true);
162
163     /// Replaces all uses of the results of one DAG node with new values.
164     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
165       return CombineTo(N, &Res, 1, AddTo);
166     }
167
168     /// Replaces all uses of the results of one DAG node with new values.
169     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
170                       bool AddTo = true) {
171       SDValue To[] = { Res0, Res1 };
172       return CombineTo(N, To, 2, AddTo);
173     }
174
175     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176
177   private:
178
179     /// Check the specified integer node value to see if it can be simplified or
180     /// if things it uses can be simplified by bit propagation.
181     /// If so, return true.
182     bool SimplifyDemandedBits(SDValue Op) {
183       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
184       APInt Demanded = APInt::getAllOnesValue(BitWidth);
185       return SimplifyDemandedBits(Op, Demanded);
186     }
187
188     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
189
190     bool CombineToPreIndexedLoadStore(SDNode *N);
191     bool CombineToPostIndexedLoadStore(SDNode *N);
192     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
193     bool SliceUpLoad(SDNode *N);
194
195     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
196     ///   load.
197     ///
198     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
199     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
200     /// \param EltNo index of the vector element to load.
201     /// \param OriginalLoad load that EVE came from to be replaced.
202     /// \returns EVE on success SDValue() on failure.
203     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
204         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
205     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
206     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
207     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
208     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue PromoteIntBinOp(SDValue Op);
210     SDValue PromoteIntShiftOp(SDValue Op);
211     SDValue PromoteExtend(SDValue Op);
212     bool PromoteLoad(SDValue Op);
213
214     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
215                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
216                          ISD::NodeType ExtType);
217
218     /// Call the node-specific routine that knows how to fold each
219     /// particular type of node. If that doesn't do anything, try the
220     /// target-specific DAG combines.
221     SDValue combine(SDNode *N);
222
223     // Visitation implementation - Implement dag node combining for different
224     // node types.  The semantics are as follows:
225     // Return Value:
226     //   SDValue.getNode() == 0 - No change was made
227     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
228     //   otherwise              - N should be replaced by the returned Operand.
229     //
230     SDValue visitTokenFactor(SDNode *N);
231     SDValue visitMERGE_VALUES(SDNode *N);
232     SDValue visitADD(SDNode *N);
233     SDValue visitSUB(SDNode *N);
234     SDValue visitADDC(SDNode *N);
235     SDValue visitSUBC(SDNode *N);
236     SDValue visitADDE(SDNode *N);
237     SDValue visitSUBE(SDNode *N);
238     SDValue visitMUL(SDNode *N);
239     SDValue visitSDIV(SDNode *N);
240     SDValue visitUDIV(SDNode *N);
241     SDValue visitREM(SDNode *N);
242     SDValue visitMULHU(SDNode *N);
243     SDValue visitMULHS(SDNode *N);
244     SDValue visitSMUL_LOHI(SDNode *N);
245     SDValue visitUMUL_LOHI(SDNode *N);
246     SDValue visitSMULO(SDNode *N);
247     SDValue visitUMULO(SDNode *N);
248     SDValue visitSDIVREM(SDNode *N);
249     SDValue visitUDIVREM(SDNode *N);
250     SDValue visitIMINMAX(SDNode *N);
251     SDValue visitAND(SDNode *N);
252     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitOR(SDNode *N);
254     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
255     SDValue visitXOR(SDNode *N);
256     SDValue SimplifyVBinOp(SDNode *N);
257     SDValue visitSHL(SDNode *N);
258     SDValue visitSRA(SDNode *N);
259     SDValue visitSRL(SDNode *N);
260     SDValue visitRotate(SDNode *N);
261     SDValue visitBSWAP(SDNode *N);
262     SDValue visitCTLZ(SDNode *N);
263     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
264     SDValue visitCTTZ(SDNode *N);
265     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
266     SDValue visitCTPOP(SDNode *N);
267     SDValue visitSELECT(SDNode *N);
268     SDValue visitVSELECT(SDNode *N);
269     SDValue visitSELECT_CC(SDNode *N);
270     SDValue visitSETCC(SDNode *N);
271     SDValue visitSIGN_EXTEND(SDNode *N);
272     SDValue visitZERO_EXTEND(SDNode *N);
273     SDValue visitANY_EXTEND(SDNode *N);
274     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
275     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
276     SDValue visitTRUNCATE(SDNode *N);
277     SDValue visitBITCAST(SDNode *N);
278     SDValue visitBUILD_PAIR(SDNode *N);
279     SDValue visitFADD(SDNode *N);
280     SDValue visitFSUB(SDNode *N);
281     SDValue visitFMUL(SDNode *N);
282     SDValue visitFMA(SDNode *N);
283     SDValue visitFDIV(SDNode *N);
284     SDValue visitFREM(SDNode *N);
285     SDValue visitFSQRT(SDNode *N);
286     SDValue visitFCOPYSIGN(SDNode *N);
287     SDValue visitSINT_TO_FP(SDNode *N);
288     SDValue visitUINT_TO_FP(SDNode *N);
289     SDValue visitFP_TO_SINT(SDNode *N);
290     SDValue visitFP_TO_UINT(SDNode *N);
291     SDValue visitFP_ROUND(SDNode *N);
292     SDValue visitFP_ROUND_INREG(SDNode *N);
293     SDValue visitFP_EXTEND(SDNode *N);
294     SDValue visitFNEG(SDNode *N);
295     SDValue visitFABS(SDNode *N);
296     SDValue visitFCEIL(SDNode *N);
297     SDValue visitFTRUNC(SDNode *N);
298     SDValue visitFFLOOR(SDNode *N);
299     SDValue visitFMINNUM(SDNode *N);
300     SDValue visitFMAXNUM(SDNode *N);
301     SDValue visitBRCOND(SDNode *N);
302     SDValue visitBR_CC(SDNode *N);
303     SDValue visitLOAD(SDNode *N);
304
305     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
306     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
307
308     SDValue visitSTORE(SDNode *N);
309     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
310     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
311     SDValue visitBUILD_VECTOR(SDNode *N);
312     SDValue visitCONCAT_VECTORS(SDNode *N);
313     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
314     SDValue visitVECTOR_SHUFFLE(SDNode *N);
315     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
316     SDValue visitINSERT_SUBVECTOR(SDNode *N);
317     SDValue visitMLOAD(SDNode *N);
318     SDValue visitMSTORE(SDNode *N);
319     SDValue visitMGATHER(SDNode *N);
320     SDValue visitMSCATTER(SDNode *N);
321     SDValue visitFP_TO_FP16(SDNode *N);
322     SDValue visitFP16_TO_FP(SDNode *N);
323
324     SDValue visitFADDForFMACombine(SDNode *N);
325     SDValue visitFSUBForFMACombine(SDNode *N);
326     SDValue visitFMULForFMACombine(SDNode *N);
327
328     SDValue XformToShuffleWithZero(SDNode *N);
329     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
330
331     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
332
333     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
334     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
335     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
336     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
337                              SDValue N3, ISD::CondCode CC,
338                              bool NotExtCompare = false);
339     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
340                           SDLoc DL, bool foldBooleans = true);
341
342     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
343                            SDValue &CC) const;
344     bool isOneUseSetCC(SDValue N) const;
345
346     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
347                                          unsigned HiOp);
348     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
349     SDValue CombineExtLoad(SDNode *N);
350     SDValue combineRepeatedFPDivisors(SDNode *N);
351     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
352     SDValue BuildSDIV(SDNode *N);
353     SDValue BuildSDIVPow2(SDNode *N);
354     SDValue BuildUDIV(SDNode *N);
355     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
356     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
357     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
358                                  SDNodeFlags *Flags);
359     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
360                                  SDNodeFlags *Flags);
361     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
362                                bool DemandHighBits = true);
363     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
364     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
365                               SDValue InnerPos, SDValue InnerNeg,
366                               unsigned PosOpcode, unsigned NegOpcode,
367                               SDLoc DL);
368     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
369     SDValue ReduceLoadWidth(SDNode *N);
370     SDValue ReduceLoadOpStoreWidth(SDNode *N);
371     SDValue TransformFPLoadStorePair(SDNode *N);
372     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
373     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
374
375     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
376
377     /// Walk up chain skipping non-aliasing memory nodes,
378     /// looking for aliasing nodes and adding them to the Aliases vector.
379     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
380                           SmallVectorImpl<SDValue> &Aliases);
381
382     /// Return true if there is any possibility that the two addresses overlap.
383     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
384
385     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
386     /// chain (aliasing node.)
387     SDValue FindBetterChain(SDNode *N, SDValue Chain);
388
389     /// Do FindBetterChain for a store and any possibly adjacent stores on
390     /// consecutive chains.
391     bool findBetterNeighborChains(StoreSDNode *St);
392
393     /// Holds a pointer to an LSBaseSDNode as well as information on where it
394     /// is located in a sequence of memory operations connected by a chain.
395     struct MemOpLink {
396       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
397       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
398       // Ptr to the mem node.
399       LSBaseSDNode *MemNode;
400       // Offset from the base ptr.
401       int64_t OffsetFromBase;
402       // What is the sequence number of this mem node.
403       // Lowest mem operand in the DAG starts at zero.
404       unsigned SequenceNum;
405     };
406
407     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
408     /// constant build_vector of the stored constant values in Stores.
409     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
410                                          SDLoc SL,
411                                          ArrayRef<MemOpLink> Stores,
412                                          SmallVectorImpl<SDValue> &Chains,
413                                          EVT Ty) const;
414
415     /// This is a helper function for MergeConsecutiveStores. When the source
416     /// elements of the consecutive stores are all constants or all extracted
417     /// vector elements, try to merge them into one larger store.
418     /// \return True if a merged store was created.
419     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
420                                          EVT MemVT, unsigned NumStores,
421                                          bool IsConstantSrc, bool UseVector);
422
423     /// This is a helper function for MergeConsecutiveStores.
424     /// Stores that may be merged are placed in StoreNodes.
425     /// Loads that may alias with those stores are placed in AliasLoadNodes.
426     void getStoreMergeAndAliasCandidates(
427         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
428         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
429
430     /// Merge consecutive store operations into a wide store.
431     /// This optimization uses wide integers or vectors when possible.
432     /// \return True if some memory operations were changed.
433     bool MergeConsecutiveStores(StoreSDNode *N);
434
435     /// \brief Try to transform a truncation where C is a constant:
436     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
437     ///
438     /// \p N needs to be a truncation and its first operand an AND. Other
439     /// requirements are checked by the function (e.g. that trunc is
440     /// single-use) and if missed an empty SDValue is returned.
441     SDValue distributeTruncateThroughAnd(SDNode *N);
442
443   public:
444     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
445         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
446           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
447       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
448     }
449
450     /// Runs the dag combiner on all nodes in the work list
451     void Run(CombineLevel AtLevel);
452
453     SelectionDAG &getDAG() const { return DAG; }
454
455     /// Returns a type large enough to hold any valid shift amount - before type
456     /// legalization these can be huge.
457     EVT getShiftAmountTy(EVT LHSTy) {
458       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
459       if (LHSTy.isVector())
460         return LHSTy;
461       auto &DL = DAG.getDataLayout();
462       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
463                         : TLI.getPointerTy(DL);
464     }
465
466     /// This method returns true if we are running before type legalization or
467     /// if the specified VT is legal.
468     bool isTypeLegal(const EVT &VT) {
469       if (!LegalTypes) return true;
470       return TLI.isTypeLegal(VT);
471     }
472
473     /// Convenience wrapper around TargetLowering::getSetCCResultType
474     EVT getSetCCResultType(EVT VT) const {
475       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
476     }
477   };
478 }
479
480
481 namespace {
482 /// This class is a DAGUpdateListener that removes any deleted
483 /// nodes from the worklist.
484 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
485   DAGCombiner &DC;
486 public:
487   explicit WorklistRemover(DAGCombiner &dc)
488     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
489
490   void NodeDeleted(SDNode *N, SDNode *E) override {
491     DC.removeFromWorklist(N);
492   }
493 };
494 }
495
496 //===----------------------------------------------------------------------===//
497 //  TargetLowering::DAGCombinerInfo implementation
498 //===----------------------------------------------------------------------===//
499
500 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
501   ((DAGCombiner*)DC)->AddToWorklist(N);
502 }
503
504 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
505   ((DAGCombiner*)DC)->removeFromWorklist(N);
506 }
507
508 SDValue TargetLowering::DAGCombinerInfo::
509 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
510   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
511 }
512
513 SDValue TargetLowering::DAGCombinerInfo::
514 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
515   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
516 }
517
518
519 SDValue TargetLowering::DAGCombinerInfo::
520 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
521   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
522 }
523
524 void TargetLowering::DAGCombinerInfo::
525 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
526   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
527 }
528
529 //===----------------------------------------------------------------------===//
530 // Helper Functions
531 //===----------------------------------------------------------------------===//
532
533 void DAGCombiner::deleteAndRecombine(SDNode *N) {
534   removeFromWorklist(N);
535
536   // If the operands of this node are only used by the node, they will now be
537   // dead. Make sure to re-visit them and recursively delete dead nodes.
538   for (const SDValue &Op : N->ops())
539     // For an operand generating multiple values, one of the values may
540     // become dead allowing further simplification (e.g. split index
541     // arithmetic from an indexed load).
542     if (Op->hasOneUse() || Op->getNumValues() > 1)
543       AddToWorklist(Op.getNode());
544
545   DAG.DeleteNode(N);
546 }
547
548 /// Return 1 if we can compute the negated form of the specified expression for
549 /// the same cost as the expression itself, or 2 if we can compute the negated
550 /// form more cheaply than the expression itself.
551 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
552                                const TargetLowering &TLI,
553                                const TargetOptions *Options,
554                                unsigned Depth = 0) {
555   // fneg is removable even if it has multiple uses.
556   if (Op.getOpcode() == ISD::FNEG) return 2;
557
558   // Don't allow anything with multiple uses.
559   if (!Op.hasOneUse()) return 0;
560
561   // Don't recurse exponentially.
562   if (Depth > 6) return 0;
563
564   switch (Op.getOpcode()) {
565   default: return false;
566   case ISD::ConstantFP:
567     // Don't invert constant FP values after legalize.  The negated constant
568     // isn't necessarily legal.
569     return LegalOperations ? 0 : 1;
570   case ISD::FADD:
571     // FIXME: determine better conditions for this xform.
572     if (!Options->UnsafeFPMath) return 0;
573
574     // After operation legalization, it might not be legal to create new FSUBs.
575     if (LegalOperations &&
576         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
577       return 0;
578
579     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
580     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
581                                     Options, Depth + 1))
582       return V;
583     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
584     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
585                               Depth + 1);
586   case ISD::FSUB:
587     // We can't turn -(A-B) into B-A when we honor signed zeros.
588     if (!Options->UnsafeFPMath) return 0;
589
590     // fold (fneg (fsub A, B)) -> (fsub B, A)
591     return 1;
592
593   case ISD::FMUL:
594   case ISD::FDIV:
595     if (Options->HonorSignDependentRoundingFPMath()) return 0;
596
597     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
598     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
599                                     Options, Depth + 1))
600       return V;
601
602     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
603                               Depth + 1);
604
605   case ISD::FP_EXTEND:
606   case ISD::FP_ROUND:
607   case ISD::FSIN:
608     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
609                               Depth + 1);
610   }
611 }
612
613 /// If isNegatibleForFree returns true, return the newly negated expression.
614 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
615                                     bool LegalOperations, unsigned Depth = 0) {
616   const TargetOptions &Options = DAG.getTarget().Options;
617   // fneg is removable even if it has multiple uses.
618   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
619
620   // Don't allow anything with multiple uses.
621   assert(Op.hasOneUse() && "Unknown reuse!");
622
623   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
624
625   const SDNodeFlags *Flags = Op.getNode()->getFlags();
626
627   switch (Op.getOpcode()) {
628   default: llvm_unreachable("Unknown code");
629   case ISD::ConstantFP: {
630     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
631     V.changeSign();
632     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
633   }
634   case ISD::FADD:
635     // FIXME: determine better conditions for this xform.
636     assert(Options.UnsafeFPMath);
637
638     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
639     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
640                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
641       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
642                          GetNegatedExpression(Op.getOperand(0), DAG,
643                                               LegalOperations, Depth+1),
644                          Op.getOperand(1), Flags);
645     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
646     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
647                        GetNegatedExpression(Op.getOperand(1), DAG,
648                                             LegalOperations, Depth+1),
649                        Op.getOperand(0), Flags);
650   case ISD::FSUB:
651     // We can't turn -(A-B) into B-A when we honor signed zeros.
652     assert(Options.UnsafeFPMath);
653
654     // fold (fneg (fsub 0, B)) -> B
655     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
656       if (N0CFP->isZero())
657         return Op.getOperand(1);
658
659     // fold (fneg (fsub A, B)) -> (fsub B, A)
660     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
661                        Op.getOperand(1), Op.getOperand(0), Flags);
662
663   case ISD::FMUL:
664   case ISD::FDIV:
665     assert(!Options.HonorSignDependentRoundingFPMath());
666
667     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
668     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
669                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
670       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
671                          GetNegatedExpression(Op.getOperand(0), DAG,
672                                               LegalOperations, Depth+1),
673                          Op.getOperand(1), Flags);
674
675     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
676     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
677                        Op.getOperand(0),
678                        GetNegatedExpression(Op.getOperand(1), DAG,
679                                             LegalOperations, Depth+1), Flags);
680
681   case ISD::FP_EXTEND:
682   case ISD::FSIN:
683     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
684                        GetNegatedExpression(Op.getOperand(0), DAG,
685                                             LegalOperations, Depth+1));
686   case ISD::FP_ROUND:
687       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
688                          GetNegatedExpression(Op.getOperand(0), DAG,
689                                               LegalOperations, Depth+1),
690                          Op.getOperand(1));
691   }
692 }
693
694 // Return true if this node is a setcc, or is a select_cc
695 // that selects between the target values used for true and false, making it
696 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
697 // the appropriate nodes based on the type of node we are checking. This
698 // simplifies life a bit for the callers.
699 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
700                                     SDValue &CC) const {
701   if (N.getOpcode() == ISD::SETCC) {
702     LHS = N.getOperand(0);
703     RHS = N.getOperand(1);
704     CC  = N.getOperand(2);
705     return true;
706   }
707
708   if (N.getOpcode() != ISD::SELECT_CC ||
709       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
710       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
711     return false;
712
713   if (TLI.getBooleanContents(N.getValueType()) ==
714       TargetLowering::UndefinedBooleanContent)
715     return false;
716
717   LHS = N.getOperand(0);
718   RHS = N.getOperand(1);
719   CC  = N.getOperand(4);
720   return true;
721 }
722
723 /// Return true if this is a SetCC-equivalent operation with only one use.
724 /// If this is true, it allows the users to invert the operation for free when
725 /// it is profitable to do so.
726 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
727   SDValue N0, N1, N2;
728   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
729     return true;
730   return false;
731 }
732
733 /// Returns true if N is a BUILD_VECTOR node whose
734 /// elements are all the same constant or undefined.
735 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
736   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
737   if (!C)
738     return false;
739
740   APInt SplatUndef;
741   unsigned SplatBitSize;
742   bool HasAnyUndefs;
743   EVT EltVT = N->getValueType(0).getVectorElementType();
744   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
745                              HasAnyUndefs) &&
746           EltVT.getSizeInBits() >= SplatBitSize);
747 }
748
749 // \brief Returns the SDNode if it is a constant integer BuildVector
750 // or constant integer.
751 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
752   if (isa<ConstantSDNode>(N))
753     return N.getNode();
754   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
755     return N.getNode();
756   return nullptr;
757 }
758
759 // \brief Returns the SDNode if it is a constant float BuildVector
760 // or constant float.
761 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
762   if (isa<ConstantFPSDNode>(N))
763     return N.getNode();
764   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
765     return N.getNode();
766   return nullptr;
767 }
768
769 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
770 // int.
771 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
772   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
773     return CN;
774
775   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
776     BitVector UndefElements;
777     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
778
779     // BuildVectors can truncate their operands. Ignore that case here.
780     // FIXME: We blindly ignore splats which include undef which is overly
781     // pessimistic.
782     if (CN && UndefElements.none() &&
783         CN->getValueType(0) == N.getValueType().getScalarType())
784       return CN;
785   }
786
787   return nullptr;
788 }
789
790 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
791 // float.
792 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
793   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
794     return CN;
795
796   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
797     BitVector UndefElements;
798     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
799
800     if (CN && UndefElements.none())
801       return CN;
802   }
803
804   return nullptr;
805 }
806
807 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
808                                     SDValue N0, SDValue N1) {
809   EVT VT = N0.getValueType();
810   if (N0.getOpcode() == Opc) {
811     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
812       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
813         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
814         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
815           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
816         return SDValue();
817       }
818       if (N0.hasOneUse()) {
819         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
820         // use
821         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
822         if (!OpNode.getNode())
823           return SDValue();
824         AddToWorklist(OpNode.getNode());
825         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
826       }
827     }
828   }
829
830   if (N1.getOpcode() == Opc) {
831     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
832       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
833         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
834         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
835           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
836         return SDValue();
837       }
838       if (N1.hasOneUse()) {
839         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
840         // use
841         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
842         if (!OpNode.getNode())
843           return SDValue();
844         AddToWorklist(OpNode.getNode());
845         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
846       }
847     }
848   }
849
850   return SDValue();
851 }
852
853 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
854                                bool AddTo) {
855   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
856   ++NodesCombined;
857   DEBUG(dbgs() << "\nReplacing.1 ";
858         N->dump(&DAG);
859         dbgs() << "\nWith: ";
860         To[0].getNode()->dump(&DAG);
861         dbgs() << " and " << NumTo-1 << " other values\n");
862   for (unsigned i = 0, e = NumTo; i != e; ++i)
863     assert((!To[i].getNode() ||
864             N->getValueType(i) == To[i].getValueType()) &&
865            "Cannot combine value to value of different type!");
866
867   WorklistRemover DeadNodes(*this);
868   DAG.ReplaceAllUsesWith(N, To);
869   if (AddTo) {
870     // Push the new nodes and any users onto the worklist
871     for (unsigned i = 0, e = NumTo; i != e; ++i) {
872       if (To[i].getNode()) {
873         AddToWorklist(To[i].getNode());
874         AddUsersToWorklist(To[i].getNode());
875       }
876     }
877   }
878
879   // Finally, if the node is now dead, remove it from the graph.  The node
880   // may not be dead if the replacement process recursively simplified to
881   // something else needing this node.
882   if (N->use_empty())
883     deleteAndRecombine(N);
884   return SDValue(N, 0);
885 }
886
887 void DAGCombiner::
888 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
889   // Replace all uses.  If any nodes become isomorphic to other nodes and
890   // are deleted, make sure to remove them from our worklist.
891   WorklistRemover DeadNodes(*this);
892   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
893
894   // Push the new node and any (possibly new) users onto the worklist.
895   AddToWorklist(TLO.New.getNode());
896   AddUsersToWorklist(TLO.New.getNode());
897
898   // Finally, if the node is now dead, remove it from the graph.  The node
899   // may not be dead if the replacement process recursively simplified to
900   // something else needing this node.
901   if (TLO.Old.getNode()->use_empty())
902     deleteAndRecombine(TLO.Old.getNode());
903 }
904
905 /// Check the specified integer node value to see if it can be simplified or if
906 /// things it uses can be simplified by bit propagation. If so, return true.
907 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
908   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
909   APInt KnownZero, KnownOne;
910   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
911     return false;
912
913   // Revisit the node.
914   AddToWorklist(Op.getNode());
915
916   // Replace the old value with the new one.
917   ++NodesCombined;
918   DEBUG(dbgs() << "\nReplacing.2 ";
919         TLO.Old.getNode()->dump(&DAG);
920         dbgs() << "\nWith: ";
921         TLO.New.getNode()->dump(&DAG);
922         dbgs() << '\n');
923
924   CommitTargetLoweringOpt(TLO);
925   return true;
926 }
927
928 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
929   SDLoc dl(Load);
930   EVT VT = Load->getValueType(0);
931   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
932
933   DEBUG(dbgs() << "\nReplacing.9 ";
934         Load->dump(&DAG);
935         dbgs() << "\nWith: ";
936         Trunc.getNode()->dump(&DAG);
937         dbgs() << '\n');
938   WorklistRemover DeadNodes(*this);
939   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
940   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
941   deleteAndRecombine(Load);
942   AddToWorklist(Trunc.getNode());
943 }
944
945 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
946   Replace = false;
947   SDLoc dl(Op);
948   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
949     EVT MemVT = LD->getMemoryVT();
950     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
951       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
952                                                        : ISD::EXTLOAD)
953       : LD->getExtensionType();
954     Replace = true;
955     return DAG.getExtLoad(ExtType, dl, PVT,
956                           LD->getChain(), LD->getBasePtr(),
957                           MemVT, LD->getMemOperand());
958   }
959
960   unsigned Opc = Op.getOpcode();
961   switch (Opc) {
962   default: break;
963   case ISD::AssertSext:
964     return DAG.getNode(ISD::AssertSext, dl, PVT,
965                        SExtPromoteOperand(Op.getOperand(0), PVT),
966                        Op.getOperand(1));
967   case ISD::AssertZext:
968     return DAG.getNode(ISD::AssertZext, dl, PVT,
969                        ZExtPromoteOperand(Op.getOperand(0), PVT),
970                        Op.getOperand(1));
971   case ISD::Constant: {
972     unsigned ExtOpc =
973       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
974     return DAG.getNode(ExtOpc, dl, PVT, Op);
975   }
976   }
977
978   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
979     return SDValue();
980   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
981 }
982
983 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
984   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
985     return SDValue();
986   EVT OldVT = Op.getValueType();
987   SDLoc dl(Op);
988   bool Replace = false;
989   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
990   if (!NewOp.getNode())
991     return SDValue();
992   AddToWorklist(NewOp.getNode());
993
994   if (Replace)
995     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
996   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
997                      DAG.getValueType(OldVT));
998 }
999
1000 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1001   EVT OldVT = Op.getValueType();
1002   SDLoc dl(Op);
1003   bool Replace = false;
1004   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1005   if (!NewOp.getNode())
1006     return SDValue();
1007   AddToWorklist(NewOp.getNode());
1008
1009   if (Replace)
1010     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1011   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1012 }
1013
1014 /// Promote the specified integer binary operation if the target indicates it is
1015 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1016 /// i32 since i16 instructions are longer.
1017 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1018   if (!LegalOperations)
1019     return SDValue();
1020
1021   EVT VT = Op.getValueType();
1022   if (VT.isVector() || !VT.isInteger())
1023     return SDValue();
1024
1025   // If operation type is 'undesirable', e.g. i16 on x86, consider
1026   // promoting it.
1027   unsigned Opc = Op.getOpcode();
1028   if (TLI.isTypeDesirableForOp(Opc, VT))
1029     return SDValue();
1030
1031   EVT PVT = VT;
1032   // Consult target whether it is a good idea to promote this operation and
1033   // what's the right type to promote it to.
1034   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1035     assert(PVT != VT && "Don't know what type to promote to!");
1036
1037     bool Replace0 = false;
1038     SDValue N0 = Op.getOperand(0);
1039     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1040     if (!NN0.getNode())
1041       return SDValue();
1042
1043     bool Replace1 = false;
1044     SDValue N1 = Op.getOperand(1);
1045     SDValue NN1;
1046     if (N0 == N1)
1047       NN1 = NN0;
1048     else {
1049       NN1 = PromoteOperand(N1, PVT, Replace1);
1050       if (!NN1.getNode())
1051         return SDValue();
1052     }
1053
1054     AddToWorklist(NN0.getNode());
1055     if (NN1.getNode())
1056       AddToWorklist(NN1.getNode());
1057
1058     if (Replace0)
1059       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1060     if (Replace1)
1061       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1062
1063     DEBUG(dbgs() << "\nPromoting ";
1064           Op.getNode()->dump(&DAG));
1065     SDLoc dl(Op);
1066     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1067                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1068   }
1069   return SDValue();
1070 }
1071
1072 /// Promote the specified integer shift operation if the target indicates it is
1073 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1074 /// i32 since i16 instructions are longer.
1075 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1076   if (!LegalOperations)
1077     return SDValue();
1078
1079   EVT VT = Op.getValueType();
1080   if (VT.isVector() || !VT.isInteger())
1081     return SDValue();
1082
1083   // If operation type is 'undesirable', e.g. i16 on x86, consider
1084   // promoting it.
1085   unsigned Opc = Op.getOpcode();
1086   if (TLI.isTypeDesirableForOp(Opc, VT))
1087     return SDValue();
1088
1089   EVT PVT = VT;
1090   // Consult target whether it is a good idea to promote this operation and
1091   // what's the right type to promote it to.
1092   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1093     assert(PVT != VT && "Don't know what type to promote to!");
1094
1095     bool Replace = false;
1096     SDValue N0 = Op.getOperand(0);
1097     if (Opc == ISD::SRA)
1098       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1099     else if (Opc == ISD::SRL)
1100       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1101     else
1102       N0 = PromoteOperand(N0, PVT, Replace);
1103     if (!N0.getNode())
1104       return SDValue();
1105
1106     AddToWorklist(N0.getNode());
1107     if (Replace)
1108       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1109
1110     DEBUG(dbgs() << "\nPromoting ";
1111           Op.getNode()->dump(&DAG));
1112     SDLoc dl(Op);
1113     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1114                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1115   }
1116   return SDValue();
1117 }
1118
1119 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1120   if (!LegalOperations)
1121     return SDValue();
1122
1123   EVT VT = Op.getValueType();
1124   if (VT.isVector() || !VT.isInteger())
1125     return SDValue();
1126
1127   // If operation type is 'undesirable', e.g. i16 on x86, consider
1128   // promoting it.
1129   unsigned Opc = Op.getOpcode();
1130   if (TLI.isTypeDesirableForOp(Opc, VT))
1131     return SDValue();
1132
1133   EVT PVT = VT;
1134   // Consult target whether it is a good idea to promote this operation and
1135   // what's the right type to promote it to.
1136   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1137     assert(PVT != VT && "Don't know what type to promote to!");
1138     // fold (aext (aext x)) -> (aext x)
1139     // fold (aext (zext x)) -> (zext x)
1140     // fold (aext (sext x)) -> (sext x)
1141     DEBUG(dbgs() << "\nPromoting ";
1142           Op.getNode()->dump(&DAG));
1143     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1144   }
1145   return SDValue();
1146 }
1147
1148 bool DAGCombiner::PromoteLoad(SDValue Op) {
1149   if (!LegalOperations)
1150     return false;
1151
1152   EVT VT = Op.getValueType();
1153   if (VT.isVector() || !VT.isInteger())
1154     return false;
1155
1156   // If operation type is 'undesirable', e.g. i16 on x86, consider
1157   // promoting it.
1158   unsigned Opc = Op.getOpcode();
1159   if (TLI.isTypeDesirableForOp(Opc, VT))
1160     return false;
1161
1162   EVT PVT = VT;
1163   // Consult target whether it is a good idea to promote this operation and
1164   // what's the right type to promote it to.
1165   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1166     assert(PVT != VT && "Don't know what type to promote to!");
1167
1168     SDLoc dl(Op);
1169     SDNode *N = Op.getNode();
1170     LoadSDNode *LD = cast<LoadSDNode>(N);
1171     EVT MemVT = LD->getMemoryVT();
1172     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1173       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1174                                                        : ISD::EXTLOAD)
1175       : LD->getExtensionType();
1176     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1177                                    LD->getChain(), LD->getBasePtr(),
1178                                    MemVT, LD->getMemOperand());
1179     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1180
1181     DEBUG(dbgs() << "\nPromoting ";
1182           N->dump(&DAG);
1183           dbgs() << "\nTo: ";
1184           Result.getNode()->dump(&DAG);
1185           dbgs() << '\n');
1186     WorklistRemover DeadNodes(*this);
1187     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1188     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1189     deleteAndRecombine(N);
1190     AddToWorklist(Result.getNode());
1191     return true;
1192   }
1193   return false;
1194 }
1195
1196 /// \brief Recursively delete a node which has no uses and any operands for
1197 /// which it is the only use.
1198 ///
1199 /// Note that this both deletes the nodes and removes them from the worklist.
1200 /// It also adds any nodes who have had a user deleted to the worklist as they
1201 /// may now have only one use and subject to other combines.
1202 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1203   if (!N->use_empty())
1204     return false;
1205
1206   SmallSetVector<SDNode *, 16> Nodes;
1207   Nodes.insert(N);
1208   do {
1209     N = Nodes.pop_back_val();
1210     if (!N)
1211       continue;
1212
1213     if (N->use_empty()) {
1214       for (const SDValue &ChildN : N->op_values())
1215         Nodes.insert(ChildN.getNode());
1216
1217       removeFromWorklist(N);
1218       DAG.DeleteNode(N);
1219     } else {
1220       AddToWorklist(N);
1221     }
1222   } while (!Nodes.empty());
1223   return true;
1224 }
1225
1226 //===----------------------------------------------------------------------===//
1227 //  Main DAG Combiner implementation
1228 //===----------------------------------------------------------------------===//
1229
1230 void DAGCombiner::Run(CombineLevel AtLevel) {
1231   // set the instance variables, so that the various visit routines may use it.
1232   Level = AtLevel;
1233   LegalOperations = Level >= AfterLegalizeVectorOps;
1234   LegalTypes = Level >= AfterLegalizeTypes;
1235
1236   // Add all the dag nodes to the worklist.
1237   for (SDNode &Node : DAG.allnodes())
1238     AddToWorklist(&Node);
1239
1240   // Create a dummy node (which is not added to allnodes), that adds a reference
1241   // to the root node, preventing it from being deleted, and tracking any
1242   // changes of the root.
1243   HandleSDNode Dummy(DAG.getRoot());
1244
1245   // while the worklist isn't empty, find a node and
1246   // try and combine it.
1247   while (!WorklistMap.empty()) {
1248     SDNode *N;
1249     // The Worklist holds the SDNodes in order, but it may contain null entries.
1250     do {
1251       N = Worklist.pop_back_val();
1252     } while (!N);
1253
1254     bool GoodWorklistEntry = WorklistMap.erase(N);
1255     (void)GoodWorklistEntry;
1256     assert(GoodWorklistEntry &&
1257            "Found a worklist entry without a corresponding map entry!");
1258
1259     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1260     // N is deleted from the DAG, since they too may now be dead or may have a
1261     // reduced number of uses, allowing other xforms.
1262     if (recursivelyDeleteUnusedNodes(N))
1263       continue;
1264
1265     WorklistRemover DeadNodes(*this);
1266
1267     // If this combine is running after legalizing the DAG, re-legalize any
1268     // nodes pulled off the worklist.
1269     if (Level == AfterLegalizeDAG) {
1270       SmallSetVector<SDNode *, 16> UpdatedNodes;
1271       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1272
1273       for (SDNode *LN : UpdatedNodes) {
1274         AddToWorklist(LN);
1275         AddUsersToWorklist(LN);
1276       }
1277       if (!NIsValid)
1278         continue;
1279     }
1280
1281     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1282
1283     // Add any operands of the new node which have not yet been combined to the
1284     // worklist as well. Because the worklist uniques things already, this
1285     // won't repeatedly process the same operand.
1286     CombinedNodes.insert(N);
1287     for (const SDValue &ChildN : N->op_values())
1288       if (!CombinedNodes.count(ChildN.getNode()))
1289         AddToWorklist(ChildN.getNode());
1290
1291     SDValue RV = combine(N);
1292
1293     if (!RV.getNode())
1294       continue;
1295
1296     ++NodesCombined;
1297
1298     // If we get back the same node we passed in, rather than a new node or
1299     // zero, we know that the node must have defined multiple values and
1300     // CombineTo was used.  Since CombineTo takes care of the worklist
1301     // mechanics for us, we have no work to do in this case.
1302     if (RV.getNode() == N)
1303       continue;
1304
1305     assert(N->getOpcode() != ISD::DELETED_NODE &&
1306            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1307            "Node was deleted but visit returned new node!");
1308
1309     DEBUG(dbgs() << " ... into: ";
1310           RV.getNode()->dump(&DAG));
1311
1312     // Transfer debug value.
1313     DAG.TransferDbgValues(SDValue(N, 0), RV);
1314     if (N->getNumValues() == RV.getNode()->getNumValues())
1315       DAG.ReplaceAllUsesWith(N, RV.getNode());
1316     else {
1317       assert(N->getValueType(0) == RV.getValueType() &&
1318              N->getNumValues() == 1 && "Type mismatch");
1319       SDValue OpV = RV;
1320       DAG.ReplaceAllUsesWith(N, &OpV);
1321     }
1322
1323     // Push the new node and any users onto the worklist
1324     AddToWorklist(RV.getNode());
1325     AddUsersToWorklist(RV.getNode());
1326
1327     // Finally, if the node is now dead, remove it from the graph.  The node
1328     // may not be dead if the replacement process recursively simplified to
1329     // something else needing this node. This will also take care of adding any
1330     // operands which have lost a user to the worklist.
1331     recursivelyDeleteUnusedNodes(N);
1332   }
1333
1334   // If the root changed (e.g. it was a dead load, update the root).
1335   DAG.setRoot(Dummy.getValue());
1336   DAG.RemoveDeadNodes();
1337 }
1338
1339 SDValue DAGCombiner::visit(SDNode *N) {
1340   switch (N->getOpcode()) {
1341   default: break;
1342   case ISD::TokenFactor:        return visitTokenFactor(N);
1343   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1344   case ISD::ADD:                return visitADD(N);
1345   case ISD::SUB:                return visitSUB(N);
1346   case ISD::ADDC:               return visitADDC(N);
1347   case ISD::SUBC:               return visitSUBC(N);
1348   case ISD::ADDE:               return visitADDE(N);
1349   case ISD::SUBE:               return visitSUBE(N);
1350   case ISD::MUL:                return visitMUL(N);
1351   case ISD::SDIV:               return visitSDIV(N);
1352   case ISD::UDIV:               return visitUDIV(N);
1353   case ISD::SREM:
1354   case ISD::UREM:               return visitREM(N);
1355   case ISD::MULHU:              return visitMULHU(N);
1356   case ISD::MULHS:              return visitMULHS(N);
1357   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1358   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1359   case ISD::SMULO:              return visitSMULO(N);
1360   case ISD::UMULO:              return visitUMULO(N);
1361   case ISD::SDIVREM:            return visitSDIVREM(N);
1362   case ISD::UDIVREM:            return visitUDIVREM(N);
1363   case ISD::SMIN:
1364   case ISD::SMAX:
1365   case ISD::UMIN:
1366   case ISD::UMAX:               return visitIMINMAX(N);
1367   case ISD::AND:                return visitAND(N);
1368   case ISD::OR:                 return visitOR(N);
1369   case ISD::XOR:                return visitXOR(N);
1370   case ISD::SHL:                return visitSHL(N);
1371   case ISD::SRA:                return visitSRA(N);
1372   case ISD::SRL:                return visitSRL(N);
1373   case ISD::ROTR:
1374   case ISD::ROTL:               return visitRotate(N);
1375   case ISD::BSWAP:              return visitBSWAP(N);
1376   case ISD::CTLZ:               return visitCTLZ(N);
1377   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1378   case ISD::CTTZ:               return visitCTTZ(N);
1379   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1380   case ISD::CTPOP:              return visitCTPOP(N);
1381   case ISD::SELECT:             return visitSELECT(N);
1382   case ISD::VSELECT:            return visitVSELECT(N);
1383   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1384   case ISD::SETCC:              return visitSETCC(N);
1385   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1386   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1387   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1388   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1389   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1390   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1391   case ISD::BITCAST:            return visitBITCAST(N);
1392   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1393   case ISD::FADD:               return visitFADD(N);
1394   case ISD::FSUB:               return visitFSUB(N);
1395   case ISD::FMUL:               return visitFMUL(N);
1396   case ISD::FMA:                return visitFMA(N);
1397   case ISD::FDIV:               return visitFDIV(N);
1398   case ISD::FREM:               return visitFREM(N);
1399   case ISD::FSQRT:              return visitFSQRT(N);
1400   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1401   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1402   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1403   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1404   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1405   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1406   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1407   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1408   case ISD::FNEG:               return visitFNEG(N);
1409   case ISD::FABS:               return visitFABS(N);
1410   case ISD::FFLOOR:             return visitFFLOOR(N);
1411   case ISD::FMINNUM:            return visitFMINNUM(N);
1412   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1413   case ISD::FCEIL:              return visitFCEIL(N);
1414   case ISD::FTRUNC:             return visitFTRUNC(N);
1415   case ISD::BRCOND:             return visitBRCOND(N);
1416   case ISD::BR_CC:              return visitBR_CC(N);
1417   case ISD::LOAD:               return visitLOAD(N);
1418   case ISD::STORE:              return visitSTORE(N);
1419   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1420   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1421   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1422   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1423   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1424   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1425   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1426   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1427   case ISD::MGATHER:            return visitMGATHER(N);
1428   case ISD::MLOAD:              return visitMLOAD(N);
1429   case ISD::MSCATTER:           return visitMSCATTER(N);
1430   case ISD::MSTORE:             return visitMSTORE(N);
1431   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1432   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1433   }
1434   return SDValue();
1435 }
1436
1437 SDValue DAGCombiner::combine(SDNode *N) {
1438   SDValue RV = visit(N);
1439
1440   // If nothing happened, try a target-specific DAG combine.
1441   if (!RV.getNode()) {
1442     assert(N->getOpcode() != ISD::DELETED_NODE &&
1443            "Node was deleted but visit returned NULL!");
1444
1445     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1446         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1447
1448       // Expose the DAG combiner to the target combiner impls.
1449       TargetLowering::DAGCombinerInfo
1450         DagCombineInfo(DAG, Level, false, this);
1451
1452       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1453     }
1454   }
1455
1456   // If nothing happened still, try promoting the operation.
1457   if (!RV.getNode()) {
1458     switch (N->getOpcode()) {
1459     default: break;
1460     case ISD::ADD:
1461     case ISD::SUB:
1462     case ISD::MUL:
1463     case ISD::AND:
1464     case ISD::OR:
1465     case ISD::XOR:
1466       RV = PromoteIntBinOp(SDValue(N, 0));
1467       break;
1468     case ISD::SHL:
1469     case ISD::SRA:
1470     case ISD::SRL:
1471       RV = PromoteIntShiftOp(SDValue(N, 0));
1472       break;
1473     case ISD::SIGN_EXTEND:
1474     case ISD::ZERO_EXTEND:
1475     case ISD::ANY_EXTEND:
1476       RV = PromoteExtend(SDValue(N, 0));
1477       break;
1478     case ISD::LOAD:
1479       if (PromoteLoad(SDValue(N, 0)))
1480         RV = SDValue(N, 0);
1481       break;
1482     }
1483   }
1484
1485   // If N is a commutative binary node, try commuting it to enable more
1486   // sdisel CSE.
1487   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1488       N->getNumValues() == 1) {
1489     SDValue N0 = N->getOperand(0);
1490     SDValue N1 = N->getOperand(1);
1491
1492     // Constant operands are canonicalized to RHS.
1493     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1494       SDValue Ops[] = {N1, N0};
1495       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1496                                             N->getFlags());
1497       if (CSENode)
1498         return SDValue(CSENode, 0);
1499     }
1500   }
1501
1502   return RV;
1503 }
1504
1505 /// Given a node, return its input chain if it has one, otherwise return a null
1506 /// sd operand.
1507 static SDValue getInputChainForNode(SDNode *N) {
1508   if (unsigned NumOps = N->getNumOperands()) {
1509     if (N->getOperand(0).getValueType() == MVT::Other)
1510       return N->getOperand(0);
1511     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1512       return N->getOperand(NumOps-1);
1513     for (unsigned i = 1; i < NumOps-1; ++i)
1514       if (N->getOperand(i).getValueType() == MVT::Other)
1515         return N->getOperand(i);
1516   }
1517   return SDValue();
1518 }
1519
1520 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1521   // If N has two operands, where one has an input chain equal to the other,
1522   // the 'other' chain is redundant.
1523   if (N->getNumOperands() == 2) {
1524     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1525       return N->getOperand(0);
1526     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1527       return N->getOperand(1);
1528   }
1529
1530   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1531   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1532   SmallPtrSet<SDNode*, 16> SeenOps;
1533   bool Changed = false;             // If we should replace this token factor.
1534
1535   // Start out with this token factor.
1536   TFs.push_back(N);
1537
1538   // Iterate through token factors.  The TFs grows when new token factors are
1539   // encountered.
1540   for (unsigned i = 0; i < TFs.size(); ++i) {
1541     SDNode *TF = TFs[i];
1542
1543     // Check each of the operands.
1544     for (const SDValue &Op : TF->op_values()) {
1545
1546       switch (Op.getOpcode()) {
1547       case ISD::EntryToken:
1548         // Entry tokens don't need to be added to the list. They are
1549         // redundant.
1550         Changed = true;
1551         break;
1552
1553       case ISD::TokenFactor:
1554         if (Op.hasOneUse() &&
1555             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1556           // Queue up for processing.
1557           TFs.push_back(Op.getNode());
1558           // Clean up in case the token factor is removed.
1559           AddToWorklist(Op.getNode());
1560           Changed = true;
1561           break;
1562         }
1563         // Fall thru
1564
1565       default:
1566         // Only add if it isn't already in the list.
1567         if (SeenOps.insert(Op.getNode()).second)
1568           Ops.push_back(Op);
1569         else
1570           Changed = true;
1571         break;
1572       }
1573     }
1574   }
1575
1576   SDValue Result;
1577
1578   // If we've changed things around then replace token factor.
1579   if (Changed) {
1580     if (Ops.empty()) {
1581       // The entry token is the only possible outcome.
1582       Result = DAG.getEntryNode();
1583     } else {
1584       // New and improved token factor.
1585       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1586     }
1587
1588     // Add users to worklist if AA is enabled, since it may introduce
1589     // a lot of new chained token factors while removing memory deps.
1590     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1591       : DAG.getSubtarget().useAA();
1592     return CombineTo(N, Result, UseAA /*add to worklist*/);
1593   }
1594
1595   return Result;
1596 }
1597
1598 /// MERGE_VALUES can always be eliminated.
1599 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1600   WorklistRemover DeadNodes(*this);
1601   // Replacing results may cause a different MERGE_VALUES to suddenly
1602   // be CSE'd with N, and carry its uses with it. Iterate until no
1603   // uses remain, to ensure that the node can be safely deleted.
1604   // First add the users of this node to the work list so that they
1605   // can be tried again once they have new operands.
1606   AddUsersToWorklist(N);
1607   do {
1608     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1609       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1610   } while (!N->use_empty());
1611   deleteAndRecombine(N);
1612   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1613 }
1614
1615 static bool isNullConstant(SDValue V) {
1616   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1617   return Const != nullptr && Const->isNullValue();
1618 }
1619
1620 static bool isNullFPConstant(SDValue V) {
1621   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1622   return Const != nullptr && Const->isZero() && !Const->isNegative();
1623 }
1624
1625 static bool isAllOnesConstant(SDValue V) {
1626   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1627   return Const != nullptr && Const->isAllOnesValue();
1628 }
1629
1630 static bool isOneConstant(SDValue V) {
1631   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1632   return Const != nullptr && Const->isOne();
1633 }
1634
1635 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1636 /// ContantSDNode pointer else nullptr.
1637 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1638   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1639   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1640 }
1641
1642 SDValue DAGCombiner::visitADD(SDNode *N) {
1643   SDValue N0 = N->getOperand(0);
1644   SDValue N1 = N->getOperand(1);
1645   EVT VT = N0.getValueType();
1646
1647   // fold vector ops
1648   if (VT.isVector()) {
1649     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1650       return FoldedVOp;
1651
1652     // fold (add x, 0) -> x, vector edition
1653     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1654       return N0;
1655     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1656       return N1;
1657   }
1658
1659   // fold (add x, undef) -> undef
1660   if (N0.getOpcode() == ISD::UNDEF)
1661     return N0;
1662   if (N1.getOpcode() == ISD::UNDEF)
1663     return N1;
1664   // fold (add c1, c2) -> c1+c2
1665   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1666   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1667   if (N0C && N1C)
1668     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1669   // canonicalize constant to RHS
1670   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1671      !isConstantIntBuildVectorOrConstantInt(N1))
1672     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1673   // fold (add x, 0) -> x
1674   if (isNullConstant(N1))
1675     return N0;
1676   // fold (add Sym, c) -> Sym+c
1677   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1678     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1679         GA->getOpcode() == ISD::GlobalAddress)
1680       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1681                                   GA->getOffset() +
1682                                     (uint64_t)N1C->getSExtValue());
1683   // fold ((c1-A)+c2) -> (c1+c2)-A
1684   if (N1C && N0.getOpcode() == ISD::SUB)
1685     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1686       SDLoc DL(N);
1687       return DAG.getNode(ISD::SUB, DL, VT,
1688                          DAG.getConstant(N1C->getAPIntValue()+
1689                                          N0C->getAPIntValue(), DL, VT),
1690                          N0.getOperand(1));
1691     }
1692   // reassociate add
1693   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1694     return RADD;
1695   // fold ((0-A) + B) -> B-A
1696   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1697     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1698   // fold (A + (0-B)) -> A-B
1699   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1700     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1701   // fold (A+(B-A)) -> B
1702   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1703     return N1.getOperand(0);
1704   // fold ((B-A)+A) -> B
1705   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1706     return N0.getOperand(0);
1707   // fold (A+(B-(A+C))) to (B-C)
1708   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1709       N0 == N1.getOperand(1).getOperand(0))
1710     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1711                        N1.getOperand(1).getOperand(1));
1712   // fold (A+(B-(C+A))) to (B-C)
1713   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1714       N0 == N1.getOperand(1).getOperand(1))
1715     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1716                        N1.getOperand(1).getOperand(0));
1717   // fold (A+((B-A)+or-C)) to (B+or-C)
1718   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1719       N1.getOperand(0).getOpcode() == ISD::SUB &&
1720       N0 == N1.getOperand(0).getOperand(1))
1721     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1722                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1723
1724   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1725   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1726     SDValue N00 = N0.getOperand(0);
1727     SDValue N01 = N0.getOperand(1);
1728     SDValue N10 = N1.getOperand(0);
1729     SDValue N11 = N1.getOperand(1);
1730
1731     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1732       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1733                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1734                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1735   }
1736
1737   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1738     return SDValue(N, 0);
1739
1740   // fold (a+b) -> (a|b) iff a and b share no bits.
1741   if (VT.isInteger() && !VT.isVector()) {
1742     APInt LHSZero, LHSOne;
1743     APInt RHSZero, RHSOne;
1744     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1745
1746     if (LHSZero.getBoolValue()) {
1747       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1748
1749       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1750       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1751       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1752         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1753           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1754       }
1755     }
1756   }
1757
1758   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1759   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1760       isNullConstant(N1.getOperand(0).getOperand(0)))
1761     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1762                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1763                                    N1.getOperand(0).getOperand(1),
1764                                    N1.getOperand(1)));
1765   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1766       isNullConstant(N0.getOperand(0).getOperand(0)))
1767     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1768                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1769                                    N0.getOperand(0).getOperand(1),
1770                                    N0.getOperand(1)));
1771
1772   if (N1.getOpcode() == ISD::AND) {
1773     SDValue AndOp0 = N1.getOperand(0);
1774     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1775     unsigned DestBits = VT.getScalarType().getSizeInBits();
1776
1777     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1778     // and similar xforms where the inner op is either ~0 or 0.
1779     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1780       SDLoc DL(N);
1781       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1782     }
1783   }
1784
1785   // add (sext i1), X -> sub X, (zext i1)
1786   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1787       N0.getOperand(0).getValueType() == MVT::i1 &&
1788       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1789     SDLoc DL(N);
1790     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1791     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1792   }
1793
1794   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1795   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1796     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1797     if (TN->getVT() == MVT::i1) {
1798       SDLoc DL(N);
1799       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1800                                  DAG.getConstant(1, DL, VT));
1801       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1802     }
1803   }
1804
1805   return SDValue();
1806 }
1807
1808 SDValue DAGCombiner::visitADDC(SDNode *N) {
1809   SDValue N0 = N->getOperand(0);
1810   SDValue N1 = N->getOperand(1);
1811   EVT VT = N0.getValueType();
1812
1813   // If the flag result is dead, turn this into an ADD.
1814   if (!N->hasAnyUseOfValue(1))
1815     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1816                      DAG.getNode(ISD::CARRY_FALSE,
1817                                  SDLoc(N), MVT::Glue));
1818
1819   // canonicalize constant to RHS.
1820   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1821   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1822   if (N0C && !N1C)
1823     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1824
1825   // fold (addc x, 0) -> x + no carry out
1826   if (isNullConstant(N1))
1827     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1828                                         SDLoc(N), MVT::Glue));
1829
1830   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1831   APInt LHSZero, LHSOne;
1832   APInt RHSZero, RHSOne;
1833   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1834
1835   if (LHSZero.getBoolValue()) {
1836     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1837
1838     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1839     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1840     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1841       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1842                        DAG.getNode(ISD::CARRY_FALSE,
1843                                    SDLoc(N), MVT::Glue));
1844   }
1845
1846   return SDValue();
1847 }
1848
1849 SDValue DAGCombiner::visitADDE(SDNode *N) {
1850   SDValue N0 = N->getOperand(0);
1851   SDValue N1 = N->getOperand(1);
1852   SDValue CarryIn = N->getOperand(2);
1853
1854   // canonicalize constant to RHS
1855   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1856   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1857   if (N0C && !N1C)
1858     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1859                        N1, N0, CarryIn);
1860
1861   // fold (adde x, y, false) -> (addc x, y)
1862   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1863     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1864
1865   return SDValue();
1866 }
1867
1868 // Since it may not be valid to emit a fold to zero for vector initializers
1869 // check if we can before folding.
1870 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1871                              SelectionDAG &DAG,
1872                              bool LegalOperations, bool LegalTypes) {
1873   if (!VT.isVector())
1874     return DAG.getConstant(0, DL, VT);
1875   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1876     return DAG.getConstant(0, DL, VT);
1877   return SDValue();
1878 }
1879
1880 SDValue DAGCombiner::visitSUB(SDNode *N) {
1881   SDValue N0 = N->getOperand(0);
1882   SDValue N1 = N->getOperand(1);
1883   EVT VT = N0.getValueType();
1884
1885   // fold vector ops
1886   if (VT.isVector()) {
1887     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1888       return FoldedVOp;
1889
1890     // fold (sub x, 0) -> x, vector edition
1891     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1892       return N0;
1893   }
1894
1895   // fold (sub x, x) -> 0
1896   // FIXME: Refactor this and xor and other similar operations together.
1897   if (N0 == N1)
1898     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1899   // fold (sub c1, c2) -> c1-c2
1900   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1901   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1902   if (N0C && N1C)
1903     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1904   // fold (sub x, c) -> (add x, -c)
1905   if (N1C) {
1906     SDLoc DL(N);
1907     return DAG.getNode(ISD::ADD, DL, VT, N0,
1908                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1909   }
1910   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1911   if (isAllOnesConstant(N0))
1912     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1913   // fold A-(A-B) -> B
1914   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1915     return N1.getOperand(1);
1916   // fold (A+B)-A -> B
1917   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1918     return N0.getOperand(1);
1919   // fold (A+B)-B -> A
1920   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1921     return N0.getOperand(0);
1922   // fold C2-(A+C1) -> (C2-C1)-A
1923   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1924     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1925   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1926     SDLoc DL(N);
1927     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1928                                    DL, VT);
1929     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1930                        N1.getOperand(0));
1931   }
1932   // fold ((A+(B+or-C))-B) -> A+or-C
1933   if (N0.getOpcode() == ISD::ADD &&
1934       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1935        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1936       N0.getOperand(1).getOperand(0) == N1)
1937     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1938                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1939   // fold ((A+(C+B))-B) -> A+C
1940   if (N0.getOpcode() == ISD::ADD &&
1941       N0.getOperand(1).getOpcode() == ISD::ADD &&
1942       N0.getOperand(1).getOperand(1) == N1)
1943     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1944                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1945   // fold ((A-(B-C))-C) -> A-B
1946   if (N0.getOpcode() == ISD::SUB &&
1947       N0.getOperand(1).getOpcode() == ISD::SUB &&
1948       N0.getOperand(1).getOperand(1) == N1)
1949     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1950                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1951
1952   // If either operand of a sub is undef, the result is undef
1953   if (N0.getOpcode() == ISD::UNDEF)
1954     return N0;
1955   if (N1.getOpcode() == ISD::UNDEF)
1956     return N1;
1957
1958   // If the relocation model supports it, consider symbol offsets.
1959   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1960     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1961       // fold (sub Sym, c) -> Sym-c
1962       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1963         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1964                                     GA->getOffset() -
1965                                       (uint64_t)N1C->getSExtValue());
1966       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1967       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1968         if (GA->getGlobal() == GB->getGlobal())
1969           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1970                                  SDLoc(N), VT);
1971     }
1972
1973   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1974   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1975     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1976     if (TN->getVT() == MVT::i1) {
1977       SDLoc DL(N);
1978       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1979                                  DAG.getConstant(1, DL, VT));
1980       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1981     }
1982   }
1983
1984   return SDValue();
1985 }
1986
1987 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1988   SDValue N0 = N->getOperand(0);
1989   SDValue N1 = N->getOperand(1);
1990   EVT VT = N0.getValueType();
1991   SDLoc DL(N);
1992
1993   // If the flag result is dead, turn this into an SUB.
1994   if (!N->hasAnyUseOfValue(1))
1995     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1996                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1997
1998   // fold (subc x, x) -> 0 + no borrow
1999   if (N0 == N1)
2000     return CombineTo(N, DAG.getConstant(0, DL, VT),
2001                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2002
2003   // fold (subc x, 0) -> x + no borrow
2004   if (isNullConstant(N1))
2005     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, 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, DL, VT, N1, N0),
2010                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2011
2012   return SDValue();
2013 }
2014
2015 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2016   SDValue N0 = N->getOperand(0);
2017   SDValue N1 = N->getOperand(1);
2018   SDValue CarryIn = N->getOperand(2);
2019
2020   // fold (sube x, y, false) -> (subc x, y)
2021   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2022     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2023
2024   return SDValue();
2025 }
2026
2027 SDValue DAGCombiner::visitMUL(SDNode *N) {
2028   SDValue N0 = N->getOperand(0);
2029   SDValue N1 = N->getOperand(1);
2030   EVT VT = N0.getValueType();
2031
2032   // fold (mul x, undef) -> 0
2033   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2034     return DAG.getConstant(0, SDLoc(N), VT);
2035
2036   bool N0IsConst = false;
2037   bool N1IsConst = false;
2038   bool N1IsOpaqueConst = false;
2039   bool N0IsOpaqueConst = false;
2040   APInt ConstValue0, ConstValue1;
2041   // fold vector ops
2042   if (VT.isVector()) {
2043     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2044       return FoldedVOp;
2045
2046     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2047     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2048   } else {
2049     N0IsConst = isa<ConstantSDNode>(N0);
2050     if (N0IsConst) {
2051       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2052       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2053     }
2054     N1IsConst = isa<ConstantSDNode>(N1);
2055     if (N1IsConst) {
2056       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2057       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2058     }
2059   }
2060
2061   // fold (mul c1, c2) -> c1*c2
2062   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2063     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2064                                       N0.getNode(), N1.getNode());
2065
2066   // canonicalize constant to RHS (vector doesn't have to splat)
2067   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2068      !isConstantIntBuildVectorOrConstantInt(N1))
2069     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2070   // fold (mul x, 0) -> 0
2071   if (N1IsConst && ConstValue1 == 0)
2072     return N1;
2073   // We require a splat of the entire scalar bit width for non-contiguous
2074   // bit patterns.
2075   bool IsFullSplat =
2076     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2077   // fold (mul x, 1) -> x
2078   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2079     return N0;
2080   // fold (mul x, -1) -> 0-x
2081   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2082     SDLoc DL(N);
2083     return DAG.getNode(ISD::SUB, DL, VT,
2084                        DAG.getConstant(0, DL, VT), N0);
2085   }
2086   // fold (mul x, (1 << c)) -> x << c
2087   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2088       IsFullSplat) {
2089     SDLoc DL(N);
2090     return DAG.getNode(ISD::SHL, DL, VT, N0,
2091                        DAG.getConstant(ConstValue1.logBase2(), DL,
2092                                        getShiftAmountTy(N0.getValueType())));
2093   }
2094   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2095   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2096       IsFullSplat) {
2097     unsigned Log2Val = (-ConstValue1).logBase2();
2098     SDLoc DL(N);
2099     // FIXME: If the input is something that is easily negated (e.g. a
2100     // single-use add), we should put the negate there.
2101     return DAG.getNode(ISD::SUB, DL, VT,
2102                        DAG.getConstant(0, DL, VT),
2103                        DAG.getNode(ISD::SHL, DL, VT, N0,
2104                             DAG.getConstant(Log2Val, DL,
2105                                       getShiftAmountTy(N0.getValueType()))));
2106   }
2107
2108   APInt Val;
2109   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2110   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2111       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2112                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2113     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2114                              N1, N0.getOperand(1));
2115     AddToWorklist(C3.getNode());
2116     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2117                        N0.getOperand(0), C3);
2118   }
2119
2120   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2121   // use.
2122   {
2123     SDValue Sh(nullptr,0), Y(nullptr,0);
2124     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2125     if (N0.getOpcode() == ISD::SHL &&
2126         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2127                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2128         N0.getNode()->hasOneUse()) {
2129       Sh = N0; Y = N1;
2130     } else if (N1.getOpcode() == ISD::SHL &&
2131                isa<ConstantSDNode>(N1.getOperand(1)) &&
2132                N1.getNode()->hasOneUse()) {
2133       Sh = N1; Y = N0;
2134     }
2135
2136     if (Sh.getNode()) {
2137       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2138                                 Sh.getOperand(0), Y);
2139       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2140                          Mul, Sh.getOperand(1));
2141     }
2142   }
2143
2144   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2145   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2146       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2147                      isa<ConstantSDNode>(N0.getOperand(1))))
2148     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2149                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2150                                    N0.getOperand(0), N1),
2151                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2152                                    N0.getOperand(1), N1));
2153
2154   // reassociate mul
2155   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2156     return RMUL;
2157
2158   return SDValue();
2159 }
2160
2161 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2162   SDValue N0 = N->getOperand(0);
2163   SDValue N1 = N->getOperand(1);
2164   EVT VT = N->getValueType(0);
2165
2166   // fold vector ops
2167   if (VT.isVector())
2168     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2169       return FoldedVOp;
2170
2171   SDLoc DL(N);
2172
2173   // fold (sdiv c1, c2) -> c1/c2
2174   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2175   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2176   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2177     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2178   // fold (sdiv X, 1) -> X
2179   if (N1C && N1C->isOne())
2180     return N0;
2181   // fold (sdiv X, -1) -> 0-X
2182   if (N1C && N1C->isAllOnesValue())
2183     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, DL, N1.getValueType(), N0, N1);
2191   }
2192
2193   // fold (sdiv X, pow2) -> simple ops after legalize
2194   // FIXME: We check for the exact bit here because the generic lowering gives
2195   // better results in that case. The target-specific lowering should learn how
2196   // to handle exact sdivs efficiently.
2197   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2198       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2199       (N1C->getAPIntValue().isPowerOf2() ||
2200        (-N1C->getAPIntValue()).isPowerOf2())) {
2201     // Target-specific implementation of sdiv x, pow2.
2202     if (SDValue Res = BuildSDIVPow2(N))
2203       return Res;
2204
2205     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2206
2207     // Splat the sign bit into the register
2208     SDValue SGN =
2209         DAG.getNode(ISD::SRA, DL, VT, N0,
2210                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2211                                     getShiftAmountTy(N0.getValueType())));
2212     AddToWorklist(SGN.getNode());
2213
2214     // Add (N0 < 0) ? abs2 - 1 : 0;
2215     SDValue SRL =
2216         DAG.getNode(ISD::SRL, DL, VT, SGN,
2217                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2218                                     getShiftAmountTy(SGN.getValueType())));
2219     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2220     AddToWorklist(SRL.getNode());
2221     AddToWorklist(ADD.getNode());    // Divide by pow2
2222     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2223                   DAG.getConstant(lg2, DL,
2224                                   getShiftAmountTy(ADD.getValueType())));
2225
2226     // If we're dividing by a positive value, we're done.  Otherwise, we must
2227     // negate the result.
2228     if (N1C->getAPIntValue().isNonNegative())
2229       return SRA;
2230
2231     AddToWorklist(SRA.getNode());
2232     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2233   }
2234
2235   // If integer divide is expensive and we satisfy the requirements, emit an
2236   // alternate sequence.  Targets may check function attributes for size/speed
2237   // trade-offs.
2238   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2239   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2240     if (SDValue Op = BuildSDIV(N))
2241       return Op;
2242
2243   // undef / X -> 0
2244   if (N0.getOpcode() == ISD::UNDEF)
2245     return DAG.getConstant(0, DL, VT);
2246   // X / undef -> undef
2247   if (N1.getOpcode() == ISD::UNDEF)
2248     return N1;
2249
2250   return SDValue();
2251 }
2252
2253 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2254   SDValue N0 = N->getOperand(0);
2255   SDValue N1 = N->getOperand(1);
2256   EVT VT = N->getValueType(0);
2257
2258   // fold vector ops
2259   if (VT.isVector())
2260     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2261       return FoldedVOp;
2262
2263   SDLoc DL(N);
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, DL, 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     return DAG.getNode(ISD::SRL, DL, VT, N0,
2275                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2276                                        getShiftAmountTy(N0.getValueType())));
2277
2278   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2279   if (N1.getOpcode() == ISD::SHL) {
2280     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2281       if (SHC->getAPIntValue().isPowerOf2()) {
2282         EVT ADDVT = N1.getOperand(1).getValueType();
2283         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2284                                   N1.getOperand(1),
2285                                   DAG.getConstant(SHC->getAPIntValue()
2286                                                                   .logBase2(),
2287                                                   DL, ADDVT));
2288         AddToWorklist(Add.getNode());
2289         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2290       }
2291     }
2292   }
2293
2294   // fold (udiv x, c) -> alternate
2295   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2296   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2297     if (SDValue Op = BuildUDIV(N))
2298       return Op;
2299
2300   // undef / X -> 0
2301   if (N0.getOpcode() == ISD::UNDEF)
2302     return DAG.getConstant(0, DL, VT);
2303   // X / undef -> undef
2304   if (N1.getOpcode() == ISD::UNDEF)
2305     return N1;
2306
2307   return SDValue();
2308 }
2309
2310 // handles ISD::SREM and ISD::UREM
2311 SDValue DAGCombiner::visitREM(SDNode *N) {
2312   unsigned Opcode = N->getOpcode();
2313   SDValue N0 = N->getOperand(0);
2314   SDValue N1 = N->getOperand(1);
2315   EVT VT = N->getValueType(0);
2316   bool isSigned = (Opcode == ISD::SREM);
2317   SDLoc DL(N);
2318
2319   // fold (rem c1, c2) -> c1%c2
2320   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2321   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2322   if (N0C && N1C)
2323     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2324       return Folded;
2325
2326   if (isSigned) {
2327     // If we know the sign bits of both operands are zero, strength reduce to a
2328     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2329     if (!VT.isVector()) {
2330       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2331         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2332     }
2333   } else {
2334     // fold (urem x, pow2) -> (and x, pow2-1)
2335     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2336         N1C->getAPIntValue().isPowerOf2()) {
2337       return DAG.getNode(ISD::AND, DL, VT, N0,
2338                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2339     }
2340     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2341     if (N1.getOpcode() == ISD::SHL) {
2342       if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2343         if (SHC->getAPIntValue().isPowerOf2()) {
2344           SDValue Add =
2345             DAG.getNode(ISD::ADD, DL, VT, N1,
2346                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2347                                  VT));
2348           AddToWorklist(Add.getNode());
2349           return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2350         }
2351       }
2352     }
2353   }
2354
2355   // If X/C can be simplified by the division-by-constant logic, lower
2356   // X%C to the equivalent of X-X/C*C.
2357   if (N1C && !N1C->isNullValue()) {
2358     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2359     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2360     AddToWorklist(Div.getNode());
2361     SDValue OptimizedDiv = combine(Div.getNode());
2362     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2363       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2364       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2365       AddToWorklist(Mul.getNode());
2366       return Sub;
2367     }
2368   }
2369
2370   // undef % X -> 0
2371   if (N0.getOpcode() == ISD::UNDEF)
2372     return DAG.getConstant(0, DL, VT);
2373   // X % undef -> undef
2374   if (N1.getOpcode() == ISD::UNDEF)
2375     return N1;
2376
2377   return SDValue();
2378 }
2379
2380 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2381   SDValue N0 = N->getOperand(0);
2382   SDValue N1 = N->getOperand(1);
2383   EVT VT = N->getValueType(0);
2384   SDLoc DL(N);
2385
2386   // fold (mulhs x, 0) -> 0
2387   if (isNullConstant(N1))
2388     return N1;
2389   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2390   if (isOneConstant(N1)) {
2391     SDLoc DL(N);
2392     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2393                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2394                                        DL,
2395                                        getShiftAmountTy(N0.getValueType())));
2396   }
2397   // fold (mulhs x, undef) -> 0
2398   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2399     return DAG.getConstant(0, SDLoc(N), VT);
2400
2401   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2402   // plus a shift.
2403   if (VT.isSimple() && !VT.isVector()) {
2404     MVT Simple = VT.getSimpleVT();
2405     unsigned SimpleSize = Simple.getSizeInBits();
2406     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2407     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2408       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2409       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2410       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2411       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2412             DAG.getConstant(SimpleSize, DL,
2413                             getShiftAmountTy(N1.getValueType())));
2414       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2415     }
2416   }
2417
2418   return SDValue();
2419 }
2420
2421 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2422   SDValue N0 = N->getOperand(0);
2423   SDValue N1 = N->getOperand(1);
2424   EVT VT = N->getValueType(0);
2425   SDLoc DL(N);
2426
2427   // fold (mulhu x, 0) -> 0
2428   if (isNullConstant(N1))
2429     return N1;
2430   // fold (mulhu x, 1) -> 0
2431   if (isOneConstant(N1))
2432     return DAG.getConstant(0, DL, N0.getValueType());
2433   // fold (mulhu x, undef) -> 0
2434   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2435     return DAG.getConstant(0, DL, VT);
2436
2437   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2438   // plus a shift.
2439   if (VT.isSimple() && !VT.isVector()) {
2440     MVT Simple = VT.getSimpleVT();
2441     unsigned SimpleSize = Simple.getSizeInBits();
2442     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2443     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2444       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2445       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2446       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2447       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2448             DAG.getConstant(SimpleSize, DL,
2449                             getShiftAmountTy(N1.getValueType())));
2450       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2451     }
2452   }
2453
2454   return SDValue();
2455 }
2456
2457 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2458 /// give the opcodes for the two computations that are being performed. Return
2459 /// true if a simplification was made.
2460 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2461                                                 unsigned HiOp) {
2462   // If the high half is not needed, just compute the low half.
2463   bool HiExists = N->hasAnyUseOfValue(1);
2464   if (!HiExists &&
2465       (!LegalOperations ||
2466        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2467     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2468     return CombineTo(N, Res, Res);
2469   }
2470
2471   // If the low half is not needed, just compute the high half.
2472   bool LoExists = N->hasAnyUseOfValue(0);
2473   if (!LoExists &&
2474       (!LegalOperations ||
2475        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2476     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2477     return CombineTo(N, Res, Res);
2478   }
2479
2480   // If both halves are used, return as it is.
2481   if (LoExists && HiExists)
2482     return SDValue();
2483
2484   // If the two computed results can be simplified separately, separate them.
2485   if (LoExists) {
2486     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2487     AddToWorklist(Lo.getNode());
2488     SDValue LoOpt = combine(Lo.getNode());
2489     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2490         (!LegalOperations ||
2491          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2492       return CombineTo(N, LoOpt, LoOpt);
2493   }
2494
2495   if (HiExists) {
2496     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2497     AddToWorklist(Hi.getNode());
2498     SDValue HiOpt = combine(Hi.getNode());
2499     if (HiOpt.getNode() && HiOpt != Hi &&
2500         (!LegalOperations ||
2501          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2502       return CombineTo(N, HiOpt, HiOpt);
2503   }
2504
2505   return SDValue();
2506 }
2507
2508 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2509   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2510     return Res;
2511
2512   EVT VT = N->getValueType(0);
2513   SDLoc DL(N);
2514
2515   // If the type is twice as wide is legal, transform the mulhu to a wider
2516   // multiply plus a shift.
2517   if (VT.isSimple() && !VT.isVector()) {
2518     MVT Simple = VT.getSimpleVT();
2519     unsigned SimpleSize = Simple.getSizeInBits();
2520     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2521     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2522       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2523       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2524       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2525       // Compute the high part as N1.
2526       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2527             DAG.getConstant(SimpleSize, DL,
2528                             getShiftAmountTy(Lo.getValueType())));
2529       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2530       // Compute the low part as N0.
2531       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2532       return CombineTo(N, Lo, Hi);
2533     }
2534   }
2535
2536   return SDValue();
2537 }
2538
2539 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2540   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2541     return Res;
2542
2543   EVT VT = N->getValueType(0);
2544   SDLoc DL(N);
2545
2546   // If the type is twice as wide is legal, transform the mulhu to a wider
2547   // multiply plus a shift.
2548   if (VT.isSimple() && !VT.isVector()) {
2549     MVT Simple = VT.getSimpleVT();
2550     unsigned SimpleSize = Simple.getSizeInBits();
2551     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2552     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2553       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2554       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2555       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2556       // Compute the high part as N1.
2557       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2558             DAG.getConstant(SimpleSize, DL,
2559                             getShiftAmountTy(Lo.getValueType())));
2560       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2561       // Compute the low part as N0.
2562       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2563       return CombineTo(N, Lo, Hi);
2564     }
2565   }
2566
2567   return SDValue();
2568 }
2569
2570 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2571   // (smulo x, 2) -> (saddo x, x)
2572   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2573     if (C2->getAPIntValue() == 2)
2574       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2575                          N->getOperand(0), N->getOperand(0));
2576
2577   return SDValue();
2578 }
2579
2580 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2581   // (umulo x, 2) -> (uaddo x, x)
2582   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2583     if (C2->getAPIntValue() == 2)
2584       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2585                          N->getOperand(0), N->getOperand(0));
2586
2587   return SDValue();
2588 }
2589
2590 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2591   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2592     return Res;
2593
2594   return SDValue();
2595 }
2596
2597 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2598   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2599     return Res;
2600
2601   return SDValue();
2602 }
2603
2604 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2605   SDValue N0 = N->getOperand(0);
2606   SDValue N1 = N->getOperand(1);
2607   EVT VT = N0.getValueType();
2608
2609   // fold vector ops
2610   if (VT.isVector())
2611     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2612       return FoldedVOp;
2613
2614   // fold (add c1, c2) -> c1+c2
2615   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2616   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2617   if (N0C && N1C)
2618     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2619
2620   // canonicalize constant to RHS
2621   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2622      !isConstantIntBuildVectorOrConstantInt(N1))
2623     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2624
2625   return SDValue();
2626 }
2627
2628 /// If this is a binary operator with two operands of the same opcode, try to
2629 /// simplify it.
2630 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2631   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2632   EVT VT = N0.getValueType();
2633   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2634
2635   // Bail early if none of these transforms apply.
2636   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2637
2638   // For each of OP in AND/OR/XOR:
2639   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2640   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2641   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2642   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2643   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2644   //
2645   // do not sink logical op inside of a vector extend, since it may combine
2646   // into a vsetcc.
2647   EVT Op0VT = N0.getOperand(0).getValueType();
2648   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2649        N0.getOpcode() == ISD::SIGN_EXTEND ||
2650        N0.getOpcode() == ISD::BSWAP ||
2651        // Avoid infinite looping with PromoteIntBinOp.
2652        (N0.getOpcode() == ISD::ANY_EXTEND &&
2653         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2654        (N0.getOpcode() == ISD::TRUNCATE &&
2655         (!TLI.isZExtFree(VT, Op0VT) ||
2656          !TLI.isTruncateFree(Op0VT, VT)) &&
2657         TLI.isTypeLegal(Op0VT))) &&
2658       !VT.isVector() &&
2659       Op0VT == N1.getOperand(0).getValueType() &&
2660       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2661     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2662                                  N0.getOperand(0).getValueType(),
2663                                  N0.getOperand(0), N1.getOperand(0));
2664     AddToWorklist(ORNode.getNode());
2665     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2666   }
2667
2668   // For each of OP in SHL/SRL/SRA/AND...
2669   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2670   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2671   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2672   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2673        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2674       N0.getOperand(1) == N1.getOperand(1)) {
2675     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2676                                  N0.getOperand(0).getValueType(),
2677                                  N0.getOperand(0), N1.getOperand(0));
2678     AddToWorklist(ORNode.getNode());
2679     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2680                        ORNode, N0.getOperand(1));
2681   }
2682
2683   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2684   // Only perform this optimization after type legalization and before
2685   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2686   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2687   // we don't want to undo this promotion.
2688   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2689   // on scalars.
2690   if ((N0.getOpcode() == ISD::BITCAST ||
2691        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2692       Level == AfterLegalizeTypes) {
2693     SDValue In0 = N0.getOperand(0);
2694     SDValue In1 = N1.getOperand(0);
2695     EVT In0Ty = In0.getValueType();
2696     EVT In1Ty = In1.getValueType();
2697     SDLoc DL(N);
2698     // If both incoming values are integers, and the original types are the
2699     // same.
2700     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2701       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2702       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2703       AddToWorklist(Op.getNode());
2704       return BC;
2705     }
2706   }
2707
2708   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2709   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2710   // If both shuffles use the same mask, and both shuffle within a single
2711   // vector, then it is worthwhile to move the swizzle after the operation.
2712   // The type-legalizer generates this pattern when loading illegal
2713   // vector types from memory. In many cases this allows additional shuffle
2714   // optimizations.
2715   // There are other cases where moving the shuffle after the xor/and/or
2716   // is profitable even if shuffles don't perform a swizzle.
2717   // If both shuffles use the same mask, and both shuffles have the same first
2718   // or second operand, then it might still be profitable to move the shuffle
2719   // after the xor/and/or operation.
2720   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2721     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2722     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2723
2724     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2725            "Inputs to shuffles are not the same type");
2726
2727     // Check that both shuffles use the same mask. The masks are known to be of
2728     // the same length because the result vector type is the same.
2729     // Check also that shuffles have only one use to avoid introducing extra
2730     // instructions.
2731     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2732         SVN0->getMask().equals(SVN1->getMask())) {
2733       SDValue ShOp = N0->getOperand(1);
2734
2735       // Don't try to fold this node if it requires introducing a
2736       // build vector of all zeros that might be illegal at this stage.
2737       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2738         if (!LegalTypes)
2739           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2740         else
2741           ShOp = SDValue();
2742       }
2743
2744       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2745       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2746       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2747       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2748         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2749                                       N0->getOperand(0), N1->getOperand(0));
2750         AddToWorklist(NewNode.getNode());
2751         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2752                                     &SVN0->getMask()[0]);
2753       }
2754
2755       // Don't try to fold this node if it requires introducing a
2756       // build vector of all zeros that might be illegal at this stage.
2757       ShOp = N0->getOperand(0);
2758       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2759         if (!LegalTypes)
2760           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2761         else
2762           ShOp = SDValue();
2763       }
2764
2765       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2766       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2767       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2768       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2769         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2770                                       N0->getOperand(1), N1->getOperand(1));
2771         AddToWorklist(NewNode.getNode());
2772         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2773                                     &SVN0->getMask()[0]);
2774       }
2775     }
2776   }
2777
2778   return SDValue();
2779 }
2780
2781 /// This contains all DAGCombine rules which reduce two values combined by
2782 /// an And operation to a single value. This makes them reusable in the context
2783 /// of visitSELECT(). Rules involving constants are not included as
2784 /// visitSELECT() already handles those cases.
2785 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2786                                   SDNode *LocReference) {
2787   EVT VT = N1.getValueType();
2788
2789   // fold (and x, undef) -> 0
2790   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2791     return DAG.getConstant(0, SDLoc(LocReference), VT);
2792   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2793   SDValue LL, LR, RL, RR, CC0, CC1;
2794   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2795     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2796     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2797
2798     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2799         LL.getValueType().isInteger()) {
2800       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2801       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2802         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2803                                      LR.getValueType(), LL, RL);
2804         AddToWorklist(ORNode.getNode());
2805         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2806       }
2807       if (isAllOnesConstant(LR)) {
2808         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2809         if (Op1 == ISD::SETEQ) {
2810           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2811                                         LR.getValueType(), LL, RL);
2812           AddToWorklist(ANDNode.getNode());
2813           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2814         }
2815         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2816         if (Op1 == ISD::SETGT) {
2817           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2818                                        LR.getValueType(), LL, RL);
2819           AddToWorklist(ORNode.getNode());
2820           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2821         }
2822       }
2823     }
2824     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2825     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2826         Op0 == Op1 && LL.getValueType().isInteger() &&
2827       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2828                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2829       SDLoc DL(N0);
2830       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2831                                     LL, DAG.getConstant(1, DL,
2832                                                         LL.getValueType()));
2833       AddToWorklist(ADDNode.getNode());
2834       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2835                           DAG.getConstant(2, DL, LL.getValueType()),
2836                           ISD::SETUGE);
2837     }
2838     // canonicalize equivalent to ll == rl
2839     if (LL == RR && LR == RL) {
2840       Op1 = ISD::getSetCCSwappedOperands(Op1);
2841       std::swap(RL, RR);
2842     }
2843     if (LL == RL && LR == RR) {
2844       bool isInteger = LL.getValueType().isInteger();
2845       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2846       if (Result != ISD::SETCC_INVALID &&
2847           (!LegalOperations ||
2848            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2849             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2850         EVT CCVT = getSetCCResultType(LL.getValueType());
2851         if (N0.getValueType() == CCVT ||
2852             (!LegalOperations && N0.getValueType() == MVT::i1))
2853           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2854                               LL, LR, Result);
2855       }
2856     }
2857   }
2858
2859   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2860       VT.getSizeInBits() <= 64) {
2861     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2862       APInt ADDC = ADDI->getAPIntValue();
2863       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2864         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2865         // immediate for an add, but it is legal if its top c2 bits are set,
2866         // transform the ADD so the immediate doesn't need to be materialized
2867         // in a register.
2868         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2869           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2870                                              SRLI->getZExtValue());
2871           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2872             ADDC |= Mask;
2873             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2874               SDLoc DL(N0);
2875               SDValue NewAdd =
2876                 DAG.getNode(ISD::ADD, DL, VT,
2877                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2878               CombineTo(N0.getNode(), NewAdd);
2879               // Return N so it doesn't get rechecked!
2880               return SDValue(LocReference, 0);
2881             }
2882           }
2883         }
2884       }
2885     }
2886   }
2887
2888   return SDValue();
2889 }
2890
2891 SDValue DAGCombiner::visitAND(SDNode *N) {
2892   SDValue N0 = N->getOperand(0);
2893   SDValue N1 = N->getOperand(1);
2894   EVT VT = N1.getValueType();
2895
2896   // fold vector ops
2897   if (VT.isVector()) {
2898     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2899       return FoldedVOp;
2900
2901     // fold (and x, 0) -> 0, vector edition
2902     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2903       // do not return N0, because undef node may exist in N0
2904       return DAG.getConstant(
2905           APInt::getNullValue(
2906               N0.getValueType().getScalarType().getSizeInBits()),
2907           SDLoc(N), N0.getValueType());
2908     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2909       // do not return N1, because undef node may exist in N1
2910       return DAG.getConstant(
2911           APInt::getNullValue(
2912               N1.getValueType().getScalarType().getSizeInBits()),
2913           SDLoc(N), N1.getValueType());
2914
2915     // fold (and x, -1) -> x, vector edition
2916     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2917       return N1;
2918     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2919       return N0;
2920   }
2921
2922   // fold (and c1, c2) -> c1&c2
2923   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2924   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2925   if (N0C && N1C && !N1C->isOpaque())
2926     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2927   // canonicalize constant to RHS
2928   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2929      !isConstantIntBuildVectorOrConstantInt(N1))
2930     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2931   // fold (and x, -1) -> x
2932   if (isAllOnesConstant(N1))
2933     return N0;
2934   // if (and x, c) is known to be zero, return 0
2935   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2936   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2937                                    APInt::getAllOnesValue(BitWidth)))
2938     return DAG.getConstant(0, SDLoc(N), VT);
2939   // reassociate and
2940   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2941     return RAND;
2942   // fold (and (or x, C), D) -> D if (C & D) == D
2943   if (N1C && N0.getOpcode() == ISD::OR)
2944     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2945       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2946         return N1;
2947   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2948   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2949     SDValue N0Op0 = N0.getOperand(0);
2950     APInt Mask = ~N1C->getAPIntValue();
2951     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2952     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2953       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2954                                  N0.getValueType(), N0Op0);
2955
2956       // Replace uses of the AND with uses of the Zero extend node.
2957       CombineTo(N, Zext);
2958
2959       // We actually want to replace all uses of the any_extend with the
2960       // zero_extend, to avoid duplicating things.  This will later cause this
2961       // AND to be folded.
2962       CombineTo(N0.getNode(), Zext);
2963       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2964     }
2965   }
2966   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2967   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2968   // already be zero by virtue of the width of the base type of the load.
2969   //
2970   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2971   // more cases.
2972   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2973        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2974       N0.getOpcode() == ISD::LOAD) {
2975     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2976                                          N0 : N0.getOperand(0) );
2977
2978     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2979     // This can be a pure constant or a vector splat, in which case we treat the
2980     // vector as a scalar and use the splat value.
2981     APInt Constant = APInt::getNullValue(1);
2982     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2983       Constant = C->getAPIntValue();
2984     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2985       APInt SplatValue, SplatUndef;
2986       unsigned SplatBitSize;
2987       bool HasAnyUndefs;
2988       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2989                                              SplatBitSize, HasAnyUndefs);
2990       if (IsSplat) {
2991         // Undef bits can contribute to a possible optimisation if set, so
2992         // set them.
2993         SplatValue |= SplatUndef;
2994
2995         // The splat value may be something like "0x00FFFFFF", which means 0 for
2996         // the first vector value and FF for the rest, repeating. We need a mask
2997         // that will apply equally to all members of the vector, so AND all the
2998         // lanes of the constant together.
2999         EVT VT = Vector->getValueType(0);
3000         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3001
3002         // If the splat value has been compressed to a bitlength lower
3003         // than the size of the vector lane, we need to re-expand it to
3004         // the lane size.
3005         if (BitWidth > SplatBitSize)
3006           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3007                SplatBitSize < BitWidth;
3008                SplatBitSize = SplatBitSize * 2)
3009             SplatValue |= SplatValue.shl(SplatBitSize);
3010
3011         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3012         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3013         if (SplatBitSize % BitWidth == 0) {
3014           Constant = APInt::getAllOnesValue(BitWidth);
3015           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3016             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3017         }
3018       }
3019     }
3020
3021     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3022     // actually legal and isn't going to get expanded, else this is a false
3023     // optimisation.
3024     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3025                                                     Load->getValueType(0),
3026                                                     Load->getMemoryVT());
3027
3028     // Resize the constant to the same size as the original memory access before
3029     // extension. If it is still the AllOnesValue then this AND is completely
3030     // unneeded.
3031     Constant =
3032       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3033
3034     bool B;
3035     switch (Load->getExtensionType()) {
3036     default: B = false; break;
3037     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3038     case ISD::ZEXTLOAD:
3039     case ISD::NON_EXTLOAD: B = true; break;
3040     }
3041
3042     if (B && Constant.isAllOnesValue()) {
3043       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3044       // preserve semantics once we get rid of the AND.
3045       SDValue NewLoad(Load, 0);
3046       if (Load->getExtensionType() == ISD::EXTLOAD) {
3047         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3048                               Load->getValueType(0), SDLoc(Load),
3049                               Load->getChain(), Load->getBasePtr(),
3050                               Load->getOffset(), Load->getMemoryVT(),
3051                               Load->getMemOperand());
3052         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3053         if (Load->getNumValues() == 3) {
3054           // PRE/POST_INC loads have 3 values.
3055           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3056                            NewLoad.getValue(2) };
3057           CombineTo(Load, To, 3, true);
3058         } else {
3059           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3060         }
3061       }
3062
3063       // Fold the AND away, taking care not to fold to the old load node if we
3064       // replaced it.
3065       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3066
3067       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3068     }
3069   }
3070
3071   // fold (and (load x), 255) -> (zextload x, i8)
3072   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3073   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3074   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3075               (N0.getOpcode() == ISD::ANY_EXTEND &&
3076                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3077     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3078     LoadSDNode *LN0 = HasAnyExt
3079       ? cast<LoadSDNode>(N0.getOperand(0))
3080       : cast<LoadSDNode>(N0);
3081     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3082         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3083       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3084       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3085         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3086         EVT LoadedVT = LN0->getMemoryVT();
3087         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3088
3089         if (ExtVT == LoadedVT &&
3090             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3091                                                     ExtVT))) {
3092
3093           SDValue NewLoad =
3094             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3095                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3096                            LN0->getMemOperand());
3097           AddToWorklist(N);
3098           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3099           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3100         }
3101
3102         // Do not change the width of a volatile load.
3103         // Do not generate loads of non-round integer types since these can
3104         // be expensive (and would be wrong if the type is not byte sized).
3105         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3106             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3107                                                     ExtVT))) {
3108           EVT PtrType = LN0->getOperand(1).getValueType();
3109
3110           unsigned Alignment = LN0->getAlignment();
3111           SDValue NewPtr = LN0->getBasePtr();
3112
3113           // For big endian targets, we need to add an offset to the pointer
3114           // to load the correct bytes.  For little endian systems, we merely
3115           // need to read fewer bytes from the same pointer.
3116           if (DAG.getDataLayout().isBigEndian()) {
3117             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3118             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3119             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3120             SDLoc DL(LN0);
3121             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3122                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3123             Alignment = MinAlign(Alignment, PtrOff);
3124           }
3125
3126           AddToWorklist(NewPtr.getNode());
3127
3128           SDValue Load =
3129             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3130                            LN0->getChain(), NewPtr,
3131                            LN0->getPointerInfo(),
3132                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3133                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3134           AddToWorklist(N);
3135           CombineTo(LN0, Load, Load.getValue(1));
3136           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3137         }
3138       }
3139     }
3140   }
3141
3142   if (SDValue Combined = visitANDLike(N0, N1, N))
3143     return Combined;
3144
3145   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3146   if (N0.getOpcode() == N1.getOpcode())
3147     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3148       return Tmp;
3149
3150   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3151   // fold (and (sra)) -> (and (srl)) when possible.
3152   if (!VT.isVector() &&
3153       SimplifyDemandedBits(SDValue(N, 0)))
3154     return SDValue(N, 0);
3155
3156   // fold (zext_inreg (extload x)) -> (zextload x)
3157   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3158     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3159     EVT MemVT = LN0->getMemoryVT();
3160     // If we zero all the possible extended bits, then we can turn this into
3161     // a zextload if we are running before legalize or the operation is legal.
3162     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3163     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3164                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3165         ((!LegalOperations && !LN0->isVolatile()) ||
3166          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3167       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3168                                        LN0->getChain(), LN0->getBasePtr(),
3169                                        MemVT, LN0->getMemOperand());
3170       AddToWorklist(N);
3171       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3172       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3173     }
3174   }
3175   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3176   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3177       N0.hasOneUse()) {
3178     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3179     EVT MemVT = LN0->getMemoryVT();
3180     // If we zero all the possible extended bits, then we can turn this into
3181     // a zextload if we are running before legalize or the operation is legal.
3182     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3183     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3184                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3185         ((!LegalOperations && !LN0->isVolatile()) ||
3186          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3187       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3188                                        LN0->getChain(), LN0->getBasePtr(),
3189                                        MemVT, LN0->getMemOperand());
3190       AddToWorklist(N);
3191       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3192       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3193     }
3194   }
3195   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3196   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3197     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3198                                        N0.getOperand(1), false);
3199     if (BSwap.getNode())
3200       return BSwap;
3201   }
3202
3203   return SDValue();
3204 }
3205
3206 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3207 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3208                                         bool DemandHighBits) {
3209   if (!LegalOperations)
3210     return SDValue();
3211
3212   EVT VT = N->getValueType(0);
3213   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3214     return SDValue();
3215   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3216     return SDValue();
3217
3218   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3219   bool LookPassAnd0 = false;
3220   bool LookPassAnd1 = false;
3221   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3222       std::swap(N0, N1);
3223   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3224       std::swap(N0, N1);
3225   if (N0.getOpcode() == ISD::AND) {
3226     if (!N0.getNode()->hasOneUse())
3227       return SDValue();
3228     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3229     if (!N01C || N01C->getZExtValue() != 0xFF00)
3230       return SDValue();
3231     N0 = N0.getOperand(0);
3232     LookPassAnd0 = true;
3233   }
3234
3235   if (N1.getOpcode() == ISD::AND) {
3236     if (!N1.getNode()->hasOneUse())
3237       return SDValue();
3238     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3239     if (!N11C || N11C->getZExtValue() != 0xFF)
3240       return SDValue();
3241     N1 = N1.getOperand(0);
3242     LookPassAnd1 = true;
3243   }
3244
3245   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3246     std::swap(N0, N1);
3247   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3248     return SDValue();
3249   if (!N0.getNode()->hasOneUse() ||
3250       !N1.getNode()->hasOneUse())
3251     return SDValue();
3252
3253   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3254   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3255   if (!N01C || !N11C)
3256     return SDValue();
3257   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3258     return SDValue();
3259
3260   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3261   SDValue N00 = N0->getOperand(0);
3262   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3263     if (!N00.getNode()->hasOneUse())
3264       return SDValue();
3265     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3266     if (!N001C || N001C->getZExtValue() != 0xFF)
3267       return SDValue();
3268     N00 = N00.getOperand(0);
3269     LookPassAnd0 = true;
3270   }
3271
3272   SDValue N10 = N1->getOperand(0);
3273   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3274     if (!N10.getNode()->hasOneUse())
3275       return SDValue();
3276     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3277     if (!N101C || N101C->getZExtValue() != 0xFF00)
3278       return SDValue();
3279     N10 = N10.getOperand(0);
3280     LookPassAnd1 = true;
3281   }
3282
3283   if (N00 != N10)
3284     return SDValue();
3285
3286   // Make sure everything beyond the low halfword gets set to zero since the SRL
3287   // 16 will clear the top bits.
3288   unsigned OpSizeInBits = VT.getSizeInBits();
3289   if (DemandHighBits && OpSizeInBits > 16) {
3290     // If the left-shift isn't masked out then the only way this is a bswap is
3291     // if all bits beyond the low 8 are 0. In that case the entire pattern
3292     // reduces to a left shift anyway: leave it for other parts of the combiner.
3293     if (!LookPassAnd0)
3294       return SDValue();
3295
3296     // However, if the right shift isn't masked out then it might be because
3297     // it's not needed. See if we can spot that too.
3298     if (!LookPassAnd1 &&
3299         !DAG.MaskedValueIsZero(
3300             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3301       return SDValue();
3302   }
3303
3304   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3305   if (OpSizeInBits > 16) {
3306     SDLoc DL(N);
3307     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3308                       DAG.getConstant(OpSizeInBits - 16, DL,
3309                                       getShiftAmountTy(VT)));
3310   }
3311   return Res;
3312 }
3313
3314 /// Return true if the specified node is an element that makes up a 32-bit
3315 /// packed halfword byteswap.
3316 /// ((x & 0x000000ff) << 8) |
3317 /// ((x & 0x0000ff00) >> 8) |
3318 /// ((x & 0x00ff0000) << 8) |
3319 /// ((x & 0xff000000) >> 8)
3320 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3321   if (!N.getNode()->hasOneUse())
3322     return false;
3323
3324   unsigned Opc = N.getOpcode();
3325   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3326     return false;
3327
3328   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3329   if (!N1C)
3330     return false;
3331
3332   unsigned Num;
3333   switch (N1C->getZExtValue()) {
3334   default:
3335     return false;
3336   case 0xFF:       Num = 0; break;
3337   case 0xFF00:     Num = 1; break;
3338   case 0xFF0000:   Num = 2; break;
3339   case 0xFF000000: Num = 3; break;
3340   }
3341
3342   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3343   SDValue N0 = N.getOperand(0);
3344   if (Opc == ISD::AND) {
3345     if (Num == 0 || Num == 2) {
3346       // (x >> 8) & 0xff
3347       // (x >> 8) & 0xff0000
3348       if (N0.getOpcode() != ISD::SRL)
3349         return false;
3350       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3351       if (!C || C->getZExtValue() != 8)
3352         return false;
3353     } else {
3354       // (x << 8) & 0xff00
3355       // (x << 8) & 0xff000000
3356       if (N0.getOpcode() != ISD::SHL)
3357         return false;
3358       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3359       if (!C || C->getZExtValue() != 8)
3360         return false;
3361     }
3362   } else if (Opc == ISD::SHL) {
3363     // (x & 0xff) << 8
3364     // (x & 0xff0000) << 8
3365     if (Num != 0 && Num != 2)
3366       return false;
3367     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3368     if (!C || C->getZExtValue() != 8)
3369       return false;
3370   } else { // Opc == ISD::SRL
3371     // (x & 0xff00) >> 8
3372     // (x & 0xff000000) >> 8
3373     if (Num != 1 && Num != 3)
3374       return false;
3375     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3376     if (!C || C->getZExtValue() != 8)
3377       return false;
3378   }
3379
3380   if (Parts[Num])
3381     return false;
3382
3383   Parts[Num] = N0.getOperand(0).getNode();
3384   return true;
3385 }
3386
3387 /// Match a 32-bit packed halfword bswap. That is
3388 /// ((x & 0x000000ff) << 8) |
3389 /// ((x & 0x0000ff00) >> 8) |
3390 /// ((x & 0x00ff0000) << 8) |
3391 /// ((x & 0xff000000) >> 8)
3392 /// => (rotl (bswap x), 16)
3393 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3394   if (!LegalOperations)
3395     return SDValue();
3396
3397   EVT VT = N->getValueType(0);
3398   if (VT != MVT::i32)
3399     return SDValue();
3400   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3401     return SDValue();
3402
3403   // Look for either
3404   // (or (or (and), (and)), (or (and), (and)))
3405   // (or (or (or (and), (and)), (and)), (and))
3406   if (N0.getOpcode() != ISD::OR)
3407     return SDValue();
3408   SDValue N00 = N0.getOperand(0);
3409   SDValue N01 = N0.getOperand(1);
3410   SDNode *Parts[4] = {};
3411
3412   if (N1.getOpcode() == ISD::OR &&
3413       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3414     // (or (or (and), (and)), (or (and), (and)))
3415     SDValue N000 = N00.getOperand(0);
3416     if (!isBSwapHWordElement(N000, Parts))
3417       return SDValue();
3418
3419     SDValue N001 = N00.getOperand(1);
3420     if (!isBSwapHWordElement(N001, Parts))
3421       return SDValue();
3422     SDValue N010 = N01.getOperand(0);
3423     if (!isBSwapHWordElement(N010, Parts))
3424       return SDValue();
3425     SDValue N011 = N01.getOperand(1);
3426     if (!isBSwapHWordElement(N011, Parts))
3427       return SDValue();
3428   } else {
3429     // (or (or (or (and), (and)), (and)), (and))
3430     if (!isBSwapHWordElement(N1, Parts))
3431       return SDValue();
3432     if (!isBSwapHWordElement(N01, Parts))
3433       return SDValue();
3434     if (N00.getOpcode() != ISD::OR)
3435       return SDValue();
3436     SDValue N000 = N00.getOperand(0);
3437     if (!isBSwapHWordElement(N000, Parts))
3438       return SDValue();
3439     SDValue N001 = N00.getOperand(1);
3440     if (!isBSwapHWordElement(N001, Parts))
3441       return SDValue();
3442   }
3443
3444   // Make sure the parts are all coming from the same node.
3445   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3446     return SDValue();
3447
3448   SDLoc DL(N);
3449   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3450                               SDValue(Parts[0], 0));
3451
3452   // Result of the bswap should be rotated by 16. If it's not legal, then
3453   // do  (x << 16) | (x >> 16).
3454   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3455   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3456     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3457   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3458     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3459   return DAG.getNode(ISD::OR, DL, VT,
3460                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3461                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3462 }
3463
3464 /// This contains all DAGCombine rules which reduce two values combined by
3465 /// an Or operation to a single value \see visitANDLike().
3466 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3467   EVT VT = N1.getValueType();
3468   // fold (or x, undef) -> -1
3469   if (!LegalOperations &&
3470       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3471     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3472     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3473                            SDLoc(LocReference), VT);
3474   }
3475   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3476   SDValue LL, LR, RL, RR, CC0, CC1;
3477   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3478     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3479     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3480
3481     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3482       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3483       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3484       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3485         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3486                                      LR.getValueType(), LL, RL);
3487         AddToWorklist(ORNode.getNode());
3488         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3489       }
3490       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3491       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3492       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3493         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3494                                       LR.getValueType(), LL, RL);
3495         AddToWorklist(ANDNode.getNode());
3496         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3497       }
3498     }
3499     // canonicalize equivalent to ll == rl
3500     if (LL == RR && LR == RL) {
3501       Op1 = ISD::getSetCCSwappedOperands(Op1);
3502       std::swap(RL, RR);
3503     }
3504     if (LL == RL && LR == RR) {
3505       bool isInteger = LL.getValueType().isInteger();
3506       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3507       if (Result != ISD::SETCC_INVALID &&
3508           (!LegalOperations ||
3509            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3510             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3511         EVT CCVT = getSetCCResultType(LL.getValueType());
3512         if (N0.getValueType() == CCVT ||
3513             (!LegalOperations && N0.getValueType() == MVT::i1))
3514           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3515                               LL, LR, Result);
3516       }
3517     }
3518   }
3519
3520   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3521   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3522       // Don't increase # computations.
3523       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3524     // We can only do this xform if we know that bits from X that are set in C2
3525     // but not in C1 are already zero.  Likewise for Y.
3526     if (const ConstantSDNode *N0O1C =
3527         getAsNonOpaqueConstant(N0.getOperand(1))) {
3528       if (const ConstantSDNode *N1O1C =
3529           getAsNonOpaqueConstant(N1.getOperand(1))) {
3530         // We can only do this xform if we know that bits from X that are set in
3531         // C2 but not in C1 are already zero.  Likewise for Y.
3532         const APInt &LHSMask = N0O1C->getAPIntValue();
3533         const APInt &RHSMask = N1O1C->getAPIntValue();
3534
3535         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3536             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3537           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3538                                   N0.getOperand(0), N1.getOperand(0));
3539           SDLoc DL(LocReference);
3540           return DAG.getNode(ISD::AND, DL, VT, X,
3541                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3542         }
3543       }
3544     }
3545   }
3546
3547   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3548   if (N0.getOpcode() == ISD::AND &&
3549       N1.getOpcode() == ISD::AND &&
3550       N0.getOperand(0) == N1.getOperand(0) &&
3551       // Don't increase # computations.
3552       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3553     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3554                             N0.getOperand(1), N1.getOperand(1));
3555     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3556   }
3557
3558   return SDValue();
3559 }
3560
3561 SDValue DAGCombiner::visitOR(SDNode *N) {
3562   SDValue N0 = N->getOperand(0);
3563   SDValue N1 = N->getOperand(1);
3564   EVT VT = N1.getValueType();
3565
3566   // fold vector ops
3567   if (VT.isVector()) {
3568     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3569       return FoldedVOp;
3570
3571     // fold (or x, 0) -> x, vector edition
3572     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3573       return N1;
3574     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3575       return N0;
3576
3577     // fold (or x, -1) -> -1, vector edition
3578     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3579       // do not return N0, because undef node may exist in N0
3580       return DAG.getConstant(
3581           APInt::getAllOnesValue(
3582               N0.getValueType().getScalarType().getSizeInBits()),
3583           SDLoc(N), N0.getValueType());
3584     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3585       // do not return N1, because undef node may exist in N1
3586       return DAG.getConstant(
3587           APInt::getAllOnesValue(
3588               N1.getValueType().getScalarType().getSizeInBits()),
3589           SDLoc(N), N1.getValueType());
3590
3591     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3592     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3593     // Do this only if the resulting shuffle is legal.
3594     if (isa<ShuffleVectorSDNode>(N0) &&
3595         isa<ShuffleVectorSDNode>(N1) &&
3596         // Avoid folding a node with illegal type.
3597         TLI.isTypeLegal(VT) &&
3598         N0->getOperand(1) == N1->getOperand(1) &&
3599         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3600       bool CanFold = true;
3601       unsigned NumElts = VT.getVectorNumElements();
3602       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3603       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3604       // We construct two shuffle masks:
3605       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3606       // and N1 as the second operand.
3607       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3608       // and N0 as the second operand.
3609       // We do this because OR is commutable and therefore there might be
3610       // two ways to fold this node into a shuffle.
3611       SmallVector<int,4> Mask1;
3612       SmallVector<int,4> Mask2;
3613
3614       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3615         int M0 = SV0->getMaskElt(i);
3616         int M1 = SV1->getMaskElt(i);
3617
3618         // Both shuffle indexes are undef. Propagate Undef.
3619         if (M0 < 0 && M1 < 0) {
3620           Mask1.push_back(M0);
3621           Mask2.push_back(M0);
3622           continue;
3623         }
3624
3625         if (M0 < 0 || M1 < 0 ||
3626             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3627             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3628           CanFold = false;
3629           break;
3630         }
3631
3632         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3633         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3634       }
3635
3636       if (CanFold) {
3637         // Fold this sequence only if the resulting shuffle is 'legal'.
3638         if (TLI.isShuffleMaskLegal(Mask1, VT))
3639           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3640                                       N1->getOperand(0), &Mask1[0]);
3641         if (TLI.isShuffleMaskLegal(Mask2, VT))
3642           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3643                                       N0->getOperand(0), &Mask2[0]);
3644       }
3645     }
3646   }
3647
3648   // fold (or c1, c2) -> c1|c2
3649   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3650   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3651   if (N0C && N1C && !N1C->isOpaque())
3652     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3653   // canonicalize constant to RHS
3654   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3655      !isConstantIntBuildVectorOrConstantInt(N1))
3656     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3657   // fold (or x, 0) -> x
3658   if (isNullConstant(N1))
3659     return N0;
3660   // fold (or x, -1) -> -1
3661   if (isAllOnesConstant(N1))
3662     return N1;
3663   // fold (or x, c) -> c iff (x & ~c) == 0
3664   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3665     return N1;
3666
3667   if (SDValue Combined = visitORLike(N0, N1, N))
3668     return Combined;
3669
3670   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3671   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3672     return BSwap;
3673   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3674     return BSwap;
3675
3676   // reassociate or
3677   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3678     return ROR;
3679   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3680   // iff (c1 & c2) == 0.
3681   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3682              isa<ConstantSDNode>(N0.getOperand(1))) {
3683     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3684     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3685       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3686                                                    N1C, C1))
3687         return DAG.getNode(
3688             ISD::AND, SDLoc(N), VT,
3689             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3690       return SDValue();
3691     }
3692   }
3693   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3694   if (N0.getOpcode() == N1.getOpcode())
3695     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3696       return Tmp;
3697
3698   // See if this is some rotate idiom.
3699   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3700     return SDValue(Rot, 0);
3701
3702   // Simplify the operands using demanded-bits information.
3703   if (!VT.isVector() &&
3704       SimplifyDemandedBits(SDValue(N, 0)))
3705     return SDValue(N, 0);
3706
3707   return SDValue();
3708 }
3709
3710 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3711 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3712   if (Op.getOpcode() == ISD::AND) {
3713     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3714       Mask = Op.getOperand(1);
3715       Op = Op.getOperand(0);
3716     } else {
3717       return false;
3718     }
3719   }
3720
3721   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3722     Shift = Op;
3723     return true;
3724   }
3725
3726   return false;
3727 }
3728
3729 // Return true if we can prove that, whenever Neg and Pos are both in the
3730 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3731 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3732 //
3733 //     (or (shift1 X, Neg), (shift2 X, Pos))
3734 //
3735 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3736 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3737 // to consider shift amounts with defined behavior.
3738 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3739   // If OpSize is a power of 2 then:
3740   //
3741   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3742   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3743   //
3744   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3745   // for the stronger condition:
3746   //
3747   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3748   //
3749   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3750   // we can just replace Neg with Neg' for the rest of the function.
3751   //
3752   // In other cases we check for the even stronger condition:
3753   //
3754   //     Neg == OpSize - Pos                                    [B]
3755   //
3756   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3757   // behavior if Pos == 0 (and consequently Neg == OpSize).
3758   //
3759   // We could actually use [A] whenever OpSize is a power of 2, but the
3760   // only extra cases that it would match are those uninteresting ones
3761   // where Neg and Pos are never in range at the same time.  E.g. for
3762   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3763   // as well as (sub 32, Pos), but:
3764   //
3765   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3766   //
3767   // always invokes undefined behavior for 32-bit X.
3768   //
3769   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3770   unsigned MaskLoBits = 0;
3771   if (Neg.getOpcode() == ISD::AND &&
3772       isPowerOf2_64(OpSize) &&
3773       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3774       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3775     Neg = Neg.getOperand(0);
3776     MaskLoBits = Log2_64(OpSize);
3777   }
3778
3779   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3780   if (Neg.getOpcode() != ISD::SUB)
3781     return 0;
3782   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3783   if (!NegC)
3784     return 0;
3785   SDValue NegOp1 = Neg.getOperand(1);
3786
3787   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3788   // Pos'.  The truncation is redundant for the purpose of the equality.
3789   if (MaskLoBits &&
3790       Pos.getOpcode() == ISD::AND &&
3791       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3792       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3793     Pos = Pos.getOperand(0);
3794
3795   // The condition we need is now:
3796   //
3797   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3798   //
3799   // If NegOp1 == Pos then we need:
3800   //
3801   //              OpSize & Mask == NegC & Mask
3802   //
3803   // (because "x & Mask" is a truncation and distributes through subtraction).
3804   APInt Width;
3805   if (Pos == NegOp1)
3806     Width = NegC->getAPIntValue();
3807   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3808   // Then the condition we want to prove becomes:
3809   //
3810   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3811   //
3812   // which, again because "x & Mask" is a truncation, becomes:
3813   //
3814   //                NegC & Mask == (OpSize - PosC) & Mask
3815   //              OpSize & Mask == (NegC + PosC) & Mask
3816   else if (Pos.getOpcode() == ISD::ADD &&
3817            Pos.getOperand(0) == NegOp1 &&
3818            Pos.getOperand(1).getOpcode() == ISD::Constant)
3819     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3820              NegC->getAPIntValue());
3821   else
3822     return false;
3823
3824   // Now we just need to check that OpSize & Mask == Width & Mask.
3825   if (MaskLoBits)
3826     // Opsize & Mask is 0 since Mask is Opsize - 1.
3827     return Width.getLoBits(MaskLoBits) == 0;
3828   return Width == OpSize;
3829 }
3830
3831 // A subroutine of MatchRotate used once we have found an OR of two opposite
3832 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3833 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3834 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3835 // Neg with outer conversions stripped away.
3836 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3837                                        SDValue Neg, SDValue InnerPos,
3838                                        SDValue InnerNeg, unsigned PosOpcode,
3839                                        unsigned NegOpcode, SDLoc DL) {
3840   // fold (or (shl x, (*ext y)),
3841   //          (srl x, (*ext (sub 32, y)))) ->
3842   //   (rotl x, y) or (rotr x, (sub 32, y))
3843   //
3844   // fold (or (shl x, (*ext (sub 32, y))),
3845   //          (srl x, (*ext y))) ->
3846   //   (rotr x, y) or (rotl x, (sub 32, y))
3847   EVT VT = Shifted.getValueType();
3848   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3849     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3850     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3851                        HasPos ? Pos : Neg).getNode();
3852   }
3853
3854   return nullptr;
3855 }
3856
3857 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3858 // idioms for rotate, and if the target supports rotation instructions, generate
3859 // a rot[lr].
3860 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3861   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3862   EVT VT = LHS.getValueType();
3863   if (!TLI.isTypeLegal(VT)) return nullptr;
3864
3865   // The target must have at least one rotate flavor.
3866   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3867   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3868   if (!HasROTL && !HasROTR) return nullptr;
3869
3870   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3871   SDValue LHSShift;   // The shift.
3872   SDValue LHSMask;    // AND value if any.
3873   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3874     return nullptr; // Not part of a rotate.
3875
3876   SDValue RHSShift;   // The shift.
3877   SDValue RHSMask;    // AND value if any.
3878   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3879     return nullptr; // Not part of a rotate.
3880
3881   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3882     return nullptr;   // Not shifting the same value.
3883
3884   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3885     return nullptr;   // Shifts must disagree.
3886
3887   // Canonicalize shl to left side in a shl/srl pair.
3888   if (RHSShift.getOpcode() == ISD::SHL) {
3889     std::swap(LHS, RHS);
3890     std::swap(LHSShift, RHSShift);
3891     std::swap(LHSMask , RHSMask );
3892   }
3893
3894   unsigned OpSizeInBits = VT.getSizeInBits();
3895   SDValue LHSShiftArg = LHSShift.getOperand(0);
3896   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3897   SDValue RHSShiftArg = RHSShift.getOperand(0);
3898   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3899
3900   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3901   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3902   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3903       RHSShiftAmt.getOpcode() == ISD::Constant) {
3904     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3905     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3906     if ((LShVal + RShVal) != OpSizeInBits)
3907       return nullptr;
3908
3909     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3910                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3911
3912     // If there is an AND of either shifted operand, apply it to the result.
3913     if (LHSMask.getNode() || RHSMask.getNode()) {
3914       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3915
3916       if (LHSMask.getNode()) {
3917         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3918         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3919       }
3920       if (RHSMask.getNode()) {
3921         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3922         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3923       }
3924
3925       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3926     }
3927
3928     return Rot.getNode();
3929   }
3930
3931   // If there is a mask here, and we have a variable shift, we can't be sure
3932   // that we're masking out the right stuff.
3933   if (LHSMask.getNode() || RHSMask.getNode())
3934     return nullptr;
3935
3936   // If the shift amount is sign/zext/any-extended just peel it off.
3937   SDValue LExtOp0 = LHSShiftAmt;
3938   SDValue RExtOp0 = RHSShiftAmt;
3939   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3940        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3941        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3942        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3943       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3944        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3945        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3946        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3947     LExtOp0 = LHSShiftAmt.getOperand(0);
3948     RExtOp0 = RHSShiftAmt.getOperand(0);
3949   }
3950
3951   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3952                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3953   if (TryL)
3954     return TryL;
3955
3956   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3957                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3958   if (TryR)
3959     return TryR;
3960
3961   return nullptr;
3962 }
3963
3964 SDValue DAGCombiner::visitXOR(SDNode *N) {
3965   SDValue N0 = N->getOperand(0);
3966   SDValue N1 = N->getOperand(1);
3967   EVT VT = N0.getValueType();
3968
3969   // fold vector ops
3970   if (VT.isVector()) {
3971     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3972       return FoldedVOp;
3973
3974     // fold (xor x, 0) -> x, vector edition
3975     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3976       return N1;
3977     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3978       return N0;
3979   }
3980
3981   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3982   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3983     return DAG.getConstant(0, SDLoc(N), VT);
3984   // fold (xor x, undef) -> undef
3985   if (N0.getOpcode() == ISD::UNDEF)
3986     return N0;
3987   if (N1.getOpcode() == ISD::UNDEF)
3988     return N1;
3989   // fold (xor c1, c2) -> c1^c2
3990   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3991   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3992   if (N0C && N1C)
3993     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3994   // canonicalize constant to RHS
3995   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3996      !isConstantIntBuildVectorOrConstantInt(N1))
3997     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3998   // fold (xor x, 0) -> x
3999   if (isNullConstant(N1))
4000     return N0;
4001   // reassociate xor
4002   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4003     return RXOR;
4004
4005   // fold !(x cc y) -> (x !cc y)
4006   SDValue LHS, RHS, CC;
4007   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4008     bool isInt = LHS.getValueType().isInteger();
4009     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4010                                                isInt);
4011
4012     if (!LegalOperations ||
4013         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4014       switch (N0.getOpcode()) {
4015       default:
4016         llvm_unreachable("Unhandled SetCC Equivalent!");
4017       case ISD::SETCC:
4018         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4019       case ISD::SELECT_CC:
4020         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4021                                N0.getOperand(3), NotCC);
4022       }
4023     }
4024   }
4025
4026   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4027   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4028       N0.getNode()->hasOneUse() &&
4029       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4030     SDValue V = N0.getOperand(0);
4031     SDLoc DL(N0);
4032     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4033                     DAG.getConstant(1, DL, V.getValueType()));
4034     AddToWorklist(V.getNode());
4035     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4036   }
4037
4038   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4039   if (isOneConstant(N1) && VT == MVT::i1 &&
4040       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4041     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4042     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4043       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4044       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4045       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4046       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4047       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4048     }
4049   }
4050   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4051   if (isAllOnesConstant(N1) &&
4052       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4053     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4054     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4055       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4056       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4057       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4058       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4059       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4060     }
4061   }
4062   // fold (xor (and x, y), y) -> (and (not x), y)
4063   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4064       N0->getOperand(1) == N1) {
4065     SDValue X = N0->getOperand(0);
4066     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4067     AddToWorklist(NotX.getNode());
4068     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4069   }
4070   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4071   if (N1C && N0.getOpcode() == ISD::XOR) {
4072     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4073       SDLoc DL(N);
4074       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4075                          DAG.getConstant(N1C->getAPIntValue() ^
4076                                          N00C->getAPIntValue(), DL, VT));
4077     }
4078     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4079       SDLoc DL(N);
4080       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4081                          DAG.getConstant(N1C->getAPIntValue() ^
4082                                          N01C->getAPIntValue(), DL, VT));
4083     }
4084   }
4085   // fold (xor x, x) -> 0
4086   if (N0 == N1)
4087     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4088
4089   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4090   // Here is a concrete example of this equivalence:
4091   // i16   x ==  14
4092   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4093   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4094   //
4095   // =>
4096   //
4097   // i16     ~1      == 0b1111111111111110
4098   // i16 rol(~1, 14) == 0b1011111111111111
4099   //
4100   // Some additional tips to help conceptualize this transform:
4101   // - Try to see the operation as placing a single zero in a value of all ones.
4102   // - There exists no value for x which would allow the result to contain zero.
4103   // - Values of x larger than the bitwidth are undefined and do not require a
4104   //   consistent result.
4105   // - Pushing the zero left requires shifting one bits in from the right.
4106   // A rotate left of ~1 is a nice way of achieving the desired result.
4107   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4108       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4109     SDLoc DL(N);
4110     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4111                        N0.getOperand(1));
4112   }
4113
4114   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4115   if (N0.getOpcode() == N1.getOpcode())
4116     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4117       return Tmp;
4118
4119   // Simplify the expression using non-local knowledge.
4120   if (!VT.isVector() &&
4121       SimplifyDemandedBits(SDValue(N, 0)))
4122     return SDValue(N, 0);
4123
4124   return SDValue();
4125 }
4126
4127 /// Handle transforms common to the three shifts, when the shift amount is a
4128 /// constant.
4129 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4130   SDNode *LHS = N->getOperand(0).getNode();
4131   if (!LHS->hasOneUse()) return SDValue();
4132
4133   // We want to pull some binops through shifts, so that we have (and (shift))
4134   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4135   // thing happens with address calculations, so it's important to canonicalize
4136   // it.
4137   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4138
4139   switch (LHS->getOpcode()) {
4140   default: return SDValue();
4141   case ISD::OR:
4142   case ISD::XOR:
4143     HighBitSet = false; // We can only transform sra if the high bit is clear.
4144     break;
4145   case ISD::AND:
4146     HighBitSet = true;  // We can only transform sra if the high bit is set.
4147     break;
4148   case ISD::ADD:
4149     if (N->getOpcode() != ISD::SHL)
4150       return SDValue(); // only shl(add) not sr[al](add).
4151     HighBitSet = false; // We can only transform sra if the high bit is clear.
4152     break;
4153   }
4154
4155   // We require the RHS of the binop to be a constant and not opaque as well.
4156   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4157   if (!BinOpCst) return SDValue();
4158
4159   // FIXME: disable this unless the input to the binop is a shift by a constant.
4160   // If it is not a shift, it pessimizes some common cases like:
4161   //
4162   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4163   //    int bar(int *X, int i) { return X[i & 255]; }
4164   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4165   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4166        BinOpLHSVal->getOpcode() != ISD::SRA &&
4167        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4168       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4169     return SDValue();
4170
4171   EVT VT = N->getValueType(0);
4172
4173   // If this is a signed shift right, and the high bit is modified by the
4174   // logical operation, do not perform the transformation. The highBitSet
4175   // boolean indicates the value of the high bit of the constant which would
4176   // cause it to be modified for this operation.
4177   if (N->getOpcode() == ISD::SRA) {
4178     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4179     if (BinOpRHSSignSet != HighBitSet)
4180       return SDValue();
4181   }
4182
4183   if (!TLI.isDesirableToCommuteWithShift(LHS))
4184     return SDValue();
4185
4186   // Fold the constants, shifting the binop RHS by the shift amount.
4187   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4188                                N->getValueType(0),
4189                                LHS->getOperand(1), N->getOperand(1));
4190   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4191
4192   // Create the new shift.
4193   SDValue NewShift = DAG.getNode(N->getOpcode(),
4194                                  SDLoc(LHS->getOperand(0)),
4195                                  VT, LHS->getOperand(0), N->getOperand(1));
4196
4197   // Create the new binop.
4198   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4199 }
4200
4201 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4202   assert(N->getOpcode() == ISD::TRUNCATE);
4203   assert(N->getOperand(0).getOpcode() == ISD::AND);
4204
4205   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4206   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4207     SDValue N01 = N->getOperand(0).getOperand(1);
4208
4209     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4210       if (!N01C->isOpaque()) {
4211         EVT TruncVT = N->getValueType(0);
4212         SDValue N00 = N->getOperand(0).getOperand(0);
4213         APInt TruncC = N01C->getAPIntValue();
4214         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4215         SDLoc DL(N);
4216
4217         return DAG.getNode(ISD::AND, DL, TruncVT,
4218                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4219                            DAG.getConstant(TruncC, DL, TruncVT));
4220       }
4221     }
4222   }
4223
4224   return SDValue();
4225 }
4226
4227 SDValue DAGCombiner::visitRotate(SDNode *N) {
4228   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4229   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4230       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4231     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4232     if (NewOp1.getNode())
4233       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4234                          N->getOperand(0), NewOp1);
4235   }
4236   return SDValue();
4237 }
4238
4239 SDValue DAGCombiner::visitSHL(SDNode *N) {
4240   SDValue N0 = N->getOperand(0);
4241   SDValue N1 = N->getOperand(1);
4242   EVT VT = N0.getValueType();
4243   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4244
4245   // fold vector ops
4246   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4247   if (VT.isVector()) {
4248     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4249       return FoldedVOp;
4250
4251     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4252     // If setcc produces all-one true value then:
4253     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4254     if (N1CV && N1CV->isConstant()) {
4255       if (N0.getOpcode() == ISD::AND) {
4256         SDValue N00 = N0->getOperand(0);
4257         SDValue N01 = N0->getOperand(1);
4258         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4259
4260         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4261             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4262                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4263           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4264                                                      N01CV, N1CV))
4265             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4266         }
4267       } else {
4268         N1C = isConstOrConstSplat(N1);
4269       }
4270     }
4271   }
4272
4273   // fold (shl c1, c2) -> c1<<c2
4274   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4275   if (N0C && N1C && !N1C->isOpaque())
4276     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4277   // fold (shl 0, x) -> 0
4278   if (isNullConstant(N0))
4279     return N0;
4280   // fold (shl x, c >= size(x)) -> undef
4281   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4282     return DAG.getUNDEF(VT);
4283   // fold (shl x, 0) -> x
4284   if (N1C && N1C->isNullValue())
4285     return N0;
4286   // fold (shl undef, x) -> 0
4287   if (N0.getOpcode() == ISD::UNDEF)
4288     return DAG.getConstant(0, SDLoc(N), VT);
4289   // if (shl x, c) is known to be zero, return 0
4290   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4291                             APInt::getAllOnesValue(OpSizeInBits)))
4292     return DAG.getConstant(0, SDLoc(N), VT);
4293   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4294   if (N1.getOpcode() == ISD::TRUNCATE &&
4295       N1.getOperand(0).getOpcode() == ISD::AND) {
4296     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4297     if (NewOp1.getNode())
4298       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4299   }
4300
4301   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4302     return SDValue(N, 0);
4303
4304   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4305   if (N1C && N0.getOpcode() == ISD::SHL) {
4306     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4307       uint64_t c1 = N0C1->getZExtValue();
4308       uint64_t c2 = N1C->getZExtValue();
4309       SDLoc DL(N);
4310       if (c1 + c2 >= OpSizeInBits)
4311         return DAG.getConstant(0, DL, VT);
4312       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4313                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4314     }
4315   }
4316
4317   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4318   // For this to be valid, the second form must not preserve any of the bits
4319   // that are shifted out by the inner shift in the first form.  This means
4320   // the outer shift size must be >= the number of bits added by the ext.
4321   // As a corollary, we don't care what kind of ext it is.
4322   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4323               N0.getOpcode() == ISD::ANY_EXTEND ||
4324               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4325       N0.getOperand(0).getOpcode() == ISD::SHL) {
4326     SDValue N0Op0 = N0.getOperand(0);
4327     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4328       uint64_t c1 = N0Op0C1->getZExtValue();
4329       uint64_t c2 = N1C->getZExtValue();
4330       EVT InnerShiftVT = N0Op0.getValueType();
4331       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4332       if (c2 >= OpSizeInBits - InnerShiftSize) {
4333         SDLoc DL(N0);
4334         if (c1 + c2 >= OpSizeInBits)
4335           return DAG.getConstant(0, DL, VT);
4336         return DAG.getNode(ISD::SHL, DL, VT,
4337                            DAG.getNode(N0.getOpcode(), DL, VT,
4338                                        N0Op0->getOperand(0)),
4339                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4340       }
4341     }
4342   }
4343
4344   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4345   // Only fold this if the inner zext has no other uses to avoid increasing
4346   // the total number of instructions.
4347   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4348       N0.getOperand(0).getOpcode() == ISD::SRL) {
4349     SDValue N0Op0 = N0.getOperand(0);
4350     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4351       uint64_t c1 = N0Op0C1->getZExtValue();
4352       if (c1 < VT.getScalarSizeInBits()) {
4353         uint64_t c2 = N1C->getZExtValue();
4354         if (c1 == c2) {
4355           SDValue NewOp0 = N0.getOperand(0);
4356           EVT CountVT = NewOp0.getOperand(1).getValueType();
4357           SDLoc DL(N);
4358           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4359                                        NewOp0,
4360                                        DAG.getConstant(c2, DL, CountVT));
4361           AddToWorklist(NewSHL.getNode());
4362           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4363         }
4364       }
4365     }
4366   }
4367
4368   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4369   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4370   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4371       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4372     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4373       uint64_t C1 = N0C1->getZExtValue();
4374       uint64_t C2 = N1C->getZExtValue();
4375       SDLoc DL(N);
4376       if (C1 <= C2)
4377         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4378                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4379       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4380                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4381     }
4382   }
4383
4384   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4385   //                               (and (srl x, (sub c1, c2), MASK)
4386   // Only fold this if the inner shift has no other uses -- if it does, folding
4387   // this will increase the total number of instructions.
4388   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4389     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4390       uint64_t c1 = N0C1->getZExtValue();
4391       if (c1 < OpSizeInBits) {
4392         uint64_t c2 = N1C->getZExtValue();
4393         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4394         SDValue Shift;
4395         if (c2 > c1) {
4396           Mask = Mask.shl(c2 - c1);
4397           SDLoc DL(N);
4398           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4399                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4400         } else {
4401           Mask = Mask.lshr(c1 - c2);
4402           SDLoc DL(N);
4403           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4404                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4405         }
4406         SDLoc DL(N0);
4407         return DAG.getNode(ISD::AND, DL, VT, Shift,
4408                            DAG.getConstant(Mask, DL, VT));
4409       }
4410     }
4411   }
4412   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4413   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4414     unsigned BitSize = VT.getScalarSizeInBits();
4415     SDLoc DL(N);
4416     SDValue HiBitsMask =
4417       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4418                                             BitSize - N1C->getZExtValue()),
4419                       DL, VT);
4420     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4421                        HiBitsMask);
4422   }
4423
4424   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4425   // Variant of version done on multiply, except mul by a power of 2 is turned
4426   // into a shift.
4427   APInt Val;
4428   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4429       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4430        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4431     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4432     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4433     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4434   }
4435
4436   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4437   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4438     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4439       if (SDValue Folded =
4440               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4441         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4442     }
4443   }
4444
4445   if (N1C && !N1C->isOpaque())
4446     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4447       return NewSHL;
4448
4449   return SDValue();
4450 }
4451
4452 SDValue DAGCombiner::visitSRA(SDNode *N) {
4453   SDValue N0 = N->getOperand(0);
4454   SDValue N1 = N->getOperand(1);
4455   EVT VT = N0.getValueType();
4456   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4457
4458   // fold vector ops
4459   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4460   if (VT.isVector()) {
4461     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4462       return FoldedVOp;
4463
4464     N1C = isConstOrConstSplat(N1);
4465   }
4466
4467   // fold (sra c1, c2) -> (sra c1, c2)
4468   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4469   if (N0C && N1C && !N1C->isOpaque())
4470     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4471   // fold (sra 0, x) -> 0
4472   if (isNullConstant(N0))
4473     return N0;
4474   // fold (sra -1, x) -> -1
4475   if (isAllOnesConstant(N0))
4476     return N0;
4477   // fold (sra x, (setge c, size(x))) -> undef
4478   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4479     return DAG.getUNDEF(VT);
4480   // fold (sra x, 0) -> x
4481   if (N1C && N1C->isNullValue())
4482     return N0;
4483   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4484   // sext_inreg.
4485   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4486     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4487     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4488     if (VT.isVector())
4489       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4490                                ExtVT, VT.getVectorNumElements());
4491     if ((!LegalOperations ||
4492          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4493       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4494                          N0.getOperand(0), DAG.getValueType(ExtVT));
4495   }
4496
4497   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4498   if (N1C && N0.getOpcode() == ISD::SRA) {
4499     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4500       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4501       if (Sum >= OpSizeInBits)
4502         Sum = OpSizeInBits - 1;
4503       SDLoc DL(N);
4504       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4505                          DAG.getConstant(Sum, DL, N1.getValueType()));
4506     }
4507   }
4508
4509   // fold (sra (shl X, m), (sub result_size, n))
4510   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4511   // result_size - n != m.
4512   // If truncate is free for the target sext(shl) is likely to result in better
4513   // code.
4514   if (N0.getOpcode() == ISD::SHL && N1C) {
4515     // Get the two constanst of the shifts, CN0 = m, CN = n.
4516     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4517     if (N01C) {
4518       LLVMContext &Ctx = *DAG.getContext();
4519       // Determine what the truncate's result bitsize and type would be.
4520       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4521
4522       if (VT.isVector())
4523         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4524
4525       // Determine the residual right-shift amount.
4526       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4527
4528       // If the shift is not a no-op (in which case this should be just a sign
4529       // extend already), the truncated to type is legal, sign_extend is legal
4530       // on that type, and the truncate to that type is both legal and free,
4531       // perform the transform.
4532       if ((ShiftAmt > 0) &&
4533           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4534           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4535           TLI.isTruncateFree(VT, TruncVT)) {
4536
4537         SDLoc DL(N);
4538         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4539             getShiftAmountTy(N0.getOperand(0).getValueType()));
4540         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4541                                     N0.getOperand(0), Amt);
4542         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4543                                     Shift);
4544         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4545                            N->getValueType(0), Trunc);
4546       }
4547     }
4548   }
4549
4550   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4551   if (N1.getOpcode() == ISD::TRUNCATE &&
4552       N1.getOperand(0).getOpcode() == ISD::AND) {
4553     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4554     if (NewOp1.getNode())
4555       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4556   }
4557
4558   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4559   //      if c1 is equal to the number of bits the trunc removes
4560   if (N0.getOpcode() == ISD::TRUNCATE &&
4561       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4562        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4563       N0.getOperand(0).hasOneUse() &&
4564       N0.getOperand(0).getOperand(1).hasOneUse() &&
4565       N1C) {
4566     SDValue N0Op0 = N0.getOperand(0);
4567     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4568       unsigned LargeShiftVal = LargeShift->getZExtValue();
4569       EVT LargeVT = N0Op0.getValueType();
4570
4571       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4572         SDLoc DL(N);
4573         SDValue Amt =
4574           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4575                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4576         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4577                                   N0Op0.getOperand(0), Amt);
4578         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4579       }
4580     }
4581   }
4582
4583   // Simplify, based on bits shifted out of the LHS.
4584   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4585     return SDValue(N, 0);
4586
4587
4588   // If the sign bit is known to be zero, switch this to a SRL.
4589   if (DAG.SignBitIsZero(N0))
4590     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4591
4592   if (N1C && !N1C->isOpaque())
4593     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4594       return NewSRA;
4595
4596   return SDValue();
4597 }
4598
4599 SDValue DAGCombiner::visitSRL(SDNode *N) {
4600   SDValue N0 = N->getOperand(0);
4601   SDValue N1 = N->getOperand(1);
4602   EVT VT = N0.getValueType();
4603   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4604
4605   // fold vector ops
4606   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4607   if (VT.isVector()) {
4608     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4609       return FoldedVOp;
4610
4611     N1C = isConstOrConstSplat(N1);
4612   }
4613
4614   // fold (srl c1, c2) -> c1 >>u c2
4615   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4616   if (N0C && N1C && !N1C->isOpaque())
4617     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4618   // fold (srl 0, x) -> 0
4619   if (isNullConstant(N0))
4620     return N0;
4621   // fold (srl x, c >= size(x)) -> undef
4622   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4623     return DAG.getUNDEF(VT);
4624   // fold (srl x, 0) -> x
4625   if (N1C && N1C->isNullValue())
4626     return N0;
4627   // if (srl x, c) is known to be zero, return 0
4628   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4629                                    APInt::getAllOnesValue(OpSizeInBits)))
4630     return DAG.getConstant(0, SDLoc(N), VT);
4631
4632   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4633   if (N1C && N0.getOpcode() == ISD::SRL) {
4634     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4635       uint64_t c1 = N01C->getZExtValue();
4636       uint64_t c2 = N1C->getZExtValue();
4637       SDLoc DL(N);
4638       if (c1 + c2 >= OpSizeInBits)
4639         return DAG.getConstant(0, DL, VT);
4640       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4641                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4642     }
4643   }
4644
4645   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4646   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4647       N0.getOperand(0).getOpcode() == ISD::SRL &&
4648       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4649     uint64_t c1 =
4650       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4651     uint64_t c2 = N1C->getZExtValue();
4652     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4653     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4654     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4655     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4656     if (c1 + OpSizeInBits == InnerShiftSize) {
4657       SDLoc DL(N0);
4658       if (c1 + c2 >= InnerShiftSize)
4659         return DAG.getConstant(0, DL, VT);
4660       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4661                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4662                                      N0.getOperand(0)->getOperand(0),
4663                                      DAG.getConstant(c1 + c2, DL,
4664                                                      ShiftCountVT)));
4665     }
4666   }
4667
4668   // fold (srl (shl x, c), c) -> (and x, cst2)
4669   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4670     unsigned BitSize = N0.getScalarValueSizeInBits();
4671     if (BitSize <= 64) {
4672       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4673       SDLoc DL(N);
4674       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4675                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4676     }
4677   }
4678
4679   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4680   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4681     // Shifting in all undef bits?
4682     EVT SmallVT = N0.getOperand(0).getValueType();
4683     unsigned BitSize = SmallVT.getScalarSizeInBits();
4684     if (N1C->getZExtValue() >= BitSize)
4685       return DAG.getUNDEF(VT);
4686
4687     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4688       uint64_t ShiftAmt = N1C->getZExtValue();
4689       SDLoc DL0(N0);
4690       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4691                                        N0.getOperand(0),
4692                           DAG.getConstant(ShiftAmt, DL0,
4693                                           getShiftAmountTy(SmallVT)));
4694       AddToWorklist(SmallShift.getNode());
4695       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4696       SDLoc DL(N);
4697       return DAG.getNode(ISD::AND, DL, VT,
4698                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4699                          DAG.getConstant(Mask, DL, VT));
4700     }
4701   }
4702
4703   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4704   // bit, which is unmodified by sra.
4705   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4706     if (N0.getOpcode() == ISD::SRA)
4707       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4708   }
4709
4710   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4711   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4712       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4713     APInt KnownZero, KnownOne;
4714     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4715
4716     // If any of the input bits are KnownOne, then the input couldn't be all
4717     // zeros, thus the result of the srl will always be zero.
4718     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4719
4720     // If all of the bits input the to ctlz node are known to be zero, then
4721     // the result of the ctlz is "32" and the result of the shift is one.
4722     APInt UnknownBits = ~KnownZero;
4723     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4724
4725     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4726     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4727       // Okay, we know that only that the single bit specified by UnknownBits
4728       // could be set on input to the CTLZ node. If this bit is set, the SRL
4729       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4730       // to an SRL/XOR pair, which is likely to simplify more.
4731       unsigned ShAmt = UnknownBits.countTrailingZeros();
4732       SDValue Op = N0.getOperand(0);
4733
4734       if (ShAmt) {
4735         SDLoc DL(N0);
4736         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4737                   DAG.getConstant(ShAmt, DL,
4738                                   getShiftAmountTy(Op.getValueType())));
4739         AddToWorklist(Op.getNode());
4740       }
4741
4742       SDLoc DL(N);
4743       return DAG.getNode(ISD::XOR, DL, VT,
4744                          Op, DAG.getConstant(1, DL, VT));
4745     }
4746   }
4747
4748   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4749   if (N1.getOpcode() == ISD::TRUNCATE &&
4750       N1.getOperand(0).getOpcode() == ISD::AND) {
4751     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4752       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4753   }
4754
4755   // fold operands of srl based on knowledge that the low bits are not
4756   // demanded.
4757   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4758     return SDValue(N, 0);
4759
4760   if (N1C && !N1C->isOpaque())
4761     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4762       return NewSRL;
4763
4764   // Attempt to convert a srl of a load into a narrower zero-extending load.
4765   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4766     return NarrowLoad;
4767
4768   // Here is a common situation. We want to optimize:
4769   //
4770   //   %a = ...
4771   //   %b = and i32 %a, 2
4772   //   %c = srl i32 %b, 1
4773   //   brcond i32 %c ...
4774   //
4775   // into
4776   //
4777   //   %a = ...
4778   //   %b = and %a, 2
4779   //   %c = setcc eq %b, 0
4780   //   brcond %c ...
4781   //
4782   // However when after the source operand of SRL is optimized into AND, the SRL
4783   // itself may not be optimized further. Look for it and add the BRCOND into
4784   // the worklist.
4785   if (N->hasOneUse()) {
4786     SDNode *Use = *N->use_begin();
4787     if (Use->getOpcode() == ISD::BRCOND)
4788       AddToWorklist(Use);
4789     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4790       // Also look pass the truncate.
4791       Use = *Use->use_begin();
4792       if (Use->getOpcode() == ISD::BRCOND)
4793         AddToWorklist(Use);
4794     }
4795   }
4796
4797   return SDValue();
4798 }
4799
4800 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4801   SDValue N0 = N->getOperand(0);
4802   EVT VT = N->getValueType(0);
4803
4804   // fold (bswap c1) -> c2
4805   if (isConstantIntBuildVectorOrConstantInt(N0))
4806     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4807   // fold (bswap (bswap x)) -> x
4808   if (N0.getOpcode() == ISD::BSWAP)
4809     return N0->getOperand(0);
4810   return SDValue();
4811 }
4812
4813 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4814   SDValue N0 = N->getOperand(0);
4815   EVT VT = N->getValueType(0);
4816
4817   // fold (ctlz c1) -> c2
4818   if (isConstantIntBuildVectorOrConstantInt(N0))
4819     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4820   return SDValue();
4821 }
4822
4823 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4824   SDValue N0 = N->getOperand(0);
4825   EVT VT = N->getValueType(0);
4826
4827   // fold (ctlz_zero_undef c1) -> c2
4828   if (isConstantIntBuildVectorOrConstantInt(N0))
4829     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4830   return SDValue();
4831 }
4832
4833 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4834   SDValue N0 = N->getOperand(0);
4835   EVT VT = N->getValueType(0);
4836
4837   // fold (cttz c1) -> c2
4838   if (isConstantIntBuildVectorOrConstantInt(N0))
4839     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4840   return SDValue();
4841 }
4842
4843 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4844   SDValue N0 = N->getOperand(0);
4845   EVT VT = N->getValueType(0);
4846
4847   // fold (cttz_zero_undef c1) -> c2
4848   if (isConstantIntBuildVectorOrConstantInt(N0))
4849     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4850   return SDValue();
4851 }
4852
4853 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4854   SDValue N0 = N->getOperand(0);
4855   EVT VT = N->getValueType(0);
4856
4857   // fold (ctpop c1) -> c2
4858   if (isConstantIntBuildVectorOrConstantInt(N0))
4859     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4860   return SDValue();
4861 }
4862
4863
4864 /// \brief Generate Min/Max node
4865 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4866                                    SDValue True, SDValue False,
4867                                    ISD::CondCode CC, const TargetLowering &TLI,
4868                                    SelectionDAG &DAG) {
4869   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4870     return SDValue();
4871
4872   switch (CC) {
4873   case ISD::SETOLT:
4874   case ISD::SETOLE:
4875   case ISD::SETLT:
4876   case ISD::SETLE:
4877   case ISD::SETULT:
4878   case ISD::SETULE: {
4879     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4880     if (TLI.isOperationLegal(Opcode, VT))
4881       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4882     return SDValue();
4883   }
4884   case ISD::SETOGT:
4885   case ISD::SETOGE:
4886   case ISD::SETGT:
4887   case ISD::SETGE:
4888   case ISD::SETUGT:
4889   case ISD::SETUGE: {
4890     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4891     if (TLI.isOperationLegal(Opcode, VT))
4892       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4893     return SDValue();
4894   }
4895   default:
4896     return SDValue();
4897   }
4898 }
4899
4900 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4901   SDValue N0 = N->getOperand(0);
4902   SDValue N1 = N->getOperand(1);
4903   SDValue N2 = N->getOperand(2);
4904   EVT VT = N->getValueType(0);
4905   EVT VT0 = N0.getValueType();
4906
4907   // fold (select C, X, X) -> X
4908   if (N1 == N2)
4909     return N1;
4910   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4911     // fold (select true, X, Y) -> X
4912     // fold (select false, X, Y) -> Y
4913     return !N0C->isNullValue() ? N1 : N2;
4914   }
4915   // fold (select C, 1, X) -> (or C, X)
4916   if (VT == MVT::i1 && isOneConstant(N1))
4917     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4918   // fold (select C, 0, 1) -> (xor C, 1)
4919   // We can't do this reliably if integer based booleans have different contents
4920   // to floating point based booleans. This is because we can't tell whether we
4921   // have an integer-based boolean or a floating-point-based boolean unless we
4922   // can find the SETCC that produced it and inspect its operands. This is
4923   // fairly easy if C is the SETCC node, but it can potentially be
4924   // undiscoverable (or not reasonably discoverable). For example, it could be
4925   // in another basic block or it could require searching a complicated
4926   // expression.
4927   if (VT.isInteger() &&
4928       (VT0 == MVT::i1 || (VT0.isInteger() &&
4929                           TLI.getBooleanContents(false, false) ==
4930                               TLI.getBooleanContents(false, true) &&
4931                           TLI.getBooleanContents(false, false) ==
4932                               TargetLowering::ZeroOrOneBooleanContent)) &&
4933       isNullConstant(N1) && isOneConstant(N2)) {
4934     SDValue XORNode;
4935     if (VT == VT0) {
4936       SDLoc DL(N);
4937       return DAG.getNode(ISD::XOR, DL, VT0,
4938                          N0, DAG.getConstant(1, DL, VT0));
4939     }
4940     SDLoc DL0(N0);
4941     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4942                           N0, DAG.getConstant(1, DL0, VT0));
4943     AddToWorklist(XORNode.getNode());
4944     if (VT.bitsGT(VT0))
4945       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4946     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4947   }
4948   // fold (select C, 0, X) -> (and (not C), X)
4949   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4950     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4951     AddToWorklist(NOTNode.getNode());
4952     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4953   }
4954   // fold (select C, X, 1) -> (or (not C), X)
4955   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4956     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4957     AddToWorklist(NOTNode.getNode());
4958     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4959   }
4960   // fold (select C, X, 0) -> (and C, X)
4961   if (VT == MVT::i1 && isNullConstant(N2))
4962     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4963   // fold (select X, X, Y) -> (or X, Y)
4964   // fold (select X, 1, Y) -> (or X, Y)
4965   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4966     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4967   // fold (select X, Y, X) -> (and X, Y)
4968   // fold (select X, Y, 0) -> (and X, Y)
4969   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4970     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4971
4972   // If we can fold this based on the true/false value, do so.
4973   if (SimplifySelectOps(N, N1, N2))
4974     return SDValue(N, 0);  // Don't revisit N.
4975
4976   if (VT0 == MVT::i1) {
4977     // The code in this block deals with the following 2 equivalences:
4978     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
4979     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
4980     // The target can specify its prefered form with the
4981     // shouldNormalizeToSelectSequence() callback. However we always transform
4982     // to the right anyway if we find the inner select exists in the DAG anyway
4983     // and we always transform to the left side if we know that we can further
4984     // optimize the combination of the conditions.
4985     bool normalizeToSequence
4986       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
4987     // select (and Cond0, Cond1), X, Y
4988     //   -> select Cond0, (select Cond1, X, Y), Y
4989     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4990       SDValue Cond0 = N0->getOperand(0);
4991       SDValue Cond1 = N0->getOperand(1);
4992       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4993                                         N1.getValueType(), Cond1, N1, N2);
4994       if (normalizeToSequence || !InnerSelect.use_empty())
4995         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4996                            InnerSelect, N2);
4997     }
4998     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4999     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5000       SDValue Cond0 = N0->getOperand(0);
5001       SDValue Cond1 = N0->getOperand(1);
5002       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5003                                         N1.getValueType(), Cond1, N1, N2);
5004       if (normalizeToSequence || !InnerSelect.use_empty())
5005         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5006                            InnerSelect);
5007     }
5008
5009     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5010     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5011       SDValue N1_0 = N1->getOperand(0);
5012       SDValue N1_1 = N1->getOperand(1);
5013       SDValue N1_2 = N1->getOperand(2);
5014       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5015         // Create the actual and node if we can generate good code for it.
5016         if (!normalizeToSequence) {
5017           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5018                                     N0, N1_0);
5019           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5020                              N1_1, N2);
5021         }
5022         // Otherwise see if we can optimize the "and" to a better pattern.
5023         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5024           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5025                              N1_1, N2);
5026       }
5027     }
5028     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5029     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5030       SDValue N2_0 = N2->getOperand(0);
5031       SDValue N2_1 = N2->getOperand(1);
5032       SDValue N2_2 = N2->getOperand(2);
5033       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5034         // Create the actual or node if we can generate good code for it.
5035         if (!normalizeToSequence) {
5036           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5037                                    N0, N2_0);
5038           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5039                              N1, N2_2);
5040         }
5041         // Otherwise see if we can optimize to a better pattern.
5042         if (SDValue Combined = visitORLike(N0, N2_0, N))
5043           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5044                              N1, N2_2);
5045       }
5046     }
5047   }
5048
5049   // fold selects based on a setcc into other things, such as min/max/abs
5050   if (N0.getOpcode() == ISD::SETCC) {
5051     // select x, y (fcmp lt x, y) -> fminnum x, y
5052     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5053     //
5054     // This is OK if we don't care about what happens if either operand is a
5055     // NaN.
5056     //
5057
5058     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5059     // no signed zeros as well as no nans.
5060     const TargetOptions &Options = DAG.getTarget().Options;
5061     if (Options.UnsafeFPMath &&
5062         VT.isFloatingPoint() && N0.hasOneUse() &&
5063         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5064       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5065
5066       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5067                                                 N0.getOperand(1), N1, N2, CC,
5068                                                 TLI, DAG))
5069         return FMinMax;
5070     }
5071
5072     if ((!LegalOperations &&
5073          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5074         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5075       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5076                          N0.getOperand(0), N0.getOperand(1),
5077                          N1, N2, N0.getOperand(2));
5078     return SimplifySelect(SDLoc(N), N0, N1, N2);
5079   }
5080
5081   return SDValue();
5082 }
5083
5084 static
5085 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5086   SDLoc DL(N);
5087   EVT LoVT, HiVT;
5088   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5089
5090   // Split the inputs.
5091   SDValue Lo, Hi, LL, LH, RL, RH;
5092   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5093   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5094
5095   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5096   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5097
5098   return std::make_pair(Lo, Hi);
5099 }
5100
5101 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5102 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5103 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5104   SDLoc dl(N);
5105   SDValue Cond = N->getOperand(0);
5106   SDValue LHS = N->getOperand(1);
5107   SDValue RHS = N->getOperand(2);
5108   EVT VT = N->getValueType(0);
5109   int NumElems = VT.getVectorNumElements();
5110   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5111          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5112          Cond.getOpcode() == ISD::BUILD_VECTOR);
5113
5114   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5115   // binary ones here.
5116   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5117     return SDValue();
5118
5119   // We're sure we have an even number of elements due to the
5120   // concat_vectors we have as arguments to vselect.
5121   // Skip BV elements until we find one that's not an UNDEF
5122   // After we find an UNDEF element, keep looping until we get to half the
5123   // length of the BV and see if all the non-undef nodes are the same.
5124   ConstantSDNode *BottomHalf = nullptr;
5125   for (int i = 0; i < NumElems / 2; ++i) {
5126     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5127       continue;
5128
5129     if (BottomHalf == nullptr)
5130       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5131     else if (Cond->getOperand(i).getNode() != BottomHalf)
5132       return SDValue();
5133   }
5134
5135   // Do the same for the second half of the BuildVector
5136   ConstantSDNode *TopHalf = nullptr;
5137   for (int i = NumElems / 2; i < NumElems; ++i) {
5138     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5139       continue;
5140
5141     if (TopHalf == nullptr)
5142       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5143     else if (Cond->getOperand(i).getNode() != TopHalf)
5144       return SDValue();
5145   }
5146
5147   assert(TopHalf && BottomHalf &&
5148          "One half of the selector was all UNDEFs and the other was all the "
5149          "same value. This should have been addressed before this function.");
5150   return DAG.getNode(
5151       ISD::CONCAT_VECTORS, dl, VT,
5152       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5153       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5154 }
5155
5156 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5157
5158   if (Level >= AfterLegalizeTypes)
5159     return SDValue();
5160
5161   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5162   SDValue Mask = MSC->getMask();
5163   SDValue Data  = MSC->getValue();
5164   SDLoc DL(N);
5165
5166   // If the MSCATTER data type requires splitting and the mask is provided by a
5167   // SETCC, then split both nodes and its operands before legalization. This
5168   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5169   // and enables future optimizations (e.g. min/max pattern matching on X86).
5170   if (Mask.getOpcode() != ISD::SETCC)
5171     return SDValue();
5172
5173   // Check if any splitting is required.
5174   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5175       TargetLowering::TypeSplitVector)
5176     return SDValue();
5177   SDValue MaskLo, MaskHi, Lo, Hi;
5178   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5179
5180   EVT LoVT, HiVT;
5181   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5182
5183   SDValue Chain = MSC->getChain();
5184
5185   EVT MemoryVT = MSC->getMemoryVT();
5186   unsigned Alignment = MSC->getOriginalAlignment();
5187
5188   EVT LoMemVT, HiMemVT;
5189   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5190
5191   SDValue DataLo, DataHi;
5192   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5193
5194   SDValue BasePtr = MSC->getBasePtr();
5195   SDValue IndexLo, IndexHi;
5196   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5197
5198   MachineMemOperand *MMO = DAG.getMachineFunction().
5199     getMachineMemOperand(MSC->getPointerInfo(),
5200                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5201                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5202
5203   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5204   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5205                             DL, OpsLo, MMO);
5206
5207   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5208   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5209                             DL, OpsHi, MMO);
5210
5211   AddToWorklist(Lo.getNode());
5212   AddToWorklist(Hi.getNode());
5213
5214   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5215 }
5216
5217 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5218
5219   if (Level >= AfterLegalizeTypes)
5220     return SDValue();
5221
5222   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5223   SDValue Mask = MST->getMask();
5224   SDValue Data  = MST->getValue();
5225   SDLoc DL(N);
5226
5227   // If the MSTORE data type requires splitting and the mask is provided by a
5228   // SETCC, then split both nodes and its operands before legalization. This
5229   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5230   // and enables future optimizations (e.g. min/max pattern matching on X86).
5231   if (Mask.getOpcode() == ISD::SETCC) {
5232
5233     // Check if any splitting is required.
5234     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5235         TargetLowering::TypeSplitVector)
5236       return SDValue();
5237
5238     SDValue MaskLo, MaskHi, Lo, Hi;
5239     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5240
5241     EVT LoVT, HiVT;
5242     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5243
5244     SDValue Chain = MST->getChain();
5245     SDValue Ptr   = MST->getBasePtr();
5246
5247     EVT MemoryVT = MST->getMemoryVT();
5248     unsigned Alignment = MST->getOriginalAlignment();
5249
5250     // if Alignment is equal to the vector size,
5251     // take the half of it for the second part
5252     unsigned SecondHalfAlignment =
5253       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5254          Alignment/2 : Alignment;
5255
5256     EVT LoMemVT, HiMemVT;
5257     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5258
5259     SDValue DataLo, DataHi;
5260     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5261
5262     MachineMemOperand *MMO = DAG.getMachineFunction().
5263       getMachineMemOperand(MST->getPointerInfo(),
5264                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5265                            Alignment, MST->getAAInfo(), MST->getRanges());
5266
5267     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5268                             MST->isTruncatingStore());
5269
5270     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5271     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5272                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5273
5274     MMO = DAG.getMachineFunction().
5275       getMachineMemOperand(MST->getPointerInfo(),
5276                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5277                            SecondHalfAlignment, MST->getAAInfo(),
5278                            MST->getRanges());
5279
5280     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5281                             MST->isTruncatingStore());
5282
5283     AddToWorklist(Lo.getNode());
5284     AddToWorklist(Hi.getNode());
5285
5286     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5287   }
5288   return SDValue();
5289 }
5290
5291 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5292
5293   if (Level >= AfterLegalizeTypes)
5294     return SDValue();
5295
5296   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5297   SDValue Mask = MGT->getMask();
5298   SDLoc DL(N);
5299
5300   // If the MGATHER result requires splitting and the mask is provided by a
5301   // SETCC, then split both nodes and its operands before legalization. This
5302   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5303   // and enables future optimizations (e.g. min/max pattern matching on X86).
5304
5305   if (Mask.getOpcode() != ISD::SETCC)
5306     return SDValue();
5307
5308   EVT VT = N->getValueType(0);
5309
5310   // Check if any splitting is required.
5311   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5312       TargetLowering::TypeSplitVector)
5313     return SDValue();
5314
5315   SDValue MaskLo, MaskHi, Lo, Hi;
5316   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5317
5318   SDValue Src0 = MGT->getValue();
5319   SDValue Src0Lo, Src0Hi;
5320   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5321
5322   EVT LoVT, HiVT;
5323   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5324
5325   SDValue Chain = MGT->getChain();
5326   EVT MemoryVT = MGT->getMemoryVT();
5327   unsigned Alignment = MGT->getOriginalAlignment();
5328
5329   EVT LoMemVT, HiMemVT;
5330   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5331
5332   SDValue BasePtr = MGT->getBasePtr();
5333   SDValue Index = MGT->getIndex();
5334   SDValue IndexLo, IndexHi;
5335   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5336
5337   MachineMemOperand *MMO = DAG.getMachineFunction().
5338     getMachineMemOperand(MGT->getPointerInfo(),
5339                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5340                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5341
5342   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5343   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5344                             MMO);
5345
5346   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5347   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5348                             MMO);
5349
5350   AddToWorklist(Lo.getNode());
5351   AddToWorklist(Hi.getNode());
5352
5353   // Build a factor node to remember that this load is independent of the
5354   // other one.
5355   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5356                       Hi.getValue(1));
5357
5358   // Legalized the chain result - switch anything that used the old chain to
5359   // use the new one.
5360   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5361
5362   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5363
5364   SDValue RetOps[] = { GatherRes, Chain };
5365   return DAG.getMergeValues(RetOps, DL);
5366 }
5367
5368 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5369
5370   if (Level >= AfterLegalizeTypes)
5371     return SDValue();
5372
5373   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5374   SDValue Mask = MLD->getMask();
5375   SDLoc DL(N);
5376
5377   // If the MLOAD result requires splitting and the mask is provided by a
5378   // SETCC, then split both nodes and its operands before legalization. This
5379   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5380   // and enables future optimizations (e.g. min/max pattern matching on X86).
5381
5382   if (Mask.getOpcode() == ISD::SETCC) {
5383     EVT VT = N->getValueType(0);
5384
5385     // Check if any splitting is required.
5386     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5387         TargetLowering::TypeSplitVector)
5388       return SDValue();
5389
5390     SDValue MaskLo, MaskHi, Lo, Hi;
5391     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5392
5393     SDValue Src0 = MLD->getSrc0();
5394     SDValue Src0Lo, Src0Hi;
5395     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5396
5397     EVT LoVT, HiVT;
5398     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5399
5400     SDValue Chain = MLD->getChain();
5401     SDValue Ptr   = MLD->getBasePtr();
5402     EVT MemoryVT = MLD->getMemoryVT();
5403     unsigned Alignment = MLD->getOriginalAlignment();
5404
5405     // if Alignment is equal to the vector size,
5406     // take the half of it for the second part
5407     unsigned SecondHalfAlignment =
5408       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5409          Alignment/2 : Alignment;
5410
5411     EVT LoMemVT, HiMemVT;
5412     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5413
5414     MachineMemOperand *MMO = DAG.getMachineFunction().
5415     getMachineMemOperand(MLD->getPointerInfo(),
5416                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5417                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5418
5419     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5420                            ISD::NON_EXTLOAD);
5421
5422     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5423     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5424                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5425
5426     MMO = DAG.getMachineFunction().
5427     getMachineMemOperand(MLD->getPointerInfo(),
5428                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5429                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5430
5431     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5432                            ISD::NON_EXTLOAD);
5433
5434     AddToWorklist(Lo.getNode());
5435     AddToWorklist(Hi.getNode());
5436
5437     // Build a factor node to remember that this load is independent of the
5438     // other one.
5439     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5440                         Hi.getValue(1));
5441
5442     // Legalized the chain result - switch anything that used the old chain to
5443     // use the new one.
5444     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5445
5446     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5447
5448     SDValue RetOps[] = { LoadRes, Chain };
5449     return DAG.getMergeValues(RetOps, DL);
5450   }
5451   return SDValue();
5452 }
5453
5454 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5455   SDValue N0 = N->getOperand(0);
5456   SDValue N1 = N->getOperand(1);
5457   SDValue N2 = N->getOperand(2);
5458   SDLoc DL(N);
5459
5460   // Canonicalize integer abs.
5461   // vselect (setg[te] X,  0),  X, -X ->
5462   // vselect (setgt    X, -1),  X, -X ->
5463   // vselect (setl[te] X,  0), -X,  X ->
5464   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5465   if (N0.getOpcode() == ISD::SETCC) {
5466     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5467     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5468     bool isAbs = false;
5469     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5470
5471     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5472          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5473         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5474       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5475     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5476              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5477       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5478
5479     if (isAbs) {
5480       EVT VT = LHS.getValueType();
5481       SDValue Shift = DAG.getNode(
5482           ISD::SRA, DL, VT, LHS,
5483           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5484       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5485       AddToWorklist(Shift.getNode());
5486       AddToWorklist(Add.getNode());
5487       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5488     }
5489   }
5490
5491   if (SimplifySelectOps(N, N1, N2))
5492     return SDValue(N, 0);  // Don't revisit N.
5493
5494   // If the VSELECT result requires splitting and the mask is provided by a
5495   // SETCC, then split both nodes and its operands before legalization. This
5496   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5497   // and enables future optimizations (e.g. min/max pattern matching on X86).
5498   if (N0.getOpcode() == ISD::SETCC) {
5499     EVT VT = N->getValueType(0);
5500
5501     // Check if any splitting is required.
5502     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5503         TargetLowering::TypeSplitVector)
5504       return SDValue();
5505
5506     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5507     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5508     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5509     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5510
5511     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5512     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5513
5514     // Add the new VSELECT nodes to the work list in case they need to be split
5515     // again.
5516     AddToWorklist(Lo.getNode());
5517     AddToWorklist(Hi.getNode());
5518
5519     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5520   }
5521
5522   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5523   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5524     return N1;
5525   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5526   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5527     return N2;
5528
5529   // The ConvertSelectToConcatVector function is assuming both the above
5530   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5531   // and addressed.
5532   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5533       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5534       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5535     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5536       return CV;
5537   }
5538
5539   return SDValue();
5540 }
5541
5542 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5543   SDValue N0 = N->getOperand(0);
5544   SDValue N1 = N->getOperand(1);
5545   SDValue N2 = N->getOperand(2);
5546   SDValue N3 = N->getOperand(3);
5547   SDValue N4 = N->getOperand(4);
5548   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5549
5550   // fold select_cc lhs, rhs, x, x, cc -> x
5551   if (N2 == N3)
5552     return N2;
5553
5554   // Determine if the condition we're dealing with is constant
5555   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5556                               N0, N1, CC, SDLoc(N), false);
5557   if (SCC.getNode()) {
5558     AddToWorklist(SCC.getNode());
5559
5560     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5561       if (!SCCC->isNullValue())
5562         return N2;    // cond always true -> true val
5563       else
5564         return N3;    // cond always false -> false val
5565     } else if (SCC->getOpcode() == ISD::UNDEF) {
5566       // When the condition is UNDEF, just return the first operand. This is
5567       // coherent the DAG creation, no setcc node is created in this case
5568       return N2;
5569     } else if (SCC.getOpcode() == ISD::SETCC) {
5570       // Fold to a simpler select_cc
5571       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5572                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5573                          SCC.getOperand(2));
5574     }
5575   }
5576
5577   // If we can fold this based on the true/false value, do so.
5578   if (SimplifySelectOps(N, N2, N3))
5579     return SDValue(N, 0);  // Don't revisit N.
5580
5581   // fold select_cc into other things, such as min/max/abs
5582   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5583 }
5584
5585 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5586   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5587                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5588                        SDLoc(N));
5589 }
5590
5591 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5592 /// a build_vector of constants.
5593 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5594 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5595 /// Vector extends are not folded if operations are legal; this is to
5596 /// avoid introducing illegal build_vector dag nodes.
5597 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5598                                          SelectionDAG &DAG, bool LegalTypes,
5599                                          bool LegalOperations) {
5600   unsigned Opcode = N->getOpcode();
5601   SDValue N0 = N->getOperand(0);
5602   EVT VT = N->getValueType(0);
5603
5604   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5605          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5606          && "Expected EXTEND dag node in input!");
5607
5608   // fold (sext c1) -> c1
5609   // fold (zext c1) -> c1
5610   // fold (aext c1) -> c1
5611   if (isa<ConstantSDNode>(N0))
5612     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5613
5614   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5615   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5616   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5617   EVT SVT = VT.getScalarType();
5618   if (!(VT.isVector() &&
5619       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5620       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5621     return nullptr;
5622
5623   // We can fold this node into a build_vector.
5624   unsigned VTBits = SVT.getSizeInBits();
5625   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5626   SmallVector<SDValue, 8> Elts;
5627   unsigned NumElts = VT.getVectorNumElements();
5628   SDLoc DL(N);
5629
5630   for (unsigned i=0; i != NumElts; ++i) {
5631     SDValue Op = N0->getOperand(i);
5632     if (Op->getOpcode() == ISD::UNDEF) {
5633       Elts.push_back(DAG.getUNDEF(SVT));
5634       continue;
5635     }
5636
5637     SDLoc DL(Op);
5638     // Get the constant value and if needed trunc it to the size of the type.
5639     // Nodes like build_vector might have constants wider than the scalar type.
5640     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5641     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5642       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5643     else
5644       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5645   }
5646
5647   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5648 }
5649
5650 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5651 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5652 // transformation. Returns true if extension are possible and the above
5653 // mentioned transformation is profitable.
5654 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5655                                     unsigned ExtOpc,
5656                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5657                                     const TargetLowering &TLI) {
5658   bool HasCopyToRegUses = false;
5659   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5660   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5661                             UE = N0.getNode()->use_end();
5662        UI != UE; ++UI) {
5663     SDNode *User = *UI;
5664     if (User == N)
5665       continue;
5666     if (UI.getUse().getResNo() != N0.getResNo())
5667       continue;
5668     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5669     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5670       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5671       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5672         // Sign bits will be lost after a zext.
5673         return false;
5674       bool Add = false;
5675       for (unsigned i = 0; i != 2; ++i) {
5676         SDValue UseOp = User->getOperand(i);
5677         if (UseOp == N0)
5678           continue;
5679         if (!isa<ConstantSDNode>(UseOp))
5680           return false;
5681         Add = true;
5682       }
5683       if (Add)
5684         ExtendNodes.push_back(User);
5685       continue;
5686     }
5687     // If truncates aren't free and there are users we can't
5688     // extend, it isn't worthwhile.
5689     if (!isTruncFree)
5690       return false;
5691     // Remember if this value is live-out.
5692     if (User->getOpcode() == ISD::CopyToReg)
5693       HasCopyToRegUses = true;
5694   }
5695
5696   if (HasCopyToRegUses) {
5697     bool BothLiveOut = false;
5698     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5699          UI != UE; ++UI) {
5700       SDUse &Use = UI.getUse();
5701       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5702         BothLiveOut = true;
5703         break;
5704       }
5705     }
5706     if (BothLiveOut)
5707       // Both unextended and extended values are live out. There had better be
5708       // a good reason for the transformation.
5709       return ExtendNodes.size();
5710   }
5711   return true;
5712 }
5713
5714 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5715                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5716                                   ISD::NodeType ExtType) {
5717   // Extend SetCC uses if necessary.
5718   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5719     SDNode *SetCC = SetCCs[i];
5720     SmallVector<SDValue, 4> Ops;
5721
5722     for (unsigned j = 0; j != 2; ++j) {
5723       SDValue SOp = SetCC->getOperand(j);
5724       if (SOp == Trunc)
5725         Ops.push_back(ExtLoad);
5726       else
5727         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5728     }
5729
5730     Ops.push_back(SetCC->getOperand(2));
5731     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5732   }
5733 }
5734
5735 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5736 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5737   SDValue N0 = N->getOperand(0);
5738   EVT DstVT = N->getValueType(0);
5739   EVT SrcVT = N0.getValueType();
5740
5741   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5742           N->getOpcode() == ISD::ZERO_EXTEND) &&
5743          "Unexpected node type (not an extend)!");
5744
5745   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5746   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5747   //   (v8i32 (sext (v8i16 (load x))))
5748   // into:
5749   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5750   //                          (v4i32 (sextload (x + 16)))))
5751   // Where uses of the original load, i.e.:
5752   //   (v8i16 (load x))
5753   // are replaced with:
5754   //   (v8i16 (truncate
5755   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5756   //                            (v4i32 (sextload (x + 16)))))))
5757   //
5758   // This combine is only applicable to illegal, but splittable, vectors.
5759   // All legal types, and illegal non-vector types, are handled elsewhere.
5760   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5761   //
5762   if (N0->getOpcode() != ISD::LOAD)
5763     return SDValue();
5764
5765   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5766
5767   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5768       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5769       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5770     return SDValue();
5771
5772   SmallVector<SDNode *, 4> SetCCs;
5773   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5774     return SDValue();
5775
5776   ISD::LoadExtType ExtType =
5777       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5778
5779   // Try to split the vector types to get down to legal types.
5780   EVT SplitSrcVT = SrcVT;
5781   EVT SplitDstVT = DstVT;
5782   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5783          SplitSrcVT.getVectorNumElements() > 1) {
5784     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5785     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5786   }
5787
5788   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5789     return SDValue();
5790
5791   SDLoc DL(N);
5792   const unsigned NumSplits =
5793       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5794   const unsigned Stride = SplitSrcVT.getStoreSize();
5795   SmallVector<SDValue, 4> Loads;
5796   SmallVector<SDValue, 4> Chains;
5797
5798   SDValue BasePtr = LN0->getBasePtr();
5799   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5800     const unsigned Offset = Idx * Stride;
5801     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5802
5803     SDValue SplitLoad = DAG.getExtLoad(
5804         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5805         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5806         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5807         Align, LN0->getAAInfo());
5808
5809     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5810                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5811
5812     Loads.push_back(SplitLoad.getValue(0));
5813     Chains.push_back(SplitLoad.getValue(1));
5814   }
5815
5816   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5817   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5818
5819   CombineTo(N, NewValue);
5820
5821   // Replace uses of the original load (before extension)
5822   // with a truncate of the concatenated sextloaded vectors.
5823   SDValue Trunc =
5824       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5825   CombineTo(N0.getNode(), Trunc, NewChain);
5826   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5827                   (ISD::NodeType)N->getOpcode());
5828   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5829 }
5830
5831 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5832   SDValue N0 = N->getOperand(0);
5833   EVT VT = N->getValueType(0);
5834
5835   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5836                                               LegalOperations))
5837     return SDValue(Res, 0);
5838
5839   // fold (sext (sext x)) -> (sext x)
5840   // fold (sext (aext x)) -> (sext x)
5841   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5842     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5843                        N0.getOperand(0));
5844
5845   if (N0.getOpcode() == ISD::TRUNCATE) {
5846     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5847     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5848     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5849       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5850       if (NarrowLoad.getNode() != N0.getNode()) {
5851         CombineTo(N0.getNode(), NarrowLoad);
5852         // CombineTo deleted the truncate, if needed, but not what's under it.
5853         AddToWorklist(oye);
5854       }
5855       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5856     }
5857
5858     // See if the value being truncated is already sign extended.  If so, just
5859     // eliminate the trunc/sext pair.
5860     SDValue Op = N0.getOperand(0);
5861     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5862     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5863     unsigned DestBits = VT.getScalarType().getSizeInBits();
5864     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5865
5866     if (OpBits == DestBits) {
5867       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5868       // bits, it is already ready.
5869       if (NumSignBits > DestBits-MidBits)
5870         return Op;
5871     } else if (OpBits < DestBits) {
5872       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5873       // bits, just sext from i32.
5874       if (NumSignBits > OpBits-MidBits)
5875         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5876     } else {
5877       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5878       // bits, just truncate to i32.
5879       if (NumSignBits > OpBits-MidBits)
5880         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5881     }
5882
5883     // fold (sext (truncate x)) -> (sextinreg x).
5884     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5885                                                  N0.getValueType())) {
5886       if (OpBits < DestBits)
5887         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5888       else if (OpBits > DestBits)
5889         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5890       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5891                          DAG.getValueType(N0.getValueType()));
5892     }
5893   }
5894
5895   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5896   // Only generate vector extloads when 1) they're legal, and 2) they are
5897   // deemed desirable by the target.
5898   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5899       ((!LegalOperations && !VT.isVector() &&
5900         !cast<LoadSDNode>(N0)->isVolatile()) ||
5901        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5902     bool DoXform = true;
5903     SmallVector<SDNode*, 4> SetCCs;
5904     if (!N0.hasOneUse())
5905       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5906     if (VT.isVector())
5907       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5908     if (DoXform) {
5909       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5910       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5911                                        LN0->getChain(),
5912                                        LN0->getBasePtr(), N0.getValueType(),
5913                                        LN0->getMemOperand());
5914       CombineTo(N, ExtLoad);
5915       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5916                                   N0.getValueType(), ExtLoad);
5917       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5918       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5919                       ISD::SIGN_EXTEND);
5920       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5921     }
5922   }
5923
5924   // fold (sext (load x)) to multiple smaller sextloads.
5925   // Only on illegal but splittable vectors.
5926   if (SDValue ExtLoad = CombineExtLoad(N))
5927     return ExtLoad;
5928
5929   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5930   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5931   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5932       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5933     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5934     EVT MemVT = LN0->getMemoryVT();
5935     if ((!LegalOperations && !LN0->isVolatile()) ||
5936         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5937       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5938                                        LN0->getChain(),
5939                                        LN0->getBasePtr(), MemVT,
5940                                        LN0->getMemOperand());
5941       CombineTo(N, ExtLoad);
5942       CombineTo(N0.getNode(),
5943                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5944                             N0.getValueType(), ExtLoad),
5945                 ExtLoad.getValue(1));
5946       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5947     }
5948   }
5949
5950   // fold (sext (and/or/xor (load x), cst)) ->
5951   //      (and/or/xor (sextload x), (sext cst))
5952   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5953        N0.getOpcode() == ISD::XOR) &&
5954       isa<LoadSDNode>(N0.getOperand(0)) &&
5955       N0.getOperand(1).getOpcode() == ISD::Constant &&
5956       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5957       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5958     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5959     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5960       bool DoXform = true;
5961       SmallVector<SDNode*, 4> SetCCs;
5962       if (!N0.hasOneUse())
5963         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5964                                           SetCCs, TLI);
5965       if (DoXform) {
5966         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5967                                          LN0->getChain(), LN0->getBasePtr(),
5968                                          LN0->getMemoryVT(),
5969                                          LN0->getMemOperand());
5970         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5971         Mask = Mask.sext(VT.getSizeInBits());
5972         SDLoc DL(N);
5973         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5974                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5975         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5976                                     SDLoc(N0.getOperand(0)),
5977                                     N0.getOperand(0).getValueType(), ExtLoad);
5978         CombineTo(N, And);
5979         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5980         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5981                         ISD::SIGN_EXTEND);
5982         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5983       }
5984     }
5985   }
5986
5987   if (N0.getOpcode() == ISD::SETCC) {
5988     EVT N0VT = N0.getOperand(0).getValueType();
5989     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5990     // Only do this before legalize for now.
5991     if (VT.isVector() && !LegalOperations &&
5992         TLI.getBooleanContents(N0VT) ==
5993             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5994       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5995       // of the same size as the compared operands. Only optimize sext(setcc())
5996       // if this is the case.
5997       EVT SVT = getSetCCResultType(N0VT);
5998
5999       // We know that the # elements of the results is the same as the
6000       // # elements of the compare (and the # elements of the compare result
6001       // for that matter).  Check to see that they are the same size.  If so,
6002       // we know that the element size of the sext'd result matches the
6003       // element size of the compare operands.
6004       if (VT.getSizeInBits() == SVT.getSizeInBits())
6005         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6006                              N0.getOperand(1),
6007                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6008
6009       // If the desired elements are smaller or larger than the source
6010       // elements we can use a matching integer vector type and then
6011       // truncate/sign extend
6012       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6013       if (SVT == MatchingVectorType) {
6014         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6015                                N0.getOperand(0), N0.getOperand(1),
6016                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6017         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6018       }
6019     }
6020
6021     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6022     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6023     SDLoc DL(N);
6024     SDValue NegOne =
6025       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6026     SDValue SCC =
6027       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6028                        NegOne, DAG.getConstant(0, DL, VT),
6029                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6030     if (SCC.getNode()) return SCC;
6031
6032     if (!VT.isVector()) {
6033       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6034       if (!LegalOperations ||
6035           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6036         SDLoc DL(N);
6037         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6038         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6039                                      N0.getOperand(0), N0.getOperand(1), CC);
6040         return DAG.getSelect(DL, VT, SetCC,
6041                              NegOne, DAG.getConstant(0, DL, VT));
6042       }
6043     }
6044   }
6045
6046   // fold (sext x) -> (zext x) if the sign bit is known zero.
6047   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6048       DAG.SignBitIsZero(N0))
6049     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6050
6051   return SDValue();
6052 }
6053
6054 // isTruncateOf - If N is a truncate of some other value, return true, record
6055 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6056 // This function computes KnownZero to avoid a duplicated call to
6057 // computeKnownBits in the caller.
6058 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6059                          APInt &KnownZero) {
6060   APInt KnownOne;
6061   if (N->getOpcode() == ISD::TRUNCATE) {
6062     Op = N->getOperand(0);
6063     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6064     return true;
6065   }
6066
6067   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6068       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6069     return false;
6070
6071   SDValue Op0 = N->getOperand(0);
6072   SDValue Op1 = N->getOperand(1);
6073   assert(Op0.getValueType() == Op1.getValueType());
6074
6075   if (isNullConstant(Op0))
6076     Op = Op1;
6077   else if (isNullConstant(Op1))
6078     Op = Op0;
6079   else
6080     return false;
6081
6082   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6083
6084   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6085     return false;
6086
6087   return true;
6088 }
6089
6090 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6091   SDValue N0 = N->getOperand(0);
6092   EVT VT = N->getValueType(0);
6093
6094   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6095                                               LegalOperations))
6096     return SDValue(Res, 0);
6097
6098   // fold (zext (zext x)) -> (zext x)
6099   // fold (zext (aext x)) -> (zext x)
6100   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6101     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6102                        N0.getOperand(0));
6103
6104   // fold (zext (truncate x)) -> (zext x) or
6105   //      (zext (truncate x)) -> (truncate x)
6106   // This is valid when the truncated bits of x are already zero.
6107   // FIXME: We should extend this to work for vectors too.
6108   SDValue Op;
6109   APInt KnownZero;
6110   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6111     APInt TruncatedBits =
6112       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6113       APInt(Op.getValueSizeInBits(), 0) :
6114       APInt::getBitsSet(Op.getValueSizeInBits(),
6115                         N0.getValueSizeInBits(),
6116                         std::min(Op.getValueSizeInBits(),
6117                                  VT.getSizeInBits()));
6118     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6119       if (VT.bitsGT(Op.getValueType()))
6120         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6121       if (VT.bitsLT(Op.getValueType()))
6122         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6123
6124       return Op;
6125     }
6126   }
6127
6128   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6129   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6130   if (N0.getOpcode() == ISD::TRUNCATE) {
6131     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6132       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6133       if (NarrowLoad.getNode() != N0.getNode()) {
6134         CombineTo(N0.getNode(), NarrowLoad);
6135         // CombineTo deleted the truncate, if needed, but not what's under it.
6136         AddToWorklist(oye);
6137       }
6138       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6139     }
6140   }
6141
6142   // fold (zext (truncate x)) -> (and x, mask)
6143   if (N0.getOpcode() == ISD::TRUNCATE) {
6144     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6145     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6146     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6147       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6148       if (NarrowLoad.getNode() != N0.getNode()) {
6149         CombineTo(N0.getNode(), NarrowLoad);
6150         // CombineTo deleted the truncate, if needed, but not what's under it.
6151         AddToWorklist(oye);
6152       }
6153       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6154     }
6155
6156     EVT SrcVT = N0.getOperand(0).getValueType();
6157     EVT MinVT = N0.getValueType();
6158
6159     // Try to mask before the extension to avoid having to generate a larger mask,
6160     // possibly over several sub-vectors.
6161     if (SrcVT.bitsLT(VT)) {
6162       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6163                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6164         SDValue Op = N0.getOperand(0);
6165         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6166         AddToWorklist(Op.getNode());
6167         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6168       }
6169     }
6170
6171     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6172       SDValue Op = N0.getOperand(0);
6173       if (SrcVT.bitsLT(VT)) {
6174         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6175         AddToWorklist(Op.getNode());
6176       } else if (SrcVT.bitsGT(VT)) {
6177         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6178         AddToWorklist(Op.getNode());
6179       }
6180       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6181     }
6182   }
6183
6184   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6185   // if either of the casts is not free.
6186   if (N0.getOpcode() == ISD::AND &&
6187       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6188       N0.getOperand(1).getOpcode() == ISD::Constant &&
6189       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6190                            N0.getValueType()) ||
6191        !TLI.isZExtFree(N0.getValueType(), VT))) {
6192     SDValue X = N0.getOperand(0).getOperand(0);
6193     if (X.getValueType().bitsLT(VT)) {
6194       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6195     } else if (X.getValueType().bitsGT(VT)) {
6196       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6197     }
6198     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6199     Mask = Mask.zext(VT.getSizeInBits());
6200     SDLoc DL(N);
6201     return DAG.getNode(ISD::AND, DL, VT,
6202                        X, DAG.getConstant(Mask, DL, VT));
6203   }
6204
6205   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6206   // Only generate vector extloads when 1) they're legal, and 2) they are
6207   // deemed desirable by the target.
6208   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6209       ((!LegalOperations && !VT.isVector() &&
6210         !cast<LoadSDNode>(N0)->isVolatile()) ||
6211        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6212     bool DoXform = true;
6213     SmallVector<SDNode*, 4> SetCCs;
6214     if (!N0.hasOneUse())
6215       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6216     if (VT.isVector())
6217       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6218     if (DoXform) {
6219       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6220       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6221                                        LN0->getChain(),
6222                                        LN0->getBasePtr(), N0.getValueType(),
6223                                        LN0->getMemOperand());
6224       CombineTo(N, ExtLoad);
6225       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6226                                   N0.getValueType(), ExtLoad);
6227       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6228
6229       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6230                       ISD::ZERO_EXTEND);
6231       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6232     }
6233   }
6234
6235   // fold (zext (load x)) to multiple smaller zextloads.
6236   // Only on illegal but splittable vectors.
6237   if (SDValue ExtLoad = CombineExtLoad(N))
6238     return ExtLoad;
6239
6240   // fold (zext (and/or/xor (load x), cst)) ->
6241   //      (and/or/xor (zextload x), (zext cst))
6242   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6243        N0.getOpcode() == ISD::XOR) &&
6244       isa<LoadSDNode>(N0.getOperand(0)) &&
6245       N0.getOperand(1).getOpcode() == ISD::Constant &&
6246       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6247       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6248     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6249     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6250       bool DoXform = true;
6251       SmallVector<SDNode*, 4> SetCCs;
6252       if (!N0.hasOneUse())
6253         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6254                                           SetCCs, TLI);
6255       if (DoXform) {
6256         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6257                                          LN0->getChain(), LN0->getBasePtr(),
6258                                          LN0->getMemoryVT(),
6259                                          LN0->getMemOperand());
6260         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6261         Mask = Mask.zext(VT.getSizeInBits());
6262         SDLoc DL(N);
6263         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6264                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6265         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6266                                     SDLoc(N0.getOperand(0)),
6267                                     N0.getOperand(0).getValueType(), ExtLoad);
6268         CombineTo(N, And);
6269         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6270         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6271                         ISD::ZERO_EXTEND);
6272         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6273       }
6274     }
6275   }
6276
6277   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6278   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6279   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6280       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6281     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6282     EVT MemVT = LN0->getMemoryVT();
6283     if ((!LegalOperations && !LN0->isVolatile()) ||
6284         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6285       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6286                                        LN0->getChain(),
6287                                        LN0->getBasePtr(), MemVT,
6288                                        LN0->getMemOperand());
6289       CombineTo(N, ExtLoad);
6290       CombineTo(N0.getNode(),
6291                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6292                             ExtLoad),
6293                 ExtLoad.getValue(1));
6294       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6295     }
6296   }
6297
6298   if (N0.getOpcode() == ISD::SETCC) {
6299     if (!LegalOperations && VT.isVector() &&
6300         N0.getValueType().getVectorElementType() == MVT::i1) {
6301       EVT N0VT = N0.getOperand(0).getValueType();
6302       if (getSetCCResultType(N0VT) == N0.getValueType())
6303         return SDValue();
6304
6305       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6306       // Only do this before legalize for now.
6307       EVT EltVT = VT.getVectorElementType();
6308       SDLoc DL(N);
6309       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6310                                     DAG.getConstant(1, DL, EltVT));
6311       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6312         // We know that the # elements of the results is the same as the
6313         // # elements of the compare (and the # elements of the compare result
6314         // for that matter).  Check to see that they are the same size.  If so,
6315         // we know that the element size of the sext'd result matches the
6316         // element size of the compare operands.
6317         return DAG.getNode(ISD::AND, DL, VT,
6318                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6319                                          N0.getOperand(1),
6320                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6321                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6322                                        OneOps));
6323
6324       // If the desired elements are smaller or larger than the source
6325       // elements we can use a matching integer vector type and then
6326       // truncate/sign extend
6327       EVT MatchingElementType =
6328         EVT::getIntegerVT(*DAG.getContext(),
6329                           N0VT.getScalarType().getSizeInBits());
6330       EVT MatchingVectorType =
6331         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6332                          N0VT.getVectorNumElements());
6333       SDValue VsetCC =
6334         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6335                       N0.getOperand(1),
6336                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6337       return DAG.getNode(ISD::AND, DL, VT,
6338                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6339                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6340     }
6341
6342     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6343     SDLoc DL(N);
6344     SDValue SCC =
6345       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6346                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6347                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6348     if (SCC.getNode()) return SCC;
6349   }
6350
6351   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6352   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6353       isa<ConstantSDNode>(N0.getOperand(1)) &&
6354       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6355       N0.hasOneUse()) {
6356     SDValue ShAmt = N0.getOperand(1);
6357     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6358     if (N0.getOpcode() == ISD::SHL) {
6359       SDValue InnerZExt = N0.getOperand(0);
6360       // If the original shl may be shifting out bits, do not perform this
6361       // transformation.
6362       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6363         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6364       if (ShAmtVal > KnownZeroBits)
6365         return SDValue();
6366     }
6367
6368     SDLoc DL(N);
6369
6370     // Ensure that the shift amount is wide enough for the shifted value.
6371     if (VT.getSizeInBits() >= 256)
6372       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6373
6374     return DAG.getNode(N0.getOpcode(), DL, VT,
6375                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6376                        ShAmt);
6377   }
6378
6379   return SDValue();
6380 }
6381
6382 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6383   SDValue N0 = N->getOperand(0);
6384   EVT VT = N->getValueType(0);
6385
6386   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6387                                               LegalOperations))
6388     return SDValue(Res, 0);
6389
6390   // fold (aext (aext x)) -> (aext x)
6391   // fold (aext (zext x)) -> (zext x)
6392   // fold (aext (sext x)) -> (sext x)
6393   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6394       N0.getOpcode() == ISD::ZERO_EXTEND ||
6395       N0.getOpcode() == ISD::SIGN_EXTEND)
6396     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6397
6398   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6399   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6400   if (N0.getOpcode() == ISD::TRUNCATE) {
6401     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6402       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6403       if (NarrowLoad.getNode() != N0.getNode()) {
6404         CombineTo(N0.getNode(), NarrowLoad);
6405         // CombineTo deleted the truncate, if needed, but not what's under it.
6406         AddToWorklist(oye);
6407       }
6408       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6409     }
6410   }
6411
6412   // fold (aext (truncate x))
6413   if (N0.getOpcode() == ISD::TRUNCATE) {
6414     SDValue TruncOp = N0.getOperand(0);
6415     if (TruncOp.getValueType() == VT)
6416       return TruncOp; // x iff x size == zext size.
6417     if (TruncOp.getValueType().bitsGT(VT))
6418       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6419     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6420   }
6421
6422   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6423   // if the trunc is not free.
6424   if (N0.getOpcode() == ISD::AND &&
6425       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6426       N0.getOperand(1).getOpcode() == ISD::Constant &&
6427       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6428                           N0.getValueType())) {
6429     SDValue X = N0.getOperand(0).getOperand(0);
6430     if (X.getValueType().bitsLT(VT)) {
6431       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6432     } else if (X.getValueType().bitsGT(VT)) {
6433       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6434     }
6435     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6436     Mask = Mask.zext(VT.getSizeInBits());
6437     SDLoc DL(N);
6438     return DAG.getNode(ISD::AND, DL, VT,
6439                        X, DAG.getConstant(Mask, DL, VT));
6440   }
6441
6442   // fold (aext (load x)) -> (aext (truncate (extload x)))
6443   // None of the supported targets knows how to perform load and any_ext
6444   // on vectors in one instruction.  We only perform this transformation on
6445   // scalars.
6446   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6447       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6448       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6449     bool DoXform = true;
6450     SmallVector<SDNode*, 4> SetCCs;
6451     if (!N0.hasOneUse())
6452       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6453     if (DoXform) {
6454       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6455       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6456                                        LN0->getChain(),
6457                                        LN0->getBasePtr(), N0.getValueType(),
6458                                        LN0->getMemOperand());
6459       CombineTo(N, ExtLoad);
6460       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6461                                   N0.getValueType(), ExtLoad);
6462       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6463       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6464                       ISD::ANY_EXTEND);
6465       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6466     }
6467   }
6468
6469   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6470   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6471   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6472   if (N0.getOpcode() == ISD::LOAD &&
6473       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6474       N0.hasOneUse()) {
6475     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6476     ISD::LoadExtType ExtType = LN0->getExtensionType();
6477     EVT MemVT = LN0->getMemoryVT();
6478     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6479       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6480                                        VT, LN0->getChain(), LN0->getBasePtr(),
6481                                        MemVT, LN0->getMemOperand());
6482       CombineTo(N, ExtLoad);
6483       CombineTo(N0.getNode(),
6484                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6485                             N0.getValueType(), ExtLoad),
6486                 ExtLoad.getValue(1));
6487       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6488     }
6489   }
6490
6491   if (N0.getOpcode() == ISD::SETCC) {
6492     // For vectors:
6493     // aext(setcc) -> vsetcc
6494     // aext(setcc) -> truncate(vsetcc)
6495     // aext(setcc) -> aext(vsetcc)
6496     // Only do this before legalize for now.
6497     if (VT.isVector() && !LegalOperations) {
6498       EVT N0VT = N0.getOperand(0).getValueType();
6499         // We know that the # elements of the results is the same as the
6500         // # elements of the compare (and the # elements of the compare result
6501         // for that matter).  Check to see that they are the same size.  If so,
6502         // we know that the element size of the sext'd result matches the
6503         // element size of the compare operands.
6504       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6505         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6506                              N0.getOperand(1),
6507                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6508       // If the desired elements are smaller or larger than the source
6509       // elements we can use a matching integer vector type and then
6510       // truncate/any extend
6511       else {
6512         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6513         SDValue VsetCC =
6514           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6515                         N0.getOperand(1),
6516                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6517         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6518       }
6519     }
6520
6521     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6522     SDLoc DL(N);
6523     SDValue SCC =
6524       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6525                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6526                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6527     if (SCC.getNode())
6528       return SCC;
6529   }
6530
6531   return SDValue();
6532 }
6533
6534 /// See if the specified operand can be simplified with the knowledge that only
6535 /// the bits specified by Mask are used.  If so, return the simpler operand,
6536 /// otherwise return a null SDValue.
6537 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6538   switch (V.getOpcode()) {
6539   default: break;
6540   case ISD::Constant: {
6541     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6542     assert(CV && "Const value should be ConstSDNode.");
6543     const APInt &CVal = CV->getAPIntValue();
6544     APInt NewVal = CVal & Mask;
6545     if (NewVal != CVal)
6546       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6547     break;
6548   }
6549   case ISD::OR:
6550   case ISD::XOR:
6551     // If the LHS or RHS don't contribute bits to the or, drop them.
6552     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6553       return V.getOperand(1);
6554     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6555       return V.getOperand(0);
6556     break;
6557   case ISD::SRL:
6558     // Only look at single-use SRLs.
6559     if (!V.getNode()->hasOneUse())
6560       break;
6561     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6562       // See if we can recursively simplify the LHS.
6563       unsigned Amt = RHSC->getZExtValue();
6564
6565       // Watch out for shift count overflow though.
6566       if (Amt >= Mask.getBitWidth()) break;
6567       APInt NewMask = Mask << Amt;
6568       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6569         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6570                            SimplifyLHS, V.getOperand(1));
6571     }
6572   }
6573   return SDValue();
6574 }
6575
6576 /// If the result of a wider load is shifted to right of N  bits and then
6577 /// truncated to a narrower type and where N is a multiple of number of bits of
6578 /// the narrower type, transform it to a narrower load from address + N / num of
6579 /// bits of new type. If the result is to be extended, also fold the extension
6580 /// to form a extending load.
6581 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6582   unsigned Opc = N->getOpcode();
6583
6584   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6585   SDValue N0 = N->getOperand(0);
6586   EVT VT = N->getValueType(0);
6587   EVT ExtVT = VT;
6588
6589   // This transformation isn't valid for vector loads.
6590   if (VT.isVector())
6591     return SDValue();
6592
6593   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6594   // extended to VT.
6595   if (Opc == ISD::SIGN_EXTEND_INREG) {
6596     ExtType = ISD::SEXTLOAD;
6597     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6598   } else if (Opc == ISD::SRL) {
6599     // Another special-case: SRL is basically zero-extending a narrower value.
6600     ExtType = ISD::ZEXTLOAD;
6601     N0 = SDValue(N, 0);
6602     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6603     if (!N01) return SDValue();
6604     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6605                               VT.getSizeInBits() - N01->getZExtValue());
6606   }
6607   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6608     return SDValue();
6609
6610   unsigned EVTBits = ExtVT.getSizeInBits();
6611
6612   // Do not generate loads of non-round integer types since these can
6613   // be expensive (and would be wrong if the type is not byte sized).
6614   if (!ExtVT.isRound())
6615     return SDValue();
6616
6617   unsigned ShAmt = 0;
6618   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6619     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6620       ShAmt = N01->getZExtValue();
6621       // Is the shift amount a multiple of size of VT?
6622       if ((ShAmt & (EVTBits-1)) == 0) {
6623         N0 = N0.getOperand(0);
6624         // Is the load width a multiple of size of VT?
6625         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6626           return SDValue();
6627       }
6628
6629       // At this point, we must have a load or else we can't do the transform.
6630       if (!isa<LoadSDNode>(N0)) return SDValue();
6631
6632       // Because a SRL must be assumed to *need* to zero-extend the high bits
6633       // (as opposed to anyext the high bits), we can't combine the zextload
6634       // lowering of SRL and an sextload.
6635       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6636         return SDValue();
6637
6638       // If the shift amount is larger than the input type then we're not
6639       // accessing any of the loaded bytes.  If the load was a zextload/extload
6640       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6641       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6642         return SDValue();
6643     }
6644   }
6645
6646   // If the load is shifted left (and the result isn't shifted back right),
6647   // we can fold the truncate through the shift.
6648   unsigned ShLeftAmt = 0;
6649   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6650       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6651     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6652       ShLeftAmt = N01->getZExtValue();
6653       N0 = N0.getOperand(0);
6654     }
6655   }
6656
6657   // If we haven't found a load, we can't narrow it.  Don't transform one with
6658   // multiple uses, this would require adding a new load.
6659   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6660     return SDValue();
6661
6662   // Don't change the width of a volatile load.
6663   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6664   if (LN0->isVolatile())
6665     return SDValue();
6666
6667   // Verify that we are actually reducing a load width here.
6668   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6669     return SDValue();
6670
6671   // For the transform to be legal, the load must produce only two values
6672   // (the value loaded and the chain).  Don't transform a pre-increment
6673   // load, for example, which produces an extra value.  Otherwise the
6674   // transformation is not equivalent, and the downstream logic to replace
6675   // uses gets things wrong.
6676   if (LN0->getNumValues() > 2)
6677     return SDValue();
6678
6679   // If the load that we're shrinking is an extload and we're not just
6680   // discarding the extension we can't simply shrink the load. Bail.
6681   // TODO: It would be possible to merge the extensions in some cases.
6682   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6683       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6684     return SDValue();
6685
6686   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6687     return SDValue();
6688
6689   EVT PtrType = N0.getOperand(1).getValueType();
6690
6691   if (PtrType == MVT::Untyped || PtrType.isExtended())
6692     // It's not possible to generate a constant of extended or untyped type.
6693     return SDValue();
6694
6695   // For big endian targets, we need to adjust the offset to the pointer to
6696   // load the correct bytes.
6697   if (DAG.getDataLayout().isBigEndian()) {
6698     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6699     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6700     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6701   }
6702
6703   uint64_t PtrOff = ShAmt / 8;
6704   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6705   SDLoc DL(LN0);
6706   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6707                                PtrType, LN0->getBasePtr(),
6708                                DAG.getConstant(PtrOff, DL, PtrType));
6709   AddToWorklist(NewPtr.getNode());
6710
6711   SDValue Load;
6712   if (ExtType == ISD::NON_EXTLOAD)
6713     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6714                         LN0->getPointerInfo().getWithOffset(PtrOff),
6715                         LN0->isVolatile(), LN0->isNonTemporal(),
6716                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6717   else
6718     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6719                           LN0->getPointerInfo().getWithOffset(PtrOff),
6720                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6721                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6722
6723   // Replace the old load's chain with the new load's chain.
6724   WorklistRemover DeadNodes(*this);
6725   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6726
6727   // Shift the result left, if we've swallowed a left shift.
6728   SDValue Result = Load;
6729   if (ShLeftAmt != 0) {
6730     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6731     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6732       ShImmTy = VT;
6733     // If the shift amount is as large as the result size (but, presumably,
6734     // no larger than the source) then the useful bits of the result are
6735     // zero; we can't simply return the shortened shift, because the result
6736     // of that operation is undefined.
6737     SDLoc DL(N0);
6738     if (ShLeftAmt >= VT.getSizeInBits())
6739       Result = DAG.getConstant(0, DL, VT);
6740     else
6741       Result = DAG.getNode(ISD::SHL, DL, VT,
6742                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6743   }
6744
6745   // Return the new loaded value.
6746   return Result;
6747 }
6748
6749 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6750   SDValue N0 = N->getOperand(0);
6751   SDValue N1 = N->getOperand(1);
6752   EVT VT = N->getValueType(0);
6753   EVT EVT = cast<VTSDNode>(N1)->getVT();
6754   unsigned VTBits = VT.getScalarType().getSizeInBits();
6755   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6756
6757   if (N0.isUndef())
6758     return DAG.getUNDEF(VT);
6759
6760   // fold (sext_in_reg c1) -> c1
6761   if (isConstantIntBuildVectorOrConstantInt(N0))
6762     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6763
6764   // If the input is already sign extended, just drop the extension.
6765   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6766     return N0;
6767
6768   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6769   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6770       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6771     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6772                        N0.getOperand(0), N1);
6773
6774   // fold (sext_in_reg (sext x)) -> (sext x)
6775   // fold (sext_in_reg (aext x)) -> (sext x)
6776   // if x is small enough.
6777   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6778     SDValue N00 = N0.getOperand(0);
6779     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6780         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6781       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6782   }
6783
6784   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6785   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6786     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6787
6788   // fold operands of sext_in_reg based on knowledge that the top bits are not
6789   // demanded.
6790   if (SimplifyDemandedBits(SDValue(N, 0)))
6791     return SDValue(N, 0);
6792
6793   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6794   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6795   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6796     return NarrowLoad;
6797
6798   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6799   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6800   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6801   if (N0.getOpcode() == ISD::SRL) {
6802     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6803       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6804         // We can turn this into an SRA iff the input to the SRL is already sign
6805         // extended enough.
6806         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6807         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6808           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6809                              N0.getOperand(0), N0.getOperand(1));
6810       }
6811   }
6812
6813   // fold (sext_inreg (extload x)) -> (sextload x)
6814   if (ISD::isEXTLoad(N0.getNode()) &&
6815       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6816       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6817       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6818        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6819     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6820     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6821                                      LN0->getChain(),
6822                                      LN0->getBasePtr(), EVT,
6823                                      LN0->getMemOperand());
6824     CombineTo(N, ExtLoad);
6825     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6826     AddToWorklist(ExtLoad.getNode());
6827     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6828   }
6829   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6830   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6831       N0.hasOneUse() &&
6832       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6833       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6834        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6835     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6836     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6837                                      LN0->getChain(),
6838                                      LN0->getBasePtr(), EVT,
6839                                      LN0->getMemOperand());
6840     CombineTo(N, ExtLoad);
6841     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6842     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6843   }
6844
6845   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6846   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6847     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6848                                        N0.getOperand(1), false);
6849     if (BSwap.getNode())
6850       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6851                          BSwap, N1);
6852   }
6853
6854   return SDValue();
6855 }
6856
6857 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6858   SDValue N0 = N->getOperand(0);
6859   EVT VT = N->getValueType(0);
6860
6861   if (N0.getOpcode() == ISD::UNDEF)
6862     return DAG.getUNDEF(VT);
6863
6864   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6865                                               LegalOperations))
6866     return SDValue(Res, 0);
6867
6868   return SDValue();
6869 }
6870
6871 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6872   SDValue N0 = N->getOperand(0);
6873   EVT VT = N->getValueType(0);
6874   bool isLE = DAG.getDataLayout().isLittleEndian();
6875
6876   // noop truncate
6877   if (N0.getValueType() == N->getValueType(0))
6878     return N0;
6879   // fold (truncate c1) -> c1
6880   if (isConstantIntBuildVectorOrConstantInt(N0))
6881     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6882   // fold (truncate (truncate x)) -> (truncate x)
6883   if (N0.getOpcode() == ISD::TRUNCATE)
6884     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6885   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6886   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6887       N0.getOpcode() == ISD::SIGN_EXTEND ||
6888       N0.getOpcode() == ISD::ANY_EXTEND) {
6889     if (N0.getOperand(0).getValueType().bitsLT(VT))
6890       // if the source is smaller than the dest, we still need an extend
6891       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6892                          N0.getOperand(0));
6893     if (N0.getOperand(0).getValueType().bitsGT(VT))
6894       // if the source is larger than the dest, than we just need the truncate
6895       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6896     // if the source and dest are the same type, we can drop both the extend
6897     // and the truncate.
6898     return N0.getOperand(0);
6899   }
6900
6901   // Fold extract-and-trunc into a narrow extract. For example:
6902   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6903   //   i32 y = TRUNCATE(i64 x)
6904   //        -- becomes --
6905   //   v16i8 b = BITCAST (v2i64 val)
6906   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6907   //
6908   // Note: We only run this optimization after type legalization (which often
6909   // creates this pattern) and before operation legalization after which
6910   // we need to be more careful about the vector instructions that we generate.
6911   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6912       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6913
6914     EVT VecTy = N0.getOperand(0).getValueType();
6915     EVT ExTy = N0.getValueType();
6916     EVT TrTy = N->getValueType(0);
6917
6918     unsigned NumElem = VecTy.getVectorNumElements();
6919     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6920
6921     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6922     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6923
6924     SDValue EltNo = N0->getOperand(1);
6925     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6926       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6927       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6928       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6929
6930       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6931                               NVT, N0.getOperand(0));
6932
6933       SDLoc DL(N);
6934       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6935                          DL, TrTy, V,
6936                          DAG.getConstant(Index, DL, IndexTy));
6937     }
6938   }
6939
6940   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6941   if (N0.getOpcode() == ISD::SELECT) {
6942     EVT SrcVT = N0.getValueType();
6943     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6944         TLI.isTruncateFree(SrcVT, VT)) {
6945       SDLoc SL(N0);
6946       SDValue Cond = N0.getOperand(0);
6947       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6948       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6949       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6950     }
6951   }
6952
6953   // Fold a series of buildvector, bitcast, and truncate if possible.
6954   // For example fold
6955   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6956   //   (2xi32 (buildvector x, y)).
6957   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6958       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6959       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6960       N0.getOperand(0).hasOneUse()) {
6961
6962     SDValue BuildVect = N0.getOperand(0);
6963     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6964     EVT TruncVecEltTy = VT.getVectorElementType();
6965
6966     // Check that the element types match.
6967     if (BuildVectEltTy == TruncVecEltTy) {
6968       // Now we only need to compute the offset of the truncated elements.
6969       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6970       unsigned TruncVecNumElts = VT.getVectorNumElements();
6971       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6972
6973       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6974              "Invalid number of elements");
6975
6976       SmallVector<SDValue, 8> Opnds;
6977       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6978         Opnds.push_back(BuildVect.getOperand(i));
6979
6980       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6981     }
6982   }
6983
6984   // See if we can simplify the input to this truncate through knowledge that
6985   // only the low bits are being used.
6986   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6987   // Currently we only perform this optimization on scalars because vectors
6988   // may have different active low bits.
6989   if (!VT.isVector()) {
6990     SDValue Shorter =
6991       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6992                                                VT.getSizeInBits()));
6993     if (Shorter.getNode())
6994       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6995   }
6996   // fold (truncate (load x)) -> (smaller load x)
6997   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6998   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6999     if (SDValue Reduced = ReduceLoadWidth(N))
7000       return Reduced;
7001
7002     // Handle the case where the load remains an extending load even
7003     // after truncation.
7004     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7005       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7006       if (!LN0->isVolatile() &&
7007           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7008         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7009                                          VT, LN0->getChain(), LN0->getBasePtr(),
7010                                          LN0->getMemoryVT(),
7011                                          LN0->getMemOperand());
7012         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7013         return NewLoad;
7014       }
7015     }
7016   }
7017   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7018   // where ... are all 'undef'.
7019   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7020     SmallVector<EVT, 8> VTs;
7021     SDValue V;
7022     unsigned Idx = 0;
7023     unsigned NumDefs = 0;
7024
7025     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7026       SDValue X = N0.getOperand(i);
7027       if (X.getOpcode() != ISD::UNDEF) {
7028         V = X;
7029         Idx = i;
7030         NumDefs++;
7031       }
7032       // Stop if more than one members are non-undef.
7033       if (NumDefs > 1)
7034         break;
7035       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7036                                      VT.getVectorElementType(),
7037                                      X.getValueType().getVectorNumElements()));
7038     }
7039
7040     if (NumDefs == 0)
7041       return DAG.getUNDEF(VT);
7042
7043     if (NumDefs == 1) {
7044       assert(V.getNode() && "The single defined operand is empty!");
7045       SmallVector<SDValue, 8> Opnds;
7046       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7047         if (i != Idx) {
7048           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7049           continue;
7050         }
7051         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7052         AddToWorklist(NV.getNode());
7053         Opnds.push_back(NV);
7054       }
7055       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7056     }
7057   }
7058
7059   // Simplify the operands using demanded-bits information.
7060   if (!VT.isVector() &&
7061       SimplifyDemandedBits(SDValue(N, 0)))
7062     return SDValue(N, 0);
7063
7064   return SDValue();
7065 }
7066
7067 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7068   SDValue Elt = N->getOperand(i);
7069   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7070     return Elt.getNode();
7071   return Elt.getOperand(Elt.getResNo()).getNode();
7072 }
7073
7074 /// build_pair (load, load) -> load
7075 /// if load locations are consecutive.
7076 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7077   assert(N->getOpcode() == ISD::BUILD_PAIR);
7078
7079   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7080   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7081   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7082       LD1->getAddressSpace() != LD2->getAddressSpace())
7083     return SDValue();
7084   EVT LD1VT = LD1->getValueType(0);
7085
7086   if (ISD::isNON_EXTLoad(LD2) &&
7087       LD2->hasOneUse() &&
7088       // If both are volatile this would reduce the number of volatile loads.
7089       // If one is volatile it might be ok, but play conservative and bail out.
7090       !LD1->isVolatile() &&
7091       !LD2->isVolatile() &&
7092       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7093     unsigned Align = LD1->getAlignment();
7094     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7095         VT.getTypeForEVT(*DAG.getContext()));
7096
7097     if (NewAlign <= Align &&
7098         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7099       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7100                          LD1->getBasePtr(), LD1->getPointerInfo(),
7101                          false, false, false, Align);
7102   }
7103
7104   return SDValue();
7105 }
7106
7107 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7108   SDValue N0 = N->getOperand(0);
7109   EVT VT = N->getValueType(0);
7110
7111   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7112   // Only do this before legalize, since afterward the target may be depending
7113   // on the bitconvert.
7114   // First check to see if this is all constant.
7115   if (!LegalTypes &&
7116       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7117       VT.isVector()) {
7118     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7119
7120     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7121     assert(!DestEltVT.isVector() &&
7122            "Element type of vector ValueType must not be vector!");
7123     if (isSimple)
7124       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7125   }
7126
7127   // If the input is a constant, let getNode fold it.
7128   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7129     // If we can't allow illegal operations, we need to check that this is just
7130     // a fp -> int or int -> conversion and that the resulting operation will
7131     // be legal.
7132     if (!LegalOperations ||
7133         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7134          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7135         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7136          TLI.isOperationLegal(ISD::Constant, VT)))
7137       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7138   }
7139
7140   // (conv (conv x, t1), t2) -> (conv x, t2)
7141   if (N0.getOpcode() == ISD::BITCAST)
7142     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7143                        N0.getOperand(0));
7144
7145   // fold (conv (load x)) -> (load (conv*)x)
7146   // If the resultant load doesn't need a higher alignment than the original!
7147   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7148       // Do not change the width of a volatile load.
7149       !cast<LoadSDNode>(N0)->isVolatile() &&
7150       // Do not remove the cast if the types differ in endian layout.
7151       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7152           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7153       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7154       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7155     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7156     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7157         VT.getTypeForEVT(*DAG.getContext()));
7158     unsigned OrigAlign = LN0->getAlignment();
7159
7160     if (Align <= OrigAlign) {
7161       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7162                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7163                                  LN0->isVolatile(), LN0->isNonTemporal(),
7164                                  LN0->isInvariant(), OrigAlign,
7165                                  LN0->getAAInfo());
7166       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7167       return Load;
7168     }
7169   }
7170
7171   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7172   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7173   // This often reduces constant pool loads.
7174   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7175        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7176       N0.getNode()->hasOneUse() && VT.isInteger() &&
7177       !VT.isVector() && !N0.getValueType().isVector()) {
7178     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7179                                   N0.getOperand(0));
7180     AddToWorklist(NewConv.getNode());
7181
7182     SDLoc DL(N);
7183     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7184     if (N0.getOpcode() == ISD::FNEG)
7185       return DAG.getNode(ISD::XOR, DL, VT,
7186                          NewConv, DAG.getConstant(SignBit, DL, VT));
7187     assert(N0.getOpcode() == ISD::FABS);
7188     return DAG.getNode(ISD::AND, DL, VT,
7189                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7190   }
7191
7192   // fold (bitconvert (fcopysign cst, x)) ->
7193   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7194   // Note that we don't handle (copysign x, cst) because this can always be
7195   // folded to an fneg or fabs.
7196   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7197       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7198       VT.isInteger() && !VT.isVector()) {
7199     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7200     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7201     if (isTypeLegal(IntXVT)) {
7202       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7203                               IntXVT, N0.getOperand(1));
7204       AddToWorklist(X.getNode());
7205
7206       // If X has a different width than the result/lhs, sext it or truncate it.
7207       unsigned VTWidth = VT.getSizeInBits();
7208       if (OrigXWidth < VTWidth) {
7209         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7210         AddToWorklist(X.getNode());
7211       } else if (OrigXWidth > VTWidth) {
7212         // To get the sign bit in the right place, we have to shift it right
7213         // before truncating.
7214         SDLoc DL(X);
7215         X = DAG.getNode(ISD::SRL, DL,
7216                         X.getValueType(), X,
7217                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7218                                         X.getValueType()));
7219         AddToWorklist(X.getNode());
7220         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7221         AddToWorklist(X.getNode());
7222       }
7223
7224       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7225       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7226                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7227       AddToWorklist(X.getNode());
7228
7229       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7230                                 VT, N0.getOperand(0));
7231       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7232                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7233       AddToWorklist(Cst.getNode());
7234
7235       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7236     }
7237   }
7238
7239   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7240   if (N0.getOpcode() == ISD::BUILD_PAIR)
7241     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7242       return CombineLD;
7243
7244   // Remove double bitcasts from shuffles - this is often a legacy of
7245   // XformToShuffleWithZero being used to combine bitmaskings (of
7246   // float vectors bitcast to integer vectors) into shuffles.
7247   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7248   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7249       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7250       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7251       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7252     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7253
7254     // If operands are a bitcast, peek through if it casts the original VT.
7255     // If operands are a constant, just bitcast back to original VT.
7256     auto PeekThroughBitcast = [&](SDValue Op) {
7257       if (Op.getOpcode() == ISD::BITCAST &&
7258           Op.getOperand(0).getValueType() == VT)
7259         return SDValue(Op.getOperand(0));
7260       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7261           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7262         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7263       return SDValue();
7264     };
7265
7266     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7267     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7268     if (!(SV0 && SV1))
7269       return SDValue();
7270
7271     int MaskScale =
7272         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7273     SmallVector<int, 8> NewMask;
7274     for (int M : SVN->getMask())
7275       for (int i = 0; i != MaskScale; ++i)
7276         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7277
7278     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7279     if (!LegalMask) {
7280       std::swap(SV0, SV1);
7281       ShuffleVectorSDNode::commuteMask(NewMask);
7282       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7283     }
7284
7285     if (LegalMask)
7286       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7287   }
7288
7289   return SDValue();
7290 }
7291
7292 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7293   EVT VT = N->getValueType(0);
7294   return CombineConsecutiveLoads(N, VT);
7295 }
7296
7297 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7298 /// operands. DstEltVT indicates the destination element value type.
7299 SDValue DAGCombiner::
7300 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7301   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7302
7303   // If this is already the right type, we're done.
7304   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7305
7306   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7307   unsigned DstBitSize = DstEltVT.getSizeInBits();
7308
7309   // If this is a conversion of N elements of one type to N elements of another
7310   // type, convert each element.  This handles FP<->INT cases.
7311   if (SrcBitSize == DstBitSize) {
7312     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7313                               BV->getValueType(0).getVectorNumElements());
7314
7315     // Due to the FP element handling below calling this routine recursively,
7316     // we can end up with a scalar-to-vector node here.
7317     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7318       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7319                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7320                                      DstEltVT, BV->getOperand(0)));
7321
7322     SmallVector<SDValue, 8> Ops;
7323     for (SDValue Op : BV->op_values()) {
7324       // If the vector element type is not legal, the BUILD_VECTOR operands
7325       // are promoted and implicitly truncated.  Make that explicit here.
7326       if (Op.getValueType() != SrcEltVT)
7327         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7328       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7329                                 DstEltVT, Op));
7330       AddToWorklist(Ops.back().getNode());
7331     }
7332     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7333   }
7334
7335   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7336   // handle annoying details of growing/shrinking FP values, we convert them to
7337   // int first.
7338   if (SrcEltVT.isFloatingPoint()) {
7339     // Convert the input float vector to a int vector where the elements are the
7340     // same sizes.
7341     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7342     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7343     SrcEltVT = IntVT;
7344   }
7345
7346   // Now we know the input is an integer vector.  If the output is a FP type,
7347   // convert to integer first, then to FP of the right size.
7348   if (DstEltVT.isFloatingPoint()) {
7349     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7350     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7351
7352     // Next, convert to FP elements of the same size.
7353     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7354   }
7355
7356   SDLoc DL(BV);
7357
7358   // Okay, we know the src/dst types are both integers of differing types.
7359   // Handling growing first.
7360   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7361   if (SrcBitSize < DstBitSize) {
7362     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7363
7364     SmallVector<SDValue, 8> Ops;
7365     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7366          i += NumInputsPerOutput) {
7367       bool isLE = DAG.getDataLayout().isLittleEndian();
7368       APInt NewBits = APInt(DstBitSize, 0);
7369       bool EltIsUndef = true;
7370       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7371         // Shift the previously computed bits over.
7372         NewBits <<= SrcBitSize;
7373         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7374         if (Op.getOpcode() == ISD::UNDEF) continue;
7375         EltIsUndef = false;
7376
7377         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7378                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7379       }
7380
7381       if (EltIsUndef)
7382         Ops.push_back(DAG.getUNDEF(DstEltVT));
7383       else
7384         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7385     }
7386
7387     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7388     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7389   }
7390
7391   // Finally, this must be the case where we are shrinking elements: each input
7392   // turns into multiple outputs.
7393   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7394   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7395                             NumOutputsPerInput*BV->getNumOperands());
7396   SmallVector<SDValue, 8> Ops;
7397
7398   for (const SDValue &Op : BV->op_values()) {
7399     if (Op.getOpcode() == ISD::UNDEF) {
7400       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7401       continue;
7402     }
7403
7404     APInt OpVal = cast<ConstantSDNode>(Op)->
7405                   getAPIntValue().zextOrTrunc(SrcBitSize);
7406
7407     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7408       APInt ThisVal = OpVal.trunc(DstBitSize);
7409       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7410       OpVal = OpVal.lshr(DstBitSize);
7411     }
7412
7413     // For big endian targets, swap the order of the pieces of each element.
7414     if (DAG.getDataLayout().isBigEndian())
7415       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7416   }
7417
7418   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7419 }
7420
7421 /// Try to perform FMA combining on a given FADD node.
7422 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7423   SDValue N0 = N->getOperand(0);
7424   SDValue N1 = N->getOperand(1);
7425   EVT VT = N->getValueType(0);
7426   SDLoc SL(N);
7427
7428   const TargetOptions &Options = DAG.getTarget().Options;
7429   bool AllowFusion =
7430       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7431
7432   // Floating-point multiply-add with intermediate rounding.
7433   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7434
7435   // Floating-point multiply-add without intermediate rounding.
7436   bool HasFMA =
7437       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7438       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7439
7440   // No valid opcode, do not combine.
7441   if (!HasFMAD && !HasFMA)
7442     return SDValue();
7443
7444   // Always prefer FMAD to FMA for precision.
7445   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7446   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7447   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7448
7449   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7450   // prefer to fold the multiply with fewer uses.
7451   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7452       N1.getOpcode() == ISD::FMUL) {
7453     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7454       std::swap(N0, N1);
7455   }
7456
7457   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7458   if (N0.getOpcode() == ISD::FMUL &&
7459       (Aggressive || N0->hasOneUse())) {
7460     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7461                        N0.getOperand(0), N0.getOperand(1), N1);
7462   }
7463
7464   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7465   // Note: Commutes FADD operands.
7466   if (N1.getOpcode() == ISD::FMUL &&
7467       (Aggressive || N1->hasOneUse())) {
7468     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7469                        N1.getOperand(0), N1.getOperand(1), N0);
7470   }
7471
7472   // Look through FP_EXTEND nodes to do more combining.
7473   if (AllowFusion && LookThroughFPExt) {
7474     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7475     if (N0.getOpcode() == ISD::FP_EXTEND) {
7476       SDValue N00 = N0.getOperand(0);
7477       if (N00.getOpcode() == ISD::FMUL)
7478         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7479                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7480                                        N00.getOperand(0)),
7481                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7482                                        N00.getOperand(1)), N1);
7483     }
7484
7485     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7486     // Note: Commutes FADD operands.
7487     if (N1.getOpcode() == ISD::FP_EXTEND) {
7488       SDValue N10 = N1.getOperand(0);
7489       if (N10.getOpcode() == ISD::FMUL)
7490         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7491                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7492                                        N10.getOperand(0)),
7493                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7494                                        N10.getOperand(1)), N0);
7495     }
7496   }
7497
7498   // More folding opportunities when target permits.
7499   if ((AllowFusion || HasFMAD)  && Aggressive) {
7500     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7501     if (N0.getOpcode() == PreferredFusedOpcode &&
7502         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7503       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7504                          N0.getOperand(0), N0.getOperand(1),
7505                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7506                                      N0.getOperand(2).getOperand(0),
7507                                      N0.getOperand(2).getOperand(1),
7508                                      N1));
7509     }
7510
7511     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7512     if (N1->getOpcode() == PreferredFusedOpcode &&
7513         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7514       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7515                          N1.getOperand(0), N1.getOperand(1),
7516                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7517                                      N1.getOperand(2).getOperand(0),
7518                                      N1.getOperand(2).getOperand(1),
7519                                      N0));
7520     }
7521
7522     if (AllowFusion && LookThroughFPExt) {
7523       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7524       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7525       auto FoldFAddFMAFPExtFMul = [&] (
7526           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7527         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7528                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7529                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7530                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7531                                        Z));
7532       };
7533       if (N0.getOpcode() == PreferredFusedOpcode) {
7534         SDValue N02 = N0.getOperand(2);
7535         if (N02.getOpcode() == ISD::FP_EXTEND) {
7536           SDValue N020 = N02.getOperand(0);
7537           if (N020.getOpcode() == ISD::FMUL)
7538             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7539                                         N020.getOperand(0), N020.getOperand(1),
7540                                         N1);
7541         }
7542       }
7543
7544       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7545       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7546       // FIXME: This turns two single-precision and one double-precision
7547       // operation into two double-precision operations, which might not be
7548       // interesting for all targets, especially GPUs.
7549       auto FoldFAddFPExtFMAFMul = [&] (
7550           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7551         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7552                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7553                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7554                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7555                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7556                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7557                                        Z));
7558       };
7559       if (N0.getOpcode() == ISD::FP_EXTEND) {
7560         SDValue N00 = N0.getOperand(0);
7561         if (N00.getOpcode() == PreferredFusedOpcode) {
7562           SDValue N002 = N00.getOperand(2);
7563           if (N002.getOpcode() == ISD::FMUL)
7564             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7565                                         N002.getOperand(0), N002.getOperand(1),
7566                                         N1);
7567         }
7568       }
7569
7570       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7571       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7572       if (N1.getOpcode() == PreferredFusedOpcode) {
7573         SDValue N12 = N1.getOperand(2);
7574         if (N12.getOpcode() == ISD::FP_EXTEND) {
7575           SDValue N120 = N12.getOperand(0);
7576           if (N120.getOpcode() == ISD::FMUL)
7577             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7578                                         N120.getOperand(0), N120.getOperand(1),
7579                                         N0);
7580         }
7581       }
7582
7583       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7584       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7585       // FIXME: This turns two single-precision and one double-precision
7586       // operation into two double-precision operations, which might not be
7587       // interesting for all targets, especially GPUs.
7588       if (N1.getOpcode() == ISD::FP_EXTEND) {
7589         SDValue N10 = N1.getOperand(0);
7590         if (N10.getOpcode() == PreferredFusedOpcode) {
7591           SDValue N102 = N10.getOperand(2);
7592           if (N102.getOpcode() == ISD::FMUL)
7593             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7594                                         N102.getOperand(0), N102.getOperand(1),
7595                                         N0);
7596         }
7597       }
7598     }
7599   }
7600
7601   return SDValue();
7602 }
7603
7604 /// Try to perform FMA combining on a given FSUB node.
7605 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7606   SDValue N0 = N->getOperand(0);
7607   SDValue N1 = N->getOperand(1);
7608   EVT VT = N->getValueType(0);
7609   SDLoc SL(N);
7610
7611   const TargetOptions &Options = DAG.getTarget().Options;
7612   bool AllowFusion =
7613       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7614
7615   // Floating-point multiply-add with intermediate rounding.
7616   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7617
7618   // Floating-point multiply-add without intermediate rounding.
7619   bool HasFMA =
7620       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7621       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7622
7623   // No valid opcode, do not combine.
7624   if (!HasFMAD && !HasFMA)
7625     return SDValue();
7626
7627   // Always prefer FMAD to FMA for precision.
7628   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7629   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7630   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7631
7632   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7633   if (N0.getOpcode() == ISD::FMUL &&
7634       (Aggressive || N0->hasOneUse())) {
7635     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7636                        N0.getOperand(0), N0.getOperand(1),
7637                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7638   }
7639
7640   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7641   // Note: Commutes FSUB operands.
7642   if (N1.getOpcode() == ISD::FMUL &&
7643       (Aggressive || N1->hasOneUse()))
7644     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7645                        DAG.getNode(ISD::FNEG, SL, VT,
7646                                    N1.getOperand(0)),
7647                        N1.getOperand(1), N0);
7648
7649   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7650   if (N0.getOpcode() == ISD::FNEG &&
7651       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7652       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7653     SDValue N00 = N0.getOperand(0).getOperand(0);
7654     SDValue N01 = N0.getOperand(0).getOperand(1);
7655     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7656                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7657                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7658   }
7659
7660   // Look through FP_EXTEND nodes to do more combining.
7661   if (AllowFusion && LookThroughFPExt) {
7662     // fold (fsub (fpext (fmul x, y)), z)
7663     //   -> (fma (fpext x), (fpext y), (fneg z))
7664     if (N0.getOpcode() == ISD::FP_EXTEND) {
7665       SDValue N00 = N0.getOperand(0);
7666       if (N00.getOpcode() == ISD::FMUL)
7667         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7668                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7669                                        N00.getOperand(0)),
7670                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7671                                        N00.getOperand(1)),
7672                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7673     }
7674
7675     // fold (fsub x, (fpext (fmul y, z)))
7676     //   -> (fma (fneg (fpext y)), (fpext z), x)
7677     // Note: Commutes FSUB operands.
7678     if (N1.getOpcode() == ISD::FP_EXTEND) {
7679       SDValue N10 = N1.getOperand(0);
7680       if (N10.getOpcode() == ISD::FMUL)
7681         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7682                            DAG.getNode(ISD::FNEG, SL, VT,
7683                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7684                                                    N10.getOperand(0))),
7685                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7686                                        N10.getOperand(1)),
7687                            N0);
7688     }
7689
7690     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7691     //   -> (fneg (fma (fpext x), (fpext y), z))
7692     // Note: This could be removed with appropriate canonicalization of the
7693     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7694     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7695     // from implementing the canonicalization in visitFSUB.
7696     if (N0.getOpcode() == ISD::FP_EXTEND) {
7697       SDValue N00 = N0.getOperand(0);
7698       if (N00.getOpcode() == ISD::FNEG) {
7699         SDValue N000 = N00.getOperand(0);
7700         if (N000.getOpcode() == ISD::FMUL) {
7701           return DAG.getNode(ISD::FNEG, SL, VT,
7702                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7703                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7704                                                      N000.getOperand(0)),
7705                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7706                                                      N000.getOperand(1)),
7707                                          N1));
7708         }
7709       }
7710     }
7711
7712     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7713     //   -> (fneg (fma (fpext x)), (fpext y), z)
7714     // Note: This could be removed with appropriate canonicalization of the
7715     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7716     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7717     // from implementing the canonicalization in visitFSUB.
7718     if (N0.getOpcode() == ISD::FNEG) {
7719       SDValue N00 = N0.getOperand(0);
7720       if (N00.getOpcode() == ISD::FP_EXTEND) {
7721         SDValue N000 = N00.getOperand(0);
7722         if (N000.getOpcode() == ISD::FMUL) {
7723           return DAG.getNode(ISD::FNEG, SL, VT,
7724                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7725                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7726                                                      N000.getOperand(0)),
7727                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7728                                                      N000.getOperand(1)),
7729                                          N1));
7730         }
7731       }
7732     }
7733
7734   }
7735
7736   // More folding opportunities when target permits.
7737   if ((AllowFusion || HasFMAD) && Aggressive) {
7738     // fold (fsub (fma x, y, (fmul u, v)), z)
7739     //   -> (fma x, y (fma u, v, (fneg z)))
7740     if (N0.getOpcode() == PreferredFusedOpcode &&
7741         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7742       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7743                          N0.getOperand(0), N0.getOperand(1),
7744                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7745                                      N0.getOperand(2).getOperand(0),
7746                                      N0.getOperand(2).getOperand(1),
7747                                      DAG.getNode(ISD::FNEG, SL, VT,
7748                                                  N1)));
7749     }
7750
7751     // fold (fsub x, (fma y, z, (fmul u, v)))
7752     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7753     if (N1.getOpcode() == PreferredFusedOpcode &&
7754         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7755       SDValue N20 = N1.getOperand(2).getOperand(0);
7756       SDValue N21 = N1.getOperand(2).getOperand(1);
7757       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7758                          DAG.getNode(ISD::FNEG, SL, VT,
7759                                      N1.getOperand(0)),
7760                          N1.getOperand(1),
7761                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7762                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7763
7764                                      N21, N0));
7765     }
7766
7767     if (AllowFusion && LookThroughFPExt) {
7768       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7769       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7770       if (N0.getOpcode() == PreferredFusedOpcode) {
7771         SDValue N02 = N0.getOperand(2);
7772         if (N02.getOpcode() == ISD::FP_EXTEND) {
7773           SDValue N020 = N02.getOperand(0);
7774           if (N020.getOpcode() == ISD::FMUL)
7775             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7776                                N0.getOperand(0), N0.getOperand(1),
7777                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7778                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779                                                        N020.getOperand(0)),
7780                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7781                                                        N020.getOperand(1)),
7782                                            DAG.getNode(ISD::FNEG, SL, VT,
7783                                                        N1)));
7784         }
7785       }
7786
7787       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7788       //   -> (fma (fpext x), (fpext y),
7789       //           (fma (fpext u), (fpext v), (fneg z)))
7790       // FIXME: This turns two single-precision and one double-precision
7791       // operation into two double-precision operations, which might not be
7792       // interesting for all targets, especially GPUs.
7793       if (N0.getOpcode() == ISD::FP_EXTEND) {
7794         SDValue N00 = N0.getOperand(0);
7795         if (N00.getOpcode() == PreferredFusedOpcode) {
7796           SDValue N002 = N00.getOperand(2);
7797           if (N002.getOpcode() == ISD::FMUL)
7798             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7799                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7800                                            N00.getOperand(0)),
7801                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7802                                            N00.getOperand(1)),
7803                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7804                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7805                                                        N002.getOperand(0)),
7806                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7807                                                        N002.getOperand(1)),
7808                                            DAG.getNode(ISD::FNEG, SL, VT,
7809                                                        N1)));
7810         }
7811       }
7812
7813       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7814       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7815       if (N1.getOpcode() == PreferredFusedOpcode &&
7816         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7817         SDValue N120 = N1.getOperand(2).getOperand(0);
7818         if (N120.getOpcode() == ISD::FMUL) {
7819           SDValue N1200 = N120.getOperand(0);
7820           SDValue N1201 = N120.getOperand(1);
7821           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7822                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7823                              N1.getOperand(1),
7824                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7825                                          DAG.getNode(ISD::FNEG, SL, VT,
7826                                              DAG.getNode(ISD::FP_EXTEND, SL,
7827                                                          VT, N1200)),
7828                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7829                                                      N1201),
7830                                          N0));
7831         }
7832       }
7833
7834       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7835       //   -> (fma (fneg (fpext y)), (fpext z),
7836       //           (fma (fneg (fpext u)), (fpext v), x))
7837       // FIXME: This turns two single-precision and one double-precision
7838       // operation into two double-precision operations, which might not be
7839       // interesting for all targets, especially GPUs.
7840       if (N1.getOpcode() == ISD::FP_EXTEND &&
7841         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7842         SDValue N100 = N1.getOperand(0).getOperand(0);
7843         SDValue N101 = N1.getOperand(0).getOperand(1);
7844         SDValue N102 = N1.getOperand(0).getOperand(2);
7845         if (N102.getOpcode() == ISD::FMUL) {
7846           SDValue N1020 = N102.getOperand(0);
7847           SDValue N1021 = N102.getOperand(1);
7848           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7849                              DAG.getNode(ISD::FNEG, SL, VT,
7850                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7851                                                      N100)),
7852                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7853                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7854                                          DAG.getNode(ISD::FNEG, SL, VT,
7855                                              DAG.getNode(ISD::FP_EXTEND, SL,
7856                                                          VT, N1020)),
7857                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7858                                                      N1021),
7859                                          N0));
7860         }
7861       }
7862     }
7863   }
7864
7865   return SDValue();
7866 }
7867
7868 /// Try to perform FMA combining on a given FMUL node.
7869 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7870   SDValue N0 = N->getOperand(0);
7871   SDValue N1 = N->getOperand(1);
7872   EVT VT = N->getValueType(0);
7873   SDLoc SL(N);
7874
7875   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7876
7877   const TargetOptions &Options = DAG.getTarget().Options;
7878   bool AllowFusion =
7879       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7880
7881   // Floating-point multiply-add with intermediate rounding.
7882   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7883
7884   // Floating-point multiply-add without intermediate rounding.
7885   bool HasFMA =
7886       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7887       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7888
7889   // No valid opcode, do not combine.
7890   if (!HasFMAD && !HasFMA)
7891     return SDValue();
7892
7893   // Always prefer FMAD to FMA for precision.
7894   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7895   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7896
7897   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7898   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7899   auto FuseFADD = [&](SDValue X, SDValue Y) {
7900     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7901       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7902       if (XC1 && XC1->isExactlyValue(+1.0))
7903         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7904       if (XC1 && XC1->isExactlyValue(-1.0))
7905         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7906                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7907     }
7908     return SDValue();
7909   };
7910
7911   if (SDValue FMA = FuseFADD(N0, N1))
7912     return FMA;
7913   if (SDValue FMA = FuseFADD(N1, N0))
7914     return FMA;
7915
7916   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
7917   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
7918   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
7919   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
7920   auto FuseFSUB = [&](SDValue X, SDValue Y) {
7921     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
7922       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
7923       if (XC0 && XC0->isExactlyValue(+1.0))
7924         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7925                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7926                            Y);
7927       if (XC0 && XC0->isExactlyValue(-1.0))
7928         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7929                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7930                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7931
7932       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7933       if (XC1 && XC1->isExactlyValue(+1.0))
7934         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7935                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7936       if (XC1 && XC1->isExactlyValue(-1.0))
7937         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7938     }
7939     return SDValue();
7940   };
7941
7942   if (SDValue FMA = FuseFSUB(N0, N1))
7943     return FMA;
7944   if (SDValue FMA = FuseFSUB(N1, N0))
7945     return FMA;
7946
7947   return SDValue();
7948 }
7949
7950 SDValue DAGCombiner::visitFADD(SDNode *N) {
7951   SDValue N0 = N->getOperand(0);
7952   SDValue N1 = N->getOperand(1);
7953   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
7954   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
7955   EVT VT = N->getValueType(0);
7956   SDLoc DL(N);
7957   const TargetOptions &Options = DAG.getTarget().Options;
7958   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
7959
7960   // fold vector ops
7961   if (VT.isVector())
7962     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7963       return FoldedVOp;
7964
7965   // fold (fadd c1, c2) -> c1 + c2
7966   if (N0CFP && N1CFP)
7967     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
7968
7969   // canonicalize constant to RHS
7970   if (N0CFP && !N1CFP)
7971     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
7972
7973   // fold (fadd A, (fneg B)) -> (fsub A, B)
7974   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7975       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7976     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7977                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
7978
7979   // fold (fadd (fneg A), B) -> (fsub B, A)
7980   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7981       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7982     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7983                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
7984
7985   // If 'unsafe math' is enabled, fold lots of things.
7986   if (Options.UnsafeFPMath) {
7987     // No FP constant should be created after legalization as Instruction
7988     // Selection pass has a hard time dealing with FP constants.
7989     bool AllowNewConst = (Level < AfterLegalizeDAG);
7990
7991     // fold (fadd A, 0) -> A
7992     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
7993       if (N1C->isZero())
7994         return N0;
7995
7996     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7997     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7998         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
7999       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8000                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8001                                      Flags),
8002                          Flags);
8003
8004     // If allowed, fold (fadd (fneg x), x) -> 0.0
8005     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8006       return DAG.getConstantFP(0.0, DL, VT);
8007
8008     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8009     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8010       return DAG.getConstantFP(0.0, DL, VT);
8011
8012     // We can fold chains of FADD's of the same value into multiplications.
8013     // This transform is not safe in general because we are reducing the number
8014     // of rounding steps.
8015     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8016       if (N0.getOpcode() == ISD::FMUL) {
8017         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8018         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8019
8020         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8021         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8022           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8023                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8024           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8025         }
8026
8027         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8028         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8029             N1.getOperand(0) == N1.getOperand(1) &&
8030             N0.getOperand(0) == N1.getOperand(0)) {
8031           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8032                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8033           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8034         }
8035       }
8036
8037       if (N1.getOpcode() == ISD::FMUL) {
8038         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8039         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8040
8041         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8042         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8043           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8044                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8045           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8046         }
8047
8048         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8049         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8050             N0.getOperand(0) == N0.getOperand(1) &&
8051             N1.getOperand(0) == N0.getOperand(0)) {
8052           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8053                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8054           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8055         }
8056       }
8057
8058       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8059         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8060         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8061         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8062             (N0.getOperand(0) == N1)) {
8063           return DAG.getNode(ISD::FMUL, DL, VT,
8064                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8065         }
8066       }
8067
8068       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8069         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8070         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8071         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8072             N1.getOperand(0) == N0) {
8073           return DAG.getNode(ISD::FMUL, DL, VT,
8074                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8075         }
8076       }
8077
8078       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8079       if (AllowNewConst &&
8080           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8081           N0.getOperand(0) == N0.getOperand(1) &&
8082           N1.getOperand(0) == N1.getOperand(1) &&
8083           N0.getOperand(0) == N1.getOperand(0)) {
8084         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8085                            DAG.getConstantFP(4.0, DL, VT), Flags);
8086       }
8087     }
8088   } // enable-unsafe-fp-math
8089
8090   // FADD -> FMA combines:
8091   if (SDValue Fused = visitFADDForFMACombine(N)) {
8092     AddToWorklist(Fused.getNode());
8093     return Fused;
8094   }
8095
8096   return SDValue();
8097 }
8098
8099 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8100   SDValue N0 = N->getOperand(0);
8101   SDValue N1 = N->getOperand(1);
8102   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8103   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8104   EVT VT = N->getValueType(0);
8105   SDLoc dl(N);
8106   const TargetOptions &Options = DAG.getTarget().Options;
8107   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8108
8109   // fold vector ops
8110   if (VT.isVector())
8111     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8112       return FoldedVOp;
8113
8114   // fold (fsub c1, c2) -> c1-c2
8115   if (N0CFP && N1CFP)
8116     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8117
8118   // fold (fsub A, (fneg B)) -> (fadd A, B)
8119   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8120     return DAG.getNode(ISD::FADD, dl, VT, N0,
8121                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8122
8123   // If 'unsafe math' is enabled, fold lots of things.
8124   if (Options.UnsafeFPMath) {
8125     // (fsub A, 0) -> A
8126     if (N1CFP && N1CFP->isZero())
8127       return N0;
8128
8129     // (fsub 0, B) -> -B
8130     if (N0CFP && N0CFP->isZero()) {
8131       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8132         return GetNegatedExpression(N1, DAG, LegalOperations);
8133       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8134         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8135     }
8136
8137     // (fsub x, x) -> 0.0
8138     if (N0 == N1)
8139       return DAG.getConstantFP(0.0f, dl, VT);
8140
8141     // (fsub x, (fadd x, y)) -> (fneg y)
8142     // (fsub x, (fadd y, x)) -> (fneg y)
8143     if (N1.getOpcode() == ISD::FADD) {
8144       SDValue N10 = N1->getOperand(0);
8145       SDValue N11 = N1->getOperand(1);
8146
8147       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8148         return GetNegatedExpression(N11, DAG, LegalOperations);
8149
8150       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8151         return GetNegatedExpression(N10, DAG, LegalOperations);
8152     }
8153   }
8154
8155   // FSUB -> FMA combines:
8156   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8157     AddToWorklist(Fused.getNode());
8158     return Fused;
8159   }
8160
8161   return SDValue();
8162 }
8163
8164 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8165   SDValue N0 = N->getOperand(0);
8166   SDValue N1 = N->getOperand(1);
8167   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8168   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8169   EVT VT = N->getValueType(0);
8170   SDLoc DL(N);
8171   const TargetOptions &Options = DAG.getTarget().Options;
8172   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8173
8174   // fold vector ops
8175   if (VT.isVector()) {
8176     // This just handles C1 * C2 for vectors. Other vector folds are below.
8177     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8178       return FoldedVOp;
8179   }
8180
8181   // fold (fmul c1, c2) -> c1*c2
8182   if (N0CFP && N1CFP)
8183     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8184
8185   // canonicalize constant to RHS
8186   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8187      !isConstantFPBuildVectorOrConstantFP(N1))
8188     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8189
8190   // fold (fmul A, 1.0) -> A
8191   if (N1CFP && N1CFP->isExactlyValue(1.0))
8192     return N0;
8193
8194   if (Options.UnsafeFPMath) {
8195     // fold (fmul A, 0) -> 0
8196     if (N1CFP && N1CFP->isZero())
8197       return N1;
8198
8199     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8200     if (N0.getOpcode() == ISD::FMUL) {
8201       // Fold scalars or any vector constants (not just splats).
8202       // This fold is done in general by InstCombine, but extra fmul insts
8203       // may have been generated during lowering.
8204       SDValue N00 = N0.getOperand(0);
8205       SDValue N01 = N0.getOperand(1);
8206       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8207       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8208       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8209
8210       // Check 1: Make sure that the first operand of the inner multiply is NOT
8211       // a constant. Otherwise, we may induce infinite looping.
8212       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8213         // Check 2: Make sure that the second operand of the inner multiply and
8214         // the second operand of the outer multiply are constants.
8215         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8216             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8217           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8218           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8219         }
8220       }
8221     }
8222
8223     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8224     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8225     // during an early run of DAGCombiner can prevent folding with fmuls
8226     // inserted during lowering.
8227     if (N0.getOpcode() == ISD::FADD &&
8228         (N0.getOperand(0) == N0.getOperand(1)) &&
8229         N0.hasOneUse()) {
8230       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8231       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8232       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8233     }
8234   }
8235
8236   // fold (fmul X, 2.0) -> (fadd X, X)
8237   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8238     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8239
8240   // fold (fmul X, -1.0) -> (fneg X)
8241   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8242     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8243       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8244
8245   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8246   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8247     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8248       // Both can be negated for free, check to see if at least one is cheaper
8249       // negated.
8250       if (LHSNeg == 2 || RHSNeg == 2)
8251         return DAG.getNode(ISD::FMUL, DL, VT,
8252                            GetNegatedExpression(N0, DAG, LegalOperations),
8253                            GetNegatedExpression(N1, DAG, LegalOperations),
8254                            Flags);
8255     }
8256   }
8257
8258   // FMUL -> FMA combines:
8259   if (SDValue Fused = visitFMULForFMACombine(N)) {
8260     AddToWorklist(Fused.getNode());
8261     return Fused;
8262   }
8263
8264   return SDValue();
8265 }
8266
8267 SDValue DAGCombiner::visitFMA(SDNode *N) {
8268   SDValue N0 = N->getOperand(0);
8269   SDValue N1 = N->getOperand(1);
8270   SDValue N2 = N->getOperand(2);
8271   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8272   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8273   EVT VT = N->getValueType(0);
8274   SDLoc dl(N);
8275   const TargetOptions &Options = DAG.getTarget().Options;
8276
8277   // Constant fold FMA.
8278   if (isa<ConstantFPSDNode>(N0) &&
8279       isa<ConstantFPSDNode>(N1) &&
8280       isa<ConstantFPSDNode>(N2)) {
8281     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8282   }
8283
8284   if (Options.UnsafeFPMath) {
8285     if (N0CFP && N0CFP->isZero())
8286       return N2;
8287     if (N1CFP && N1CFP->isZero())
8288       return N2;
8289   }
8290   // TODO: The FMA node should have flags that propagate to these nodes.
8291   if (N0CFP && N0CFP->isExactlyValue(1.0))
8292     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8293   if (N1CFP && N1CFP->isExactlyValue(1.0))
8294     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8295
8296   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8297   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8298      !isConstantFPBuildVectorOrConstantFP(N1))
8299     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8300
8301   // TODO: FMA nodes should have flags that propagate to the created nodes.
8302   // For now, create a Flags object for use with all unsafe math transforms.
8303   SDNodeFlags Flags;
8304   Flags.setUnsafeAlgebra(true);
8305
8306   if (Options.UnsafeFPMath) {
8307     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8308     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8309         isConstantFPBuildVectorOrConstantFP(N1) &&
8310         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8311       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8312                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8313                                      &Flags), &Flags);
8314     }
8315
8316     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8317     if (N0.getOpcode() == ISD::FMUL &&
8318         isConstantFPBuildVectorOrConstantFP(N1) &&
8319         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8320       return DAG.getNode(ISD::FMA, dl, VT,
8321                          N0.getOperand(0),
8322                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8323                                      &Flags),
8324                          N2);
8325     }
8326   }
8327
8328   // (fma x, 1, y) -> (fadd x, y)
8329   // (fma x, -1, y) -> (fadd (fneg x), y)
8330   if (N1CFP) {
8331     if (N1CFP->isExactlyValue(1.0))
8332       // TODO: The FMA node should have flags that propagate to this node.
8333       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8334
8335     if (N1CFP->isExactlyValue(-1.0) &&
8336         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8337       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8338       AddToWorklist(RHSNeg.getNode());
8339       // TODO: The FMA node should have flags that propagate to this node.
8340       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8341     }
8342   }
8343
8344   if (Options.UnsafeFPMath) {
8345     // (fma x, c, x) -> (fmul x, (c+1))
8346     if (N1CFP && N0 == N2) {
8347     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8348                          DAG.getNode(ISD::FADD, dl, VT,
8349                                      N1, DAG.getConstantFP(1.0, dl, VT),
8350                                      &Flags), &Flags);
8351     }
8352
8353     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8354     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8355       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8356                          DAG.getNode(ISD::FADD, dl, VT,
8357                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8358                                      &Flags), &Flags);
8359     }
8360   }
8361
8362   return SDValue();
8363 }
8364
8365 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8366 // reciprocal.
8367 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8368 // Notice that this is not always beneficial. One reason is different target
8369 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8370 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8371 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8372 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8373   if (!DAG.getTarget().Options.UnsafeFPMath)
8374     return SDValue();
8375
8376   // Skip if current node is a reciprocal.
8377   SDValue N0 = N->getOperand(0);
8378   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8379   if (N0CFP && N0CFP->isExactlyValue(1.0))
8380     return SDValue();
8381
8382   // Exit early if the target does not want this transform or if there can't
8383   // possibly be enough uses of the divisor to make the transform worthwhile.
8384   SDValue N1 = N->getOperand(1);
8385   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8386   if (!MinUses || N1->use_size() < MinUses)
8387     return SDValue();
8388
8389   // Find all FDIV users of the same divisor.
8390   // Use a set because duplicates may be present in the user list.
8391   SetVector<SDNode *> Users;
8392   for (auto *U : N1->uses())
8393     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8394       Users.insert(U);
8395
8396   // Now that we have the actual number of divisor uses, make sure it meets
8397   // the minimum threshold specified by the target.
8398   if (Users.size() < MinUses)
8399     return SDValue();
8400
8401   EVT VT = N->getValueType(0);
8402   SDLoc DL(N);
8403   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8404   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8405   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8406
8407   // Dividend / Divisor -> Dividend * Reciprocal
8408   for (auto *U : Users) {
8409     SDValue Dividend = U->getOperand(0);
8410     if (Dividend != FPOne) {
8411       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8412                                     Reciprocal, Flags);
8413       CombineTo(U, NewNode);
8414     } else if (U != Reciprocal.getNode()) {
8415       // In the absence of fast-math-flags, this user node is always the
8416       // same node as Reciprocal, but with FMF they may be different nodes.
8417       CombineTo(U, Reciprocal);
8418     }
8419   }
8420   return SDValue(N, 0);  // N was replaced.
8421 }
8422
8423 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8424   SDValue N0 = N->getOperand(0);
8425   SDValue N1 = N->getOperand(1);
8426   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8427   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8428   EVT VT = N->getValueType(0);
8429   SDLoc DL(N);
8430   const TargetOptions &Options = DAG.getTarget().Options;
8431   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8432
8433   // fold vector ops
8434   if (VT.isVector())
8435     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8436       return FoldedVOp;
8437
8438   // fold (fdiv c1, c2) -> c1/c2
8439   if (N0CFP && N1CFP)
8440     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8441
8442   if (Options.UnsafeFPMath) {
8443     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8444     if (N1CFP) {
8445       // Compute the reciprocal 1.0 / c2.
8446       APFloat N1APF = N1CFP->getValueAPF();
8447       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8448       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8449       // Only do the transform if the reciprocal is a legal fp immediate that
8450       // isn't too nasty (eg NaN, denormal, ...).
8451       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8452           (!LegalOperations ||
8453            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8454            // backend)... we should handle this gracefully after Legalize.
8455            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8456            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8457            TLI.isFPImmLegal(Recip, VT)))
8458         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8459                            DAG.getConstantFP(Recip, DL, VT), Flags);
8460     }
8461
8462     // If this FDIV is part of a reciprocal square root, it may be folded
8463     // into a target-specific square root estimate instruction.
8464     if (N1.getOpcode() == ISD::FSQRT) {
8465       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8466         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8467       }
8468     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8469                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8470       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8471                                           Flags)) {
8472         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8473         AddToWorklist(RV.getNode());
8474         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8475       }
8476     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8477                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8478       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8479                                           Flags)) {
8480         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8481         AddToWorklist(RV.getNode());
8482         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8483       }
8484     } else if (N1.getOpcode() == ISD::FMUL) {
8485       // Look through an FMUL. Even though this won't remove the FDIV directly,
8486       // it's still worthwhile to get rid of the FSQRT if possible.
8487       SDValue SqrtOp;
8488       SDValue OtherOp;
8489       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8490         SqrtOp = N1.getOperand(0);
8491         OtherOp = N1.getOperand(1);
8492       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8493         SqrtOp = N1.getOperand(1);
8494         OtherOp = N1.getOperand(0);
8495       }
8496       if (SqrtOp.getNode()) {
8497         // We found a FSQRT, so try to make this fold:
8498         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8499         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8500           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8501           AddToWorklist(RV.getNode());
8502           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8503         }
8504       }
8505     }
8506
8507     // Fold into a reciprocal estimate and multiply instead of a real divide.
8508     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8509       AddToWorklist(RV.getNode());
8510       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8511     }
8512   }
8513
8514   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8515   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8516     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8517       // Both can be negated for free, check to see if at least one is cheaper
8518       // negated.
8519       if (LHSNeg == 2 || RHSNeg == 2)
8520         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8521                            GetNegatedExpression(N0, DAG, LegalOperations),
8522                            GetNegatedExpression(N1, DAG, LegalOperations),
8523                            Flags);
8524     }
8525   }
8526
8527   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8528     return CombineRepeatedDivisors;
8529
8530   return SDValue();
8531 }
8532
8533 SDValue DAGCombiner::visitFREM(SDNode *N) {
8534   SDValue N0 = N->getOperand(0);
8535   SDValue N1 = N->getOperand(1);
8536   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8537   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8538   EVT VT = N->getValueType(0);
8539
8540   // fold (frem c1, c2) -> fmod(c1,c2)
8541   if (N0CFP && N1CFP)
8542     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8543                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8544
8545   return SDValue();
8546 }
8547
8548 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8549   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8550     return SDValue();
8551
8552   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8553   // For now, create a Flags object for use with all unsafe math transforms.
8554   SDNodeFlags Flags;
8555   Flags.setUnsafeAlgebra(true);
8556
8557   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8558   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8559   if (!RV)
8560     return SDValue();
8561
8562   EVT VT = RV.getValueType();
8563   SDLoc DL(N);
8564   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8565   AddToWorklist(RV.getNode());
8566
8567   // Unfortunately, RV is now NaN if the input was exactly 0.
8568   // Select out this case and force the answer to 0.
8569   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8570   EVT CCVT = getSetCCResultType(VT);
8571   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8572   AddToWorklist(ZeroCmp.getNode());
8573   AddToWorklist(RV.getNode());
8574
8575   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8576                      ZeroCmp, Zero, RV);
8577 }
8578
8579 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8580   SDValue N0 = N->getOperand(0);
8581   SDValue N1 = N->getOperand(1);
8582   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8583   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8584   EVT VT = N->getValueType(0);
8585
8586   if (N0CFP && N1CFP)  // Constant fold
8587     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8588
8589   if (N1CFP) {
8590     const APFloat& V = N1CFP->getValueAPF();
8591     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8592     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8593     if (!V.isNegative()) {
8594       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8595         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8596     } else {
8597       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8598         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8599                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8600     }
8601   }
8602
8603   // copysign(fabs(x), y) -> copysign(x, y)
8604   // copysign(fneg(x), y) -> copysign(x, y)
8605   // copysign(copysign(x,z), y) -> copysign(x, y)
8606   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8607       N0.getOpcode() == ISD::FCOPYSIGN)
8608     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8609                        N0.getOperand(0), N1);
8610
8611   // copysign(x, abs(y)) -> abs(x)
8612   if (N1.getOpcode() == ISD::FABS)
8613     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8614
8615   // copysign(x, copysign(y,z)) -> copysign(x, z)
8616   if (N1.getOpcode() == ISD::FCOPYSIGN)
8617     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8618                        N0, N1.getOperand(1));
8619
8620   // copysign(x, fp_extend(y)) -> copysign(x, y)
8621   // copysign(x, fp_round(y)) -> copysign(x, y)
8622   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8623     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8624                        N0, N1.getOperand(0));
8625
8626   return SDValue();
8627 }
8628
8629 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8630   SDValue N0 = N->getOperand(0);
8631   EVT VT = N->getValueType(0);
8632   EVT OpVT = N0.getValueType();
8633
8634   // fold (sint_to_fp c1) -> c1fp
8635   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8636       // ...but only if the target supports immediate floating-point values
8637       (!LegalOperations ||
8638        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8639     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8640
8641   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8642   // but UINT_TO_FP is legal on this target, try to convert.
8643   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8644       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8645     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8646     if (DAG.SignBitIsZero(N0))
8647       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8648   }
8649
8650   // The next optimizations are desirable only if SELECT_CC can be lowered.
8651   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8652     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8653     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8654         !VT.isVector() &&
8655         (!LegalOperations ||
8656          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8657       SDLoc DL(N);
8658       SDValue Ops[] =
8659         { N0.getOperand(0), N0.getOperand(1),
8660           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8661           N0.getOperand(2) };
8662       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8663     }
8664
8665     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8666     //      (select_cc x, y, 1.0, 0.0,, cc)
8667     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8668         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8669         (!LegalOperations ||
8670          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8671       SDLoc DL(N);
8672       SDValue Ops[] =
8673         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8674           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8675           N0.getOperand(0).getOperand(2) };
8676       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8677     }
8678   }
8679
8680   return SDValue();
8681 }
8682
8683 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8684   SDValue N0 = N->getOperand(0);
8685   EVT VT = N->getValueType(0);
8686   EVT OpVT = N0.getValueType();
8687
8688   // fold (uint_to_fp c1) -> c1fp
8689   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8690       // ...but only if the target supports immediate floating-point values
8691       (!LegalOperations ||
8692        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8693     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8694
8695   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8696   // but SINT_TO_FP is legal on this target, try to convert.
8697   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8698       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8699     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8700     if (DAG.SignBitIsZero(N0))
8701       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8702   }
8703
8704   // The next optimizations are desirable only if SELECT_CC can be lowered.
8705   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8706     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8707
8708     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8709         (!LegalOperations ||
8710          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8711       SDLoc DL(N);
8712       SDValue Ops[] =
8713         { N0.getOperand(0), N0.getOperand(1),
8714           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8715           N0.getOperand(2) };
8716       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8717     }
8718   }
8719
8720   return SDValue();
8721 }
8722
8723 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8724 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8725   SDValue N0 = N->getOperand(0);
8726   EVT VT = N->getValueType(0);
8727
8728   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8729     return SDValue();
8730
8731   SDValue Src = N0.getOperand(0);
8732   EVT SrcVT = Src.getValueType();
8733   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8734   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8735
8736   // We can safely assume the conversion won't overflow the output range,
8737   // because (for example) (uint8_t)18293.f is undefined behavior.
8738
8739   // Since we can assume the conversion won't overflow, our decision as to
8740   // whether the input will fit in the float should depend on the minimum
8741   // of the input range and output range.
8742
8743   // This means this is also safe for a signed input and unsigned output, since
8744   // a negative input would lead to undefined behavior.
8745   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8746   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8747   unsigned ActualSize = std::min(InputSize, OutputSize);
8748   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8749
8750   // We can only fold away the float conversion if the input range can be
8751   // represented exactly in the float range.
8752   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8753     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8754       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8755                                                        : ISD::ZERO_EXTEND;
8756       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8757     }
8758     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8759       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8760     if (SrcVT == VT)
8761       return Src;
8762     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8763   }
8764   return SDValue();
8765 }
8766
8767 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8768   SDValue N0 = N->getOperand(0);
8769   EVT VT = N->getValueType(0);
8770
8771   // fold (fp_to_sint c1fp) -> c1
8772   if (isConstantFPBuildVectorOrConstantFP(N0))
8773     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8774
8775   return FoldIntToFPToInt(N, DAG);
8776 }
8777
8778 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8779   SDValue N0 = N->getOperand(0);
8780   EVT VT = N->getValueType(0);
8781
8782   // fold (fp_to_uint c1fp) -> c1
8783   if (isConstantFPBuildVectorOrConstantFP(N0))
8784     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8785
8786   return FoldIntToFPToInt(N, DAG);
8787 }
8788
8789 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8790   SDValue N0 = N->getOperand(0);
8791   SDValue N1 = N->getOperand(1);
8792   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8793   EVT VT = N->getValueType(0);
8794
8795   // fold (fp_round c1fp) -> c1fp
8796   if (N0CFP)
8797     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8798
8799   // fold (fp_round (fp_extend x)) -> x
8800   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8801     return N0.getOperand(0);
8802
8803   // fold (fp_round (fp_round x)) -> (fp_round x)
8804   if (N0.getOpcode() == ISD::FP_ROUND) {
8805     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8806     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8807     // If the first fp_round isn't a value preserving truncation, it might
8808     // introduce a tie in the second fp_round, that wouldn't occur in the
8809     // single-step fp_round we want to fold to.
8810     // In other words, double rounding isn't the same as rounding.
8811     // Also, this is a value preserving truncation iff both fp_round's are.
8812     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8813       SDLoc DL(N);
8814       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8815                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8816     }
8817   }
8818
8819   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8820   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8821     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8822                               N0.getOperand(0), N1);
8823     AddToWorklist(Tmp.getNode());
8824     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8825                        Tmp, N0.getOperand(1));
8826   }
8827
8828   return SDValue();
8829 }
8830
8831 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8832   SDValue N0 = N->getOperand(0);
8833   EVT VT = N->getValueType(0);
8834   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8835   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8836
8837   // fold (fp_round_inreg c1fp) -> c1fp
8838   if (N0CFP && isTypeLegal(EVT)) {
8839     SDLoc DL(N);
8840     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8841     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8842   }
8843
8844   return SDValue();
8845 }
8846
8847 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8848   SDValue N0 = N->getOperand(0);
8849   EVT VT = N->getValueType(0);
8850
8851   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8852   if (N->hasOneUse() &&
8853       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8854     return SDValue();
8855
8856   // fold (fp_extend c1fp) -> c1fp
8857   if (isConstantFPBuildVectorOrConstantFP(N0))
8858     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8859
8860   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8861   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8862       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8863     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8864
8865   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8866   // value of X.
8867   if (N0.getOpcode() == ISD::FP_ROUND
8868       && N0.getNode()->getConstantOperandVal(1) == 1) {
8869     SDValue In = N0.getOperand(0);
8870     if (In.getValueType() == VT) return In;
8871     if (VT.bitsLT(In.getValueType()))
8872       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8873                          In, N0.getOperand(1));
8874     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8875   }
8876
8877   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8878   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8879        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8880     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8881     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8882                                      LN0->getChain(),
8883                                      LN0->getBasePtr(), N0.getValueType(),
8884                                      LN0->getMemOperand());
8885     CombineTo(N, ExtLoad);
8886     CombineTo(N0.getNode(),
8887               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8888                           N0.getValueType(), ExtLoad,
8889                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8890               ExtLoad.getValue(1));
8891     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8892   }
8893
8894   return SDValue();
8895 }
8896
8897 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8898   SDValue N0 = N->getOperand(0);
8899   EVT VT = N->getValueType(0);
8900
8901   // fold (fceil c1) -> fceil(c1)
8902   if (isConstantFPBuildVectorOrConstantFP(N0))
8903     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8904
8905   return SDValue();
8906 }
8907
8908 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8909   SDValue N0 = N->getOperand(0);
8910   EVT VT = N->getValueType(0);
8911
8912   // fold (ftrunc c1) -> ftrunc(c1)
8913   if (isConstantFPBuildVectorOrConstantFP(N0))
8914     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8915
8916   return SDValue();
8917 }
8918
8919 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8920   SDValue N0 = N->getOperand(0);
8921   EVT VT = N->getValueType(0);
8922
8923   // fold (ffloor c1) -> ffloor(c1)
8924   if (isConstantFPBuildVectorOrConstantFP(N0))
8925     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8926
8927   return SDValue();
8928 }
8929
8930 // FIXME: FNEG and FABS have a lot in common; refactor.
8931 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8932   SDValue N0 = N->getOperand(0);
8933   EVT VT = N->getValueType(0);
8934
8935   // Constant fold FNEG.
8936   if (isConstantFPBuildVectorOrConstantFP(N0))
8937     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8938
8939   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8940                          &DAG.getTarget().Options))
8941     return GetNegatedExpression(N0, DAG, LegalOperations);
8942
8943   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8944   // constant pool values.
8945   if (!TLI.isFNegFree(VT) &&
8946       N0.getOpcode() == ISD::BITCAST &&
8947       N0.getNode()->hasOneUse()) {
8948     SDValue Int = N0.getOperand(0);
8949     EVT IntVT = Int.getValueType();
8950     if (IntVT.isInteger() && !IntVT.isVector()) {
8951       APInt SignMask;
8952       if (N0.getValueType().isVector()) {
8953         // For a vector, get a mask such as 0x80... per scalar element
8954         // and splat it.
8955         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8956         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8957       } else {
8958         // For a scalar, just generate 0x80...
8959         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8960       }
8961       SDLoc DL0(N0);
8962       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8963                         DAG.getConstant(SignMask, DL0, IntVT));
8964       AddToWorklist(Int.getNode());
8965       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8966     }
8967   }
8968
8969   // (fneg (fmul c, x)) -> (fmul -c, x)
8970   if (N0.getOpcode() == ISD::FMUL &&
8971       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8972     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8973     if (CFP1) {
8974       APFloat CVal = CFP1->getValueAPF();
8975       CVal.changeSign();
8976       if (Level >= AfterLegalizeDAG &&
8977           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8978            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8979         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8980                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8981                                        N0.getOperand(1)),
8982                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
8983     }
8984   }
8985
8986   return SDValue();
8987 }
8988
8989 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8990   SDValue N0 = N->getOperand(0);
8991   SDValue N1 = N->getOperand(1);
8992   EVT VT = N->getValueType(0);
8993   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8994   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8995
8996   if (N0CFP && N1CFP) {
8997     const APFloat &C0 = N0CFP->getValueAPF();
8998     const APFloat &C1 = N1CFP->getValueAPF();
8999     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9000   }
9001
9002   // Canonicalize to constant on RHS.
9003   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9004      !isConstantFPBuildVectorOrConstantFP(N1))
9005     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9006
9007   return SDValue();
9008 }
9009
9010 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9011   SDValue N0 = N->getOperand(0);
9012   SDValue N1 = N->getOperand(1);
9013   EVT VT = N->getValueType(0);
9014   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9015   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9016
9017   if (N0CFP && N1CFP) {
9018     const APFloat &C0 = N0CFP->getValueAPF();
9019     const APFloat &C1 = N1CFP->getValueAPF();
9020     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9021   }
9022
9023   // Canonicalize to constant on RHS.
9024   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9025      !isConstantFPBuildVectorOrConstantFP(N1))
9026     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9027
9028   return SDValue();
9029 }
9030
9031 SDValue DAGCombiner::visitFABS(SDNode *N) {
9032   SDValue N0 = N->getOperand(0);
9033   EVT VT = N->getValueType(0);
9034
9035   // fold (fabs c1) -> fabs(c1)
9036   if (isConstantFPBuildVectorOrConstantFP(N0))
9037     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9038
9039   // fold (fabs (fabs x)) -> (fabs x)
9040   if (N0.getOpcode() == ISD::FABS)
9041     return N->getOperand(0);
9042
9043   // fold (fabs (fneg x)) -> (fabs x)
9044   // fold (fabs (fcopysign x, y)) -> (fabs x)
9045   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9046     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9047
9048   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9049   // constant pool values.
9050   if (!TLI.isFAbsFree(VT) &&
9051       N0.getOpcode() == ISD::BITCAST &&
9052       N0.getNode()->hasOneUse()) {
9053     SDValue Int = N0.getOperand(0);
9054     EVT IntVT = Int.getValueType();
9055     if (IntVT.isInteger() && !IntVT.isVector()) {
9056       APInt SignMask;
9057       if (N0.getValueType().isVector()) {
9058         // For a vector, get a mask such as 0x7f... per scalar element
9059         // and splat it.
9060         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9061         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9062       } else {
9063         // For a scalar, just generate 0x7f...
9064         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9065       }
9066       SDLoc DL(N0);
9067       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9068                         DAG.getConstant(SignMask, DL, IntVT));
9069       AddToWorklist(Int.getNode());
9070       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9071     }
9072   }
9073
9074   return SDValue();
9075 }
9076
9077 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9078   SDValue Chain = N->getOperand(0);
9079   SDValue N1 = N->getOperand(1);
9080   SDValue N2 = N->getOperand(2);
9081
9082   // If N is a constant we could fold this into a fallthrough or unconditional
9083   // branch. However that doesn't happen very often in normal code, because
9084   // Instcombine/SimplifyCFG should have handled the available opportunities.
9085   // If we did this folding here, it would be necessary to update the
9086   // MachineBasicBlock CFG, which is awkward.
9087
9088   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9089   // on the target.
9090   if (N1.getOpcode() == ISD::SETCC &&
9091       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9092                                    N1.getOperand(0).getValueType())) {
9093     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9094                        Chain, N1.getOperand(2),
9095                        N1.getOperand(0), N1.getOperand(1), N2);
9096   }
9097
9098   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9099       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9100        (N1.getOperand(0).hasOneUse() &&
9101         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9102     SDNode *Trunc = nullptr;
9103     if (N1.getOpcode() == ISD::TRUNCATE) {
9104       // Look pass the truncate.
9105       Trunc = N1.getNode();
9106       N1 = N1.getOperand(0);
9107     }
9108
9109     // Match this pattern so that we can generate simpler code:
9110     //
9111     //   %a = ...
9112     //   %b = and i32 %a, 2
9113     //   %c = srl i32 %b, 1
9114     //   brcond i32 %c ...
9115     //
9116     // into
9117     //
9118     //   %a = ...
9119     //   %b = and i32 %a, 2
9120     //   %c = setcc eq %b, 0
9121     //   brcond %c ...
9122     //
9123     // This applies only when the AND constant value has one bit set and the
9124     // SRL constant is equal to the log2 of the AND constant. The back-end is
9125     // smart enough to convert the result into a TEST/JMP sequence.
9126     SDValue Op0 = N1.getOperand(0);
9127     SDValue Op1 = N1.getOperand(1);
9128
9129     if (Op0.getOpcode() == ISD::AND &&
9130         Op1.getOpcode() == ISD::Constant) {
9131       SDValue AndOp1 = Op0.getOperand(1);
9132
9133       if (AndOp1.getOpcode() == ISD::Constant) {
9134         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9135
9136         if (AndConst.isPowerOf2() &&
9137             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9138           SDLoc DL(N);
9139           SDValue SetCC =
9140             DAG.getSetCC(DL,
9141                          getSetCCResultType(Op0.getValueType()),
9142                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9143                          ISD::SETNE);
9144
9145           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9146                                           MVT::Other, Chain, SetCC, N2);
9147           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9148           // will convert it back to (X & C1) >> C2.
9149           CombineTo(N, NewBRCond, false);
9150           // Truncate is dead.
9151           if (Trunc)
9152             deleteAndRecombine(Trunc);
9153           // Replace the uses of SRL with SETCC
9154           WorklistRemover DeadNodes(*this);
9155           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9156           deleteAndRecombine(N1.getNode());
9157           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9158         }
9159       }
9160     }
9161
9162     if (Trunc)
9163       // Restore N1 if the above transformation doesn't match.
9164       N1 = N->getOperand(1);
9165   }
9166
9167   // Transform br(xor(x, y)) -> br(x != y)
9168   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9169   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9170     SDNode *TheXor = N1.getNode();
9171     SDValue Op0 = TheXor->getOperand(0);
9172     SDValue Op1 = TheXor->getOperand(1);
9173     if (Op0.getOpcode() == Op1.getOpcode()) {
9174       // Avoid missing important xor optimizations.
9175       if (SDValue Tmp = visitXOR(TheXor)) {
9176         if (Tmp.getNode() != TheXor) {
9177           DEBUG(dbgs() << "\nReplacing.8 ";
9178                 TheXor->dump(&DAG);
9179                 dbgs() << "\nWith: ";
9180                 Tmp.getNode()->dump(&DAG);
9181                 dbgs() << '\n');
9182           WorklistRemover DeadNodes(*this);
9183           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9184           deleteAndRecombine(TheXor);
9185           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9186                              MVT::Other, Chain, Tmp, N2);
9187         }
9188
9189         // visitXOR has changed XOR's operands or replaced the XOR completely,
9190         // bail out.
9191         return SDValue(N, 0);
9192       }
9193     }
9194
9195     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9196       bool Equal = false;
9197       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9198           Op0.getOpcode() == ISD::XOR) {
9199         TheXor = Op0.getNode();
9200         Equal = true;
9201       }
9202
9203       EVT SetCCVT = N1.getValueType();
9204       if (LegalTypes)
9205         SetCCVT = getSetCCResultType(SetCCVT);
9206       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9207                                    SetCCVT,
9208                                    Op0, Op1,
9209                                    Equal ? ISD::SETEQ : ISD::SETNE);
9210       // Replace the uses of XOR with SETCC
9211       WorklistRemover DeadNodes(*this);
9212       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9213       deleteAndRecombine(N1.getNode());
9214       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9215                          MVT::Other, Chain, SetCC, N2);
9216     }
9217   }
9218
9219   return SDValue();
9220 }
9221
9222 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9223 //
9224 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9225   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9226   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9227
9228   // If N is a constant we could fold this into a fallthrough or unconditional
9229   // branch. However that doesn't happen very often in normal code, because
9230   // Instcombine/SimplifyCFG should have handled the available opportunities.
9231   // If we did this folding here, it would be necessary to update the
9232   // MachineBasicBlock CFG, which is awkward.
9233
9234   // Use SimplifySetCC to simplify SETCC's.
9235   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9236                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9237                                false);
9238   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9239
9240   // fold to a simpler setcc
9241   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9242     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9243                        N->getOperand(0), Simp.getOperand(2),
9244                        Simp.getOperand(0), Simp.getOperand(1),
9245                        N->getOperand(4));
9246
9247   return SDValue();
9248 }
9249
9250 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9251 /// and that N may be folded in the load / store addressing mode.
9252 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9253                                     SelectionDAG &DAG,
9254                                     const TargetLowering &TLI) {
9255   EVT VT;
9256   unsigned AS;
9257
9258   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9259     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9260       return false;
9261     VT = LD->getMemoryVT();
9262     AS = LD->getAddressSpace();
9263   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9264     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9265       return false;
9266     VT = ST->getMemoryVT();
9267     AS = ST->getAddressSpace();
9268   } else
9269     return false;
9270
9271   TargetLowering::AddrMode AM;
9272   if (N->getOpcode() == ISD::ADD) {
9273     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9274     if (Offset)
9275       // [reg +/- imm]
9276       AM.BaseOffs = Offset->getSExtValue();
9277     else
9278       // [reg +/- reg]
9279       AM.Scale = 1;
9280   } else if (N->getOpcode() == ISD::SUB) {
9281     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9282     if (Offset)
9283       // [reg +/- imm]
9284       AM.BaseOffs = -Offset->getSExtValue();
9285     else
9286       // [reg +/- reg]
9287       AM.Scale = 1;
9288   } else
9289     return false;
9290
9291   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9292                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9293 }
9294
9295 /// Try turning a load/store into a pre-indexed load/store when the base
9296 /// pointer is an add or subtract and it has other uses besides the load/store.
9297 /// After the transformation, the new indexed load/store has effectively folded
9298 /// the add/subtract in and all of its other uses are redirected to the
9299 /// new load/store.
9300 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9301   if (Level < AfterLegalizeDAG)
9302     return false;
9303
9304   bool isLoad = true;
9305   SDValue Ptr;
9306   EVT VT;
9307   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9308     if (LD->isIndexed())
9309       return false;
9310     VT = LD->getMemoryVT();
9311     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9312         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9313       return false;
9314     Ptr = LD->getBasePtr();
9315   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9316     if (ST->isIndexed())
9317       return false;
9318     VT = ST->getMemoryVT();
9319     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9320         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9321       return false;
9322     Ptr = ST->getBasePtr();
9323     isLoad = false;
9324   } else {
9325     return false;
9326   }
9327
9328   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9329   // out.  There is no reason to make this a preinc/predec.
9330   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9331       Ptr.getNode()->hasOneUse())
9332     return false;
9333
9334   // Ask the target to do addressing mode selection.
9335   SDValue BasePtr;
9336   SDValue Offset;
9337   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9338   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9339     return false;
9340
9341   // Backends without true r+i pre-indexed forms may need to pass a
9342   // constant base with a variable offset so that constant coercion
9343   // will work with the patterns in canonical form.
9344   bool Swapped = false;
9345   if (isa<ConstantSDNode>(BasePtr)) {
9346     std::swap(BasePtr, Offset);
9347     Swapped = true;
9348   }
9349
9350   // Don't create a indexed load / store with zero offset.
9351   if (isNullConstant(Offset))
9352     return false;
9353
9354   // Try turning it into a pre-indexed load / store except when:
9355   // 1) The new base ptr is a frame index.
9356   // 2) If N is a store and the new base ptr is either the same as or is a
9357   //    predecessor of the value being stored.
9358   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9359   //    that would create a cycle.
9360   // 4) All uses are load / store ops that use it as old base ptr.
9361
9362   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9363   // (plus the implicit offset) to a register to preinc anyway.
9364   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9365     return false;
9366
9367   // Check #2.
9368   if (!isLoad) {
9369     SDValue Val = cast<StoreSDNode>(N)->getValue();
9370     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9371       return false;
9372   }
9373
9374   // If the offset is a constant, there may be other adds of constants that
9375   // can be folded with this one. We should do this to avoid having to keep
9376   // a copy of the original base pointer.
9377   SmallVector<SDNode *, 16> OtherUses;
9378   if (isa<ConstantSDNode>(Offset))
9379     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9380                               UE = BasePtr.getNode()->use_end();
9381          UI != UE; ++UI) {
9382       SDUse &Use = UI.getUse();
9383       // Skip the use that is Ptr and uses of other results from BasePtr's
9384       // node (important for nodes that return multiple results).
9385       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9386         continue;
9387
9388       if (Use.getUser()->isPredecessorOf(N))
9389         continue;
9390
9391       if (Use.getUser()->getOpcode() != ISD::ADD &&
9392           Use.getUser()->getOpcode() != ISD::SUB) {
9393         OtherUses.clear();
9394         break;
9395       }
9396
9397       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9398       if (!isa<ConstantSDNode>(Op1)) {
9399         OtherUses.clear();
9400         break;
9401       }
9402
9403       // FIXME: In some cases, we can be smarter about this.
9404       if (Op1.getValueType() != Offset.getValueType()) {
9405         OtherUses.clear();
9406         break;
9407       }
9408
9409       OtherUses.push_back(Use.getUser());
9410     }
9411
9412   if (Swapped)
9413     std::swap(BasePtr, Offset);
9414
9415   // Now check for #3 and #4.
9416   bool RealUse = false;
9417
9418   // Caches for hasPredecessorHelper
9419   SmallPtrSet<const SDNode *, 32> Visited;
9420   SmallVector<const SDNode *, 16> Worklist;
9421
9422   for (SDNode *Use : Ptr.getNode()->uses()) {
9423     if (Use == N)
9424       continue;
9425     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9426       return false;
9427
9428     // If Ptr may be folded in addressing mode of other use, then it's
9429     // not profitable to do this transformation.
9430     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9431       RealUse = true;
9432   }
9433
9434   if (!RealUse)
9435     return false;
9436
9437   SDValue Result;
9438   if (isLoad)
9439     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9440                                 BasePtr, Offset, AM);
9441   else
9442     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9443                                  BasePtr, Offset, AM);
9444   ++PreIndexedNodes;
9445   ++NodesCombined;
9446   DEBUG(dbgs() << "\nReplacing.4 ";
9447         N->dump(&DAG);
9448         dbgs() << "\nWith: ";
9449         Result.getNode()->dump(&DAG);
9450         dbgs() << '\n');
9451   WorklistRemover DeadNodes(*this);
9452   if (isLoad) {
9453     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9454     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9455   } else {
9456     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9457   }
9458
9459   // Finally, since the node is now dead, remove it from the graph.
9460   deleteAndRecombine(N);
9461
9462   if (Swapped)
9463     std::swap(BasePtr, Offset);
9464
9465   // Replace other uses of BasePtr that can be updated to use Ptr
9466   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9467     unsigned OffsetIdx = 1;
9468     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9469       OffsetIdx = 0;
9470     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9471            BasePtr.getNode() && "Expected BasePtr operand");
9472
9473     // We need to replace ptr0 in the following expression:
9474     //   x0 * offset0 + y0 * ptr0 = t0
9475     // knowing that
9476     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9477     //
9478     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9479     // indexed load/store and the expresion that needs to be re-written.
9480     //
9481     // Therefore, we have:
9482     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9483
9484     ConstantSDNode *CN =
9485       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9486     int X0, X1, Y0, Y1;
9487     APInt Offset0 = CN->getAPIntValue();
9488     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9489
9490     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9491     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9492     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9493     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9494
9495     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9496
9497     APInt CNV = Offset0;
9498     if (X0 < 0) CNV = -CNV;
9499     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9500     else CNV = CNV - Offset1;
9501
9502     SDLoc DL(OtherUses[i]);
9503
9504     // We can now generate the new expression.
9505     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9506     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9507
9508     SDValue NewUse = DAG.getNode(Opcode,
9509                                  DL,
9510                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9511     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9512     deleteAndRecombine(OtherUses[i]);
9513   }
9514
9515   // Replace the uses of Ptr with uses of the updated base value.
9516   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9517   deleteAndRecombine(Ptr.getNode());
9518
9519   return true;
9520 }
9521
9522 /// Try to combine a load/store with a add/sub of the base pointer node into a
9523 /// post-indexed load/store. The transformation folded the add/subtract into the
9524 /// new indexed load/store effectively and all of its uses are redirected to the
9525 /// new load/store.
9526 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9527   if (Level < AfterLegalizeDAG)
9528     return false;
9529
9530   bool isLoad = true;
9531   SDValue Ptr;
9532   EVT VT;
9533   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9534     if (LD->isIndexed())
9535       return false;
9536     VT = LD->getMemoryVT();
9537     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9538         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9539       return false;
9540     Ptr = LD->getBasePtr();
9541   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9542     if (ST->isIndexed())
9543       return false;
9544     VT = ST->getMemoryVT();
9545     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9546         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9547       return false;
9548     Ptr = ST->getBasePtr();
9549     isLoad = false;
9550   } else {
9551     return false;
9552   }
9553
9554   if (Ptr.getNode()->hasOneUse())
9555     return false;
9556
9557   for (SDNode *Op : Ptr.getNode()->uses()) {
9558     if (Op == N ||
9559         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9560       continue;
9561
9562     SDValue BasePtr;
9563     SDValue Offset;
9564     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9565     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9566       // Don't create a indexed load / store with zero offset.
9567       if (isNullConstant(Offset))
9568         continue;
9569
9570       // Try turning it into a post-indexed load / store except when
9571       // 1) All uses are load / store ops that use it as base ptr (and
9572       //    it may be folded as addressing mmode).
9573       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9574       //    nor a successor of N. Otherwise, if Op is folded that would
9575       //    create a cycle.
9576
9577       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9578         continue;
9579
9580       // Check for #1.
9581       bool TryNext = false;
9582       for (SDNode *Use : BasePtr.getNode()->uses()) {
9583         if (Use == Ptr.getNode())
9584           continue;
9585
9586         // If all the uses are load / store addresses, then don't do the
9587         // transformation.
9588         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9589           bool RealUse = false;
9590           for (SDNode *UseUse : Use->uses()) {
9591             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9592               RealUse = true;
9593           }
9594
9595           if (!RealUse) {
9596             TryNext = true;
9597             break;
9598           }
9599         }
9600       }
9601
9602       if (TryNext)
9603         continue;
9604
9605       // Check for #2
9606       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9607         SDValue Result = isLoad
9608           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9609                                BasePtr, Offset, AM)
9610           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9611                                 BasePtr, Offset, AM);
9612         ++PostIndexedNodes;
9613         ++NodesCombined;
9614         DEBUG(dbgs() << "\nReplacing.5 ";
9615               N->dump(&DAG);
9616               dbgs() << "\nWith: ";
9617               Result.getNode()->dump(&DAG);
9618               dbgs() << '\n');
9619         WorklistRemover DeadNodes(*this);
9620         if (isLoad) {
9621           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9622           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9623         } else {
9624           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9625         }
9626
9627         // Finally, since the node is now dead, remove it from the graph.
9628         deleteAndRecombine(N);
9629
9630         // Replace the uses of Use with uses of the updated base value.
9631         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9632                                       Result.getValue(isLoad ? 1 : 0));
9633         deleteAndRecombine(Op);
9634         return true;
9635       }
9636     }
9637   }
9638
9639   return false;
9640 }
9641
9642 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9643 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9644   ISD::MemIndexedMode AM = LD->getAddressingMode();
9645   assert(AM != ISD::UNINDEXED);
9646   SDValue BP = LD->getOperand(1);
9647   SDValue Inc = LD->getOperand(2);
9648
9649   // Some backends use TargetConstants for load offsets, but don't expect
9650   // TargetConstants in general ADD nodes. We can convert these constants into
9651   // regular Constants (if the constant is not opaque).
9652   assert((Inc.getOpcode() != ISD::TargetConstant ||
9653           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9654          "Cannot split out indexing using opaque target constants");
9655   if (Inc.getOpcode() == ISD::TargetConstant) {
9656     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9657     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9658                           ConstInc->getValueType(0));
9659   }
9660
9661   unsigned Opc =
9662       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9663   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9664 }
9665
9666 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9667   LoadSDNode *LD  = cast<LoadSDNode>(N);
9668   SDValue Chain = LD->getChain();
9669   SDValue Ptr   = LD->getBasePtr();
9670
9671   // If load is not volatile and there are no uses of the loaded value (and
9672   // the updated indexed value in case of indexed loads), change uses of the
9673   // chain value into uses of the chain input (i.e. delete the dead load).
9674   if (!LD->isVolatile()) {
9675     if (N->getValueType(1) == MVT::Other) {
9676       // Unindexed loads.
9677       if (!N->hasAnyUseOfValue(0)) {
9678         // It's not safe to use the two value CombineTo variant here. e.g.
9679         // v1, chain2 = load chain1, loc
9680         // v2, chain3 = load chain2, loc
9681         // v3         = add v2, c
9682         // Now we replace use of chain2 with chain1.  This makes the second load
9683         // isomorphic to the one we are deleting, and thus makes this load live.
9684         DEBUG(dbgs() << "\nReplacing.6 ";
9685               N->dump(&DAG);
9686               dbgs() << "\nWith chain: ";
9687               Chain.getNode()->dump(&DAG);
9688               dbgs() << "\n");
9689         WorklistRemover DeadNodes(*this);
9690         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9691
9692         if (N->use_empty())
9693           deleteAndRecombine(N);
9694
9695         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9696       }
9697     } else {
9698       // Indexed loads.
9699       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9700
9701       // If this load has an opaque TargetConstant offset, then we cannot split
9702       // the indexing into an add/sub directly (that TargetConstant may not be
9703       // valid for a different type of node, and we cannot convert an opaque
9704       // target constant into a regular constant).
9705       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9706                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9707
9708       if (!N->hasAnyUseOfValue(0) &&
9709           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9710         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9711         SDValue Index;
9712         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9713           Index = SplitIndexingFromLoad(LD);
9714           // Try to fold the base pointer arithmetic into subsequent loads and
9715           // stores.
9716           AddUsersToWorklist(N);
9717         } else
9718           Index = DAG.getUNDEF(N->getValueType(1));
9719         DEBUG(dbgs() << "\nReplacing.7 ";
9720               N->dump(&DAG);
9721               dbgs() << "\nWith: ";
9722               Undef.getNode()->dump(&DAG);
9723               dbgs() << " and 2 other values\n");
9724         WorklistRemover DeadNodes(*this);
9725         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9726         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9727         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9728         deleteAndRecombine(N);
9729         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9730       }
9731     }
9732   }
9733
9734   // If this load is directly stored, replace the load value with the stored
9735   // value.
9736   // TODO: Handle store large -> read small portion.
9737   // TODO: Handle TRUNCSTORE/LOADEXT
9738   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9739     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9740       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9741       if (PrevST->getBasePtr() == Ptr &&
9742           PrevST->getValue().getValueType() == N->getValueType(0))
9743       return CombineTo(N, Chain.getOperand(1), Chain);
9744     }
9745   }
9746
9747   // Try to infer better alignment information than the load already has.
9748   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9749     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9750       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9751         SDValue NewLoad =
9752                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9753                               LD->getValueType(0),
9754                               Chain, Ptr, LD->getPointerInfo(),
9755                               LD->getMemoryVT(),
9756                               LD->isVolatile(), LD->isNonTemporal(),
9757                               LD->isInvariant(), Align, LD->getAAInfo());
9758         if (NewLoad.getNode() != N)
9759           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9760       }
9761     }
9762   }
9763
9764   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9765                                                   : DAG.getSubtarget().useAA();
9766 #ifndef NDEBUG
9767   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9768       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9769     UseAA = false;
9770 #endif
9771   if (UseAA && LD->isUnindexed()) {
9772     // Walk up chain skipping non-aliasing memory nodes.
9773     SDValue BetterChain = FindBetterChain(N, Chain);
9774
9775     // If there is a better chain.
9776     if (Chain != BetterChain) {
9777       SDValue ReplLoad;
9778
9779       // Replace the chain to void dependency.
9780       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9781         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9782                                BetterChain, Ptr, LD->getMemOperand());
9783       } else {
9784         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9785                                   LD->getValueType(0),
9786                                   BetterChain, Ptr, LD->getMemoryVT(),
9787                                   LD->getMemOperand());
9788       }
9789
9790       // Create token factor to keep old chain connected.
9791       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9792                                   MVT::Other, Chain, ReplLoad.getValue(1));
9793
9794       // Make sure the new and old chains are cleaned up.
9795       AddToWorklist(Token.getNode());
9796
9797       // Replace uses with load result and token factor. Don't add users
9798       // to work list.
9799       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9800     }
9801   }
9802
9803   // Try transforming N to an indexed load.
9804   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9805     return SDValue(N, 0);
9806
9807   // Try to slice up N to more direct loads if the slices are mapped to
9808   // different register banks or pairing can take place.
9809   if (SliceUpLoad(N))
9810     return SDValue(N, 0);
9811
9812   return SDValue();
9813 }
9814
9815 namespace {
9816 /// \brief Helper structure used to slice a load in smaller loads.
9817 /// Basically a slice is obtained from the following sequence:
9818 /// Origin = load Ty1, Base
9819 /// Shift = srl Ty1 Origin, CstTy Amount
9820 /// Inst = trunc Shift to Ty2
9821 ///
9822 /// Then, it will be rewriten into:
9823 /// Slice = load SliceTy, Base + SliceOffset
9824 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9825 ///
9826 /// SliceTy is deduced from the number of bits that are actually used to
9827 /// build Inst.
9828 struct LoadedSlice {
9829   /// \brief Helper structure used to compute the cost of a slice.
9830   struct Cost {
9831     /// Are we optimizing for code size.
9832     bool ForCodeSize;
9833     /// Various cost.
9834     unsigned Loads;
9835     unsigned Truncates;
9836     unsigned CrossRegisterBanksCopies;
9837     unsigned ZExts;
9838     unsigned Shift;
9839
9840     Cost(bool ForCodeSize = false)
9841         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9842           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9843
9844     /// \brief Get the cost of one isolated slice.
9845     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9846         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9847           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9848       EVT TruncType = LS.Inst->getValueType(0);
9849       EVT LoadedType = LS.getLoadedType();
9850       if (TruncType != LoadedType &&
9851           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9852         ZExts = 1;
9853     }
9854
9855     /// \brief Account for slicing gain in the current cost.
9856     /// Slicing provide a few gains like removing a shift or a
9857     /// truncate. This method allows to grow the cost of the original
9858     /// load with the gain from this slice.
9859     void addSliceGain(const LoadedSlice &LS) {
9860       // Each slice saves a truncate.
9861       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9862       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9863                               LS.Inst->getValueType(0)))
9864         ++Truncates;
9865       // If there is a shift amount, this slice gets rid of it.
9866       if (LS.Shift)
9867         ++Shift;
9868       // If this slice can merge a cross register bank copy, account for it.
9869       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9870         ++CrossRegisterBanksCopies;
9871     }
9872
9873     Cost &operator+=(const Cost &RHS) {
9874       Loads += RHS.Loads;
9875       Truncates += RHS.Truncates;
9876       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9877       ZExts += RHS.ZExts;
9878       Shift += RHS.Shift;
9879       return *this;
9880     }
9881
9882     bool operator==(const Cost &RHS) const {
9883       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9884              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9885              ZExts == RHS.ZExts && Shift == RHS.Shift;
9886     }
9887
9888     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9889
9890     bool operator<(const Cost &RHS) const {
9891       // Assume cross register banks copies are as expensive as loads.
9892       // FIXME: Do we want some more target hooks?
9893       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9894       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9895       // Unless we are optimizing for code size, consider the
9896       // expensive operation first.
9897       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9898         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9899       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9900              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9901     }
9902
9903     bool operator>(const Cost &RHS) const { return RHS < *this; }
9904
9905     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9906
9907     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9908   };
9909   // The last instruction that represent the slice. This should be a
9910   // truncate instruction.
9911   SDNode *Inst;
9912   // The original load instruction.
9913   LoadSDNode *Origin;
9914   // The right shift amount in bits from the original load.
9915   unsigned Shift;
9916   // The DAG from which Origin came from.
9917   // This is used to get some contextual information about legal types, etc.
9918   SelectionDAG *DAG;
9919
9920   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9921               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9922       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9923
9924   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9925   /// \return Result is \p BitWidth and has used bits set to 1 and
9926   ///         not used bits set to 0.
9927   APInt getUsedBits() const {
9928     // Reproduce the trunc(lshr) sequence:
9929     // - Start from the truncated value.
9930     // - Zero extend to the desired bit width.
9931     // - Shift left.
9932     assert(Origin && "No original load to compare against.");
9933     unsigned BitWidth = Origin->getValueSizeInBits(0);
9934     assert(Inst && "This slice is not bound to an instruction");
9935     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9936            "Extracted slice is bigger than the whole type!");
9937     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9938     UsedBits.setAllBits();
9939     UsedBits = UsedBits.zext(BitWidth);
9940     UsedBits <<= Shift;
9941     return UsedBits;
9942   }
9943
9944   /// \brief Get the size of the slice to be loaded in bytes.
9945   unsigned getLoadedSize() const {
9946     unsigned SliceSize = getUsedBits().countPopulation();
9947     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9948     return SliceSize / 8;
9949   }
9950
9951   /// \brief Get the type that will be loaded for this slice.
9952   /// Note: This may not be the final type for the slice.
9953   EVT getLoadedType() const {
9954     assert(DAG && "Missing context");
9955     LLVMContext &Ctxt = *DAG->getContext();
9956     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9957   }
9958
9959   /// \brief Get the alignment of the load used for this slice.
9960   unsigned getAlignment() const {
9961     unsigned Alignment = Origin->getAlignment();
9962     unsigned Offset = getOffsetFromBase();
9963     if (Offset != 0)
9964       Alignment = MinAlign(Alignment, Alignment + Offset);
9965     return Alignment;
9966   }
9967
9968   /// \brief Check if this slice can be rewritten with legal operations.
9969   bool isLegal() const {
9970     // An invalid slice is not legal.
9971     if (!Origin || !Inst || !DAG)
9972       return false;
9973
9974     // Offsets are for indexed load only, we do not handle that.
9975     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9976       return false;
9977
9978     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9979
9980     // Check that the type is legal.
9981     EVT SliceType = getLoadedType();
9982     if (!TLI.isTypeLegal(SliceType))
9983       return false;
9984
9985     // Check that the load is legal for this type.
9986     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9987       return false;
9988
9989     // Check that the offset can be computed.
9990     // 1. Check its type.
9991     EVT PtrType = Origin->getBasePtr().getValueType();
9992     if (PtrType == MVT::Untyped || PtrType.isExtended())
9993       return false;
9994
9995     // 2. Check that it fits in the immediate.
9996     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9997       return false;
9998
9999     // 3. Check that the computation is legal.
10000     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10001       return false;
10002
10003     // Check that the zext is legal if it needs one.
10004     EVT TruncateType = Inst->getValueType(0);
10005     if (TruncateType != SliceType &&
10006         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10007       return false;
10008
10009     return true;
10010   }
10011
10012   /// \brief Get the offset in bytes of this slice in the original chunk of
10013   /// bits.
10014   /// \pre DAG != nullptr.
10015   uint64_t getOffsetFromBase() const {
10016     assert(DAG && "Missing context.");
10017     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10018     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10019     uint64_t Offset = Shift / 8;
10020     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10021     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10022            "The size of the original loaded type is not a multiple of a"
10023            " byte.");
10024     // If Offset is bigger than TySizeInBytes, it means we are loading all
10025     // zeros. This should have been optimized before in the process.
10026     assert(TySizeInBytes > Offset &&
10027            "Invalid shift amount for given loaded size");
10028     if (IsBigEndian)
10029       Offset = TySizeInBytes - Offset - getLoadedSize();
10030     return Offset;
10031   }
10032
10033   /// \brief Generate the sequence of instructions to load the slice
10034   /// represented by this object and redirect the uses of this slice to
10035   /// this new sequence of instructions.
10036   /// \pre this->Inst && this->Origin are valid Instructions and this
10037   /// object passed the legal check: LoadedSlice::isLegal returned true.
10038   /// \return The last instruction of the sequence used to load the slice.
10039   SDValue loadSlice() const {
10040     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10041     const SDValue &OldBaseAddr = Origin->getBasePtr();
10042     SDValue BaseAddr = OldBaseAddr;
10043     // Get the offset in that chunk of bytes w.r.t. the endianess.
10044     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10045     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10046     if (Offset) {
10047       // BaseAddr = BaseAddr + Offset.
10048       EVT ArithType = BaseAddr.getValueType();
10049       SDLoc DL(Origin);
10050       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10051                               DAG->getConstant(Offset, DL, ArithType));
10052     }
10053
10054     // Create the type of the loaded slice according to its size.
10055     EVT SliceType = getLoadedType();
10056
10057     // Create the load for the slice.
10058     SDValue LastInst = DAG->getLoad(
10059         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10060         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10061         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10062     // If the final type is not the same as the loaded type, this means that
10063     // we have to pad with zero. Create a zero extend for that.
10064     EVT FinalType = Inst->getValueType(0);
10065     if (SliceType != FinalType)
10066       LastInst =
10067           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10068     return LastInst;
10069   }
10070
10071   /// \brief Check if this slice can be merged with an expensive cross register
10072   /// bank copy. E.g.,
10073   /// i = load i32
10074   /// f = bitcast i32 i to float
10075   bool canMergeExpensiveCrossRegisterBankCopy() const {
10076     if (!Inst || !Inst->hasOneUse())
10077       return false;
10078     SDNode *Use = *Inst->use_begin();
10079     if (Use->getOpcode() != ISD::BITCAST)
10080       return false;
10081     assert(DAG && "Missing context");
10082     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10083     EVT ResVT = Use->getValueType(0);
10084     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10085     const TargetRegisterClass *ArgRC =
10086         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10087     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10088       return false;
10089
10090     // At this point, we know that we perform a cross-register-bank copy.
10091     // Check if it is expensive.
10092     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10093     // Assume bitcasts are cheap, unless both register classes do not
10094     // explicitly share a common sub class.
10095     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10096       return false;
10097
10098     // Check if it will be merged with the load.
10099     // 1. Check the alignment constraint.
10100     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10101         ResVT.getTypeForEVT(*DAG->getContext()));
10102
10103     if (RequiredAlignment > getAlignment())
10104       return false;
10105
10106     // 2. Check that the load is a legal operation for that type.
10107     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10108       return false;
10109
10110     // 3. Check that we do not have a zext in the way.
10111     if (Inst->getValueType(0) != getLoadedType())
10112       return false;
10113
10114     return true;
10115   }
10116 };
10117 }
10118
10119 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10120 /// \p UsedBits looks like 0..0 1..1 0..0.
10121 static bool areUsedBitsDense(const APInt &UsedBits) {
10122   // If all the bits are one, this is dense!
10123   if (UsedBits.isAllOnesValue())
10124     return true;
10125
10126   // Get rid of the unused bits on the right.
10127   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10128   // Get rid of the unused bits on the left.
10129   if (NarrowedUsedBits.countLeadingZeros())
10130     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10131   // Check that the chunk of bits is completely used.
10132   return NarrowedUsedBits.isAllOnesValue();
10133 }
10134
10135 /// \brief Check whether or not \p First and \p Second are next to each other
10136 /// in memory. This means that there is no hole between the bits loaded
10137 /// by \p First and the bits loaded by \p Second.
10138 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10139                                      const LoadedSlice &Second) {
10140   assert(First.Origin == Second.Origin && First.Origin &&
10141          "Unable to match different memory origins.");
10142   APInt UsedBits = First.getUsedBits();
10143   assert((UsedBits & Second.getUsedBits()) == 0 &&
10144          "Slices are not supposed to overlap.");
10145   UsedBits |= Second.getUsedBits();
10146   return areUsedBitsDense(UsedBits);
10147 }
10148
10149 /// \brief Adjust the \p GlobalLSCost according to the target
10150 /// paring capabilities and the layout of the slices.
10151 /// \pre \p GlobalLSCost should account for at least as many loads as
10152 /// there is in the slices in \p LoadedSlices.
10153 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10154                                  LoadedSlice::Cost &GlobalLSCost) {
10155   unsigned NumberOfSlices = LoadedSlices.size();
10156   // If there is less than 2 elements, no pairing is possible.
10157   if (NumberOfSlices < 2)
10158     return;
10159
10160   // Sort the slices so that elements that are likely to be next to each
10161   // other in memory are next to each other in the list.
10162   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10163             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10164     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10165     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10166   });
10167   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10168   // First (resp. Second) is the first (resp. Second) potentially candidate
10169   // to be placed in a paired load.
10170   const LoadedSlice *First = nullptr;
10171   const LoadedSlice *Second = nullptr;
10172   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10173                 // Set the beginning of the pair.
10174                                                            First = Second) {
10175
10176     Second = &LoadedSlices[CurrSlice];
10177
10178     // If First is NULL, it means we start a new pair.
10179     // Get to the next slice.
10180     if (!First)
10181       continue;
10182
10183     EVT LoadedType = First->getLoadedType();
10184
10185     // If the types of the slices are different, we cannot pair them.
10186     if (LoadedType != Second->getLoadedType())
10187       continue;
10188
10189     // Check if the target supplies paired loads for this type.
10190     unsigned RequiredAlignment = 0;
10191     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10192       // move to the next pair, this type is hopeless.
10193       Second = nullptr;
10194       continue;
10195     }
10196     // Check if we meet the alignment requirement.
10197     if (RequiredAlignment > First->getAlignment())
10198       continue;
10199
10200     // Check that both loads are next to each other in memory.
10201     if (!areSlicesNextToEachOther(*First, *Second))
10202       continue;
10203
10204     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10205     --GlobalLSCost.Loads;
10206     // Move to the next pair.
10207     Second = nullptr;
10208   }
10209 }
10210
10211 /// \brief Check the profitability of all involved LoadedSlice.
10212 /// Currently, it is considered profitable if there is exactly two
10213 /// involved slices (1) which are (2) next to each other in memory, and
10214 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10215 ///
10216 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10217 /// the elements themselves.
10218 ///
10219 /// FIXME: When the cost model will be mature enough, we can relax
10220 /// constraints (1) and (2).
10221 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10222                                 const APInt &UsedBits, bool ForCodeSize) {
10223   unsigned NumberOfSlices = LoadedSlices.size();
10224   if (StressLoadSlicing)
10225     return NumberOfSlices > 1;
10226
10227   // Check (1).
10228   if (NumberOfSlices != 2)
10229     return false;
10230
10231   // Check (2).
10232   if (!areUsedBitsDense(UsedBits))
10233     return false;
10234
10235   // Check (3).
10236   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10237   // The original code has one big load.
10238   OrigCost.Loads = 1;
10239   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10240     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10241     // Accumulate the cost of all the slices.
10242     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10243     GlobalSlicingCost += SliceCost;
10244
10245     // Account as cost in the original configuration the gain obtained
10246     // with the current slices.
10247     OrigCost.addSliceGain(LS);
10248   }
10249
10250   // If the target supports paired load, adjust the cost accordingly.
10251   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10252   return OrigCost > GlobalSlicingCost;
10253 }
10254
10255 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10256 /// operations, split it in the various pieces being extracted.
10257 ///
10258 /// This sort of thing is introduced by SROA.
10259 /// This slicing takes care not to insert overlapping loads.
10260 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10261 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10262   if (Level < AfterLegalizeDAG)
10263     return false;
10264
10265   LoadSDNode *LD = cast<LoadSDNode>(N);
10266   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10267       !LD->getValueType(0).isInteger())
10268     return false;
10269
10270   // Keep track of already used bits to detect overlapping values.
10271   // In that case, we will just abort the transformation.
10272   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10273
10274   SmallVector<LoadedSlice, 4> LoadedSlices;
10275
10276   // Check if this load is used as several smaller chunks of bits.
10277   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10278   // of computation for each trunc.
10279   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10280        UI != UIEnd; ++UI) {
10281     // Skip the uses of the chain.
10282     if (UI.getUse().getResNo() != 0)
10283       continue;
10284
10285     SDNode *User = *UI;
10286     unsigned Shift = 0;
10287
10288     // Check if this is a trunc(lshr).
10289     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10290         isa<ConstantSDNode>(User->getOperand(1))) {
10291       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10292       User = *User->use_begin();
10293     }
10294
10295     // At this point, User is a Truncate, iff we encountered, trunc or
10296     // trunc(lshr).
10297     if (User->getOpcode() != ISD::TRUNCATE)
10298       return false;
10299
10300     // The width of the type must be a power of 2 and greater than 8-bits.
10301     // Otherwise the load cannot be represented in LLVM IR.
10302     // Moreover, if we shifted with a non-8-bits multiple, the slice
10303     // will be across several bytes. We do not support that.
10304     unsigned Width = User->getValueSizeInBits(0);
10305     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10306       return 0;
10307
10308     // Build the slice for this chain of computations.
10309     LoadedSlice LS(User, LD, Shift, &DAG);
10310     APInt CurrentUsedBits = LS.getUsedBits();
10311
10312     // Check if this slice overlaps with another.
10313     if ((CurrentUsedBits & UsedBits) != 0)
10314       return false;
10315     // Update the bits used globally.
10316     UsedBits |= CurrentUsedBits;
10317
10318     // Check if the new slice would be legal.
10319     if (!LS.isLegal())
10320       return false;
10321
10322     // Record the slice.
10323     LoadedSlices.push_back(LS);
10324   }
10325
10326   // Abort slicing if it does not seem to be profitable.
10327   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10328     return false;
10329
10330   ++SlicedLoads;
10331
10332   // Rewrite each chain to use an independent load.
10333   // By construction, each chain can be represented by a unique load.
10334
10335   // Prepare the argument for the new token factor for all the slices.
10336   SmallVector<SDValue, 8> ArgChains;
10337   for (SmallVectorImpl<LoadedSlice>::const_iterator
10338            LSIt = LoadedSlices.begin(),
10339            LSItEnd = LoadedSlices.end();
10340        LSIt != LSItEnd; ++LSIt) {
10341     SDValue SliceInst = LSIt->loadSlice();
10342     CombineTo(LSIt->Inst, SliceInst, true);
10343     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10344       SliceInst = SliceInst.getOperand(0);
10345     assert(SliceInst->getOpcode() == ISD::LOAD &&
10346            "It takes more than a zext to get to the loaded slice!!");
10347     ArgChains.push_back(SliceInst.getValue(1));
10348   }
10349
10350   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10351                               ArgChains);
10352   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10353   return true;
10354 }
10355
10356 /// Check to see if V is (and load (ptr), imm), where the load is having
10357 /// specific bytes cleared out.  If so, return the byte size being masked out
10358 /// and the shift amount.
10359 static std::pair<unsigned, unsigned>
10360 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10361   std::pair<unsigned, unsigned> Result(0, 0);
10362
10363   // Check for the structure we're looking for.
10364   if (V->getOpcode() != ISD::AND ||
10365       !isa<ConstantSDNode>(V->getOperand(1)) ||
10366       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10367     return Result;
10368
10369   // Check the chain and pointer.
10370   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10371   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10372
10373   // The store should be chained directly to the load or be an operand of a
10374   // tokenfactor.
10375   if (LD == Chain.getNode())
10376     ; // ok.
10377   else if (Chain->getOpcode() != ISD::TokenFactor)
10378     return Result; // Fail.
10379   else {
10380     bool isOk = false;
10381     for (const SDValue &ChainOp : Chain->op_values())
10382       if (ChainOp.getNode() == LD) {
10383         isOk = true;
10384         break;
10385       }
10386     if (!isOk) return Result;
10387   }
10388
10389   // This only handles simple types.
10390   if (V.getValueType() != MVT::i16 &&
10391       V.getValueType() != MVT::i32 &&
10392       V.getValueType() != MVT::i64)
10393     return Result;
10394
10395   // Check the constant mask.  Invert it so that the bits being masked out are
10396   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10397   // follow the sign bit for uniformity.
10398   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10399   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10400   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10401   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10402   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10403   if (NotMaskLZ == 64) return Result;  // All zero mask.
10404
10405   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10406   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10407     return Result;
10408
10409   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10410   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10411     NotMaskLZ -= 64-V.getValueSizeInBits();
10412
10413   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10414   switch (MaskedBytes) {
10415   case 1:
10416   case 2:
10417   case 4: break;
10418   default: return Result; // All one mask, or 5-byte mask.
10419   }
10420
10421   // Verify that the first bit starts at a multiple of mask so that the access
10422   // is aligned the same as the access width.
10423   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10424
10425   Result.first = MaskedBytes;
10426   Result.second = NotMaskTZ/8;
10427   return Result;
10428 }
10429
10430
10431 /// Check to see if IVal is something that provides a value as specified by
10432 /// MaskInfo. If so, replace the specified store with a narrower store of
10433 /// truncated IVal.
10434 static SDNode *
10435 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10436                                 SDValue IVal, StoreSDNode *St,
10437                                 DAGCombiner *DC) {
10438   unsigned NumBytes = MaskInfo.first;
10439   unsigned ByteShift = MaskInfo.second;
10440   SelectionDAG &DAG = DC->getDAG();
10441
10442   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10443   // that uses this.  If not, this is not a replacement.
10444   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10445                                   ByteShift*8, (ByteShift+NumBytes)*8);
10446   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10447
10448   // Check that it is legal on the target to do this.  It is legal if the new
10449   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10450   // legalization.
10451   MVT VT = MVT::getIntegerVT(NumBytes*8);
10452   if (!DC->isTypeLegal(VT))
10453     return nullptr;
10454
10455   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10456   // shifted by ByteShift and truncated down to NumBytes.
10457   if (ByteShift) {
10458     SDLoc DL(IVal);
10459     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10460                        DAG.getConstant(ByteShift*8, DL,
10461                                     DC->getShiftAmountTy(IVal.getValueType())));
10462   }
10463
10464   // Figure out the offset for the store and the alignment of the access.
10465   unsigned StOffset;
10466   unsigned NewAlign = St->getAlignment();
10467
10468   if (DAG.getDataLayout().isLittleEndian())
10469     StOffset = ByteShift;
10470   else
10471     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10472
10473   SDValue Ptr = St->getBasePtr();
10474   if (StOffset) {
10475     SDLoc DL(IVal);
10476     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10477                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10478     NewAlign = MinAlign(NewAlign, StOffset);
10479   }
10480
10481   // Truncate down to the new size.
10482   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10483
10484   ++OpsNarrowed;
10485   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10486                       St->getPointerInfo().getWithOffset(StOffset),
10487                       false, false, NewAlign).getNode();
10488 }
10489
10490
10491 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10492 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10493 /// narrowing the load and store if it would end up being a win for performance
10494 /// or code size.
10495 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10496   StoreSDNode *ST  = cast<StoreSDNode>(N);
10497   if (ST->isVolatile())
10498     return SDValue();
10499
10500   SDValue Chain = ST->getChain();
10501   SDValue Value = ST->getValue();
10502   SDValue Ptr   = ST->getBasePtr();
10503   EVT VT = Value.getValueType();
10504
10505   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10506     return SDValue();
10507
10508   unsigned Opc = Value.getOpcode();
10509
10510   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10511   // is a byte mask indicating a consecutive number of bytes, check to see if
10512   // Y is known to provide just those bytes.  If so, we try to replace the
10513   // load + replace + store sequence with a single (narrower) store, which makes
10514   // the load dead.
10515   if (Opc == ISD::OR) {
10516     std::pair<unsigned, unsigned> MaskedLoad;
10517     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10518     if (MaskedLoad.first)
10519       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10520                                                   Value.getOperand(1), ST,this))
10521         return SDValue(NewST, 0);
10522
10523     // Or is commutative, so try swapping X and Y.
10524     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10525     if (MaskedLoad.first)
10526       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10527                                                   Value.getOperand(0), ST,this))
10528         return SDValue(NewST, 0);
10529   }
10530
10531   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10532       Value.getOperand(1).getOpcode() != ISD::Constant)
10533     return SDValue();
10534
10535   SDValue N0 = Value.getOperand(0);
10536   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10537       Chain == SDValue(N0.getNode(), 1)) {
10538     LoadSDNode *LD = cast<LoadSDNode>(N0);
10539     if (LD->getBasePtr() != Ptr ||
10540         LD->getPointerInfo().getAddrSpace() !=
10541         ST->getPointerInfo().getAddrSpace())
10542       return SDValue();
10543
10544     // Find the type to narrow it the load / op / store to.
10545     SDValue N1 = Value.getOperand(1);
10546     unsigned BitWidth = N1.getValueSizeInBits();
10547     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10548     if (Opc == ISD::AND)
10549       Imm ^= APInt::getAllOnesValue(BitWidth);
10550     if (Imm == 0 || Imm.isAllOnesValue())
10551       return SDValue();
10552     unsigned ShAmt = Imm.countTrailingZeros();
10553     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10554     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10555     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10556     // The narrowing should be profitable, the load/store operation should be
10557     // legal (or custom) and the store size should be equal to the NewVT width.
10558     while (NewBW < BitWidth &&
10559            (NewVT.getStoreSizeInBits() != NewBW ||
10560             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10561             !TLI.isNarrowingProfitable(VT, NewVT))) {
10562       NewBW = NextPowerOf2(NewBW);
10563       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10564     }
10565     if (NewBW >= BitWidth)
10566       return SDValue();
10567
10568     // If the lsb changed does not start at the type bitwidth boundary,
10569     // start at the previous one.
10570     if (ShAmt % NewBW)
10571       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10572     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10573                                    std::min(BitWidth, ShAmt + NewBW));
10574     if ((Imm & Mask) == Imm) {
10575       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10576       if (Opc == ISD::AND)
10577         NewImm ^= APInt::getAllOnesValue(NewBW);
10578       uint64_t PtrOff = ShAmt / 8;
10579       // For big endian targets, we need to adjust the offset to the pointer to
10580       // load the correct bytes.
10581       if (DAG.getDataLayout().isBigEndian())
10582         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10583
10584       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10585       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10586       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10587         return SDValue();
10588
10589       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10590                                    Ptr.getValueType(), Ptr,
10591                                    DAG.getConstant(PtrOff, SDLoc(LD),
10592                                                    Ptr.getValueType()));
10593       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10594                                   LD->getChain(), NewPtr,
10595                                   LD->getPointerInfo().getWithOffset(PtrOff),
10596                                   LD->isVolatile(), LD->isNonTemporal(),
10597                                   LD->isInvariant(), NewAlign,
10598                                   LD->getAAInfo());
10599       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10600                                    DAG.getConstant(NewImm, SDLoc(Value),
10601                                                    NewVT));
10602       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10603                                    NewVal, NewPtr,
10604                                    ST->getPointerInfo().getWithOffset(PtrOff),
10605                                    false, false, NewAlign);
10606
10607       AddToWorklist(NewPtr.getNode());
10608       AddToWorklist(NewLD.getNode());
10609       AddToWorklist(NewVal.getNode());
10610       WorklistRemover DeadNodes(*this);
10611       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10612       ++OpsNarrowed;
10613       return NewST;
10614     }
10615   }
10616
10617   return SDValue();
10618 }
10619
10620 /// For a given floating point load / store pair, if the load value isn't used
10621 /// by any other operations, then consider transforming the pair to integer
10622 /// load / store operations if the target deems the transformation profitable.
10623 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10624   StoreSDNode *ST  = cast<StoreSDNode>(N);
10625   SDValue Chain = ST->getChain();
10626   SDValue Value = ST->getValue();
10627   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10628       Value.hasOneUse() &&
10629       Chain == SDValue(Value.getNode(), 1)) {
10630     LoadSDNode *LD = cast<LoadSDNode>(Value);
10631     EVT VT = LD->getMemoryVT();
10632     if (!VT.isFloatingPoint() ||
10633         VT != ST->getMemoryVT() ||
10634         LD->isNonTemporal() ||
10635         ST->isNonTemporal() ||
10636         LD->getPointerInfo().getAddrSpace() != 0 ||
10637         ST->getPointerInfo().getAddrSpace() != 0)
10638       return SDValue();
10639
10640     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10641     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10642         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10643         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10644         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10645       return SDValue();
10646
10647     unsigned LDAlign = LD->getAlignment();
10648     unsigned STAlign = ST->getAlignment();
10649     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10650     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10651     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10652       return SDValue();
10653
10654     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10655                                 LD->getChain(), LD->getBasePtr(),
10656                                 LD->getPointerInfo(),
10657                                 false, false, false, LDAlign);
10658
10659     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10660                                  NewLD, ST->getBasePtr(),
10661                                  ST->getPointerInfo(),
10662                                  false, false, STAlign);
10663
10664     AddToWorklist(NewLD.getNode());
10665     AddToWorklist(NewST.getNode());
10666     WorklistRemover DeadNodes(*this);
10667     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10668     ++LdStFP2Int;
10669     return NewST;
10670   }
10671
10672   return SDValue();
10673 }
10674
10675 namespace {
10676 /// Helper struct to parse and store a memory address as base + index + offset.
10677 /// We ignore sign extensions when it is safe to do so.
10678 /// The following two expressions are not equivalent. To differentiate we need
10679 /// to store whether there was a sign extension involved in the index
10680 /// computation.
10681 ///  (load (i64 add (i64 copyfromreg %c)
10682 ///                 (i64 signextend (add (i8 load %index)
10683 ///                                      (i8 1))))
10684 /// vs
10685 ///
10686 /// (load (i64 add (i64 copyfromreg %c)
10687 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10688 ///                                         (i32 1)))))
10689 struct BaseIndexOffset {
10690   SDValue Base;
10691   SDValue Index;
10692   int64_t Offset;
10693   bool IsIndexSignExt;
10694
10695   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10696
10697   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10698                   bool IsIndexSignExt) :
10699     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10700
10701   bool equalBaseIndex(const BaseIndexOffset &Other) {
10702     return Other.Base == Base && Other.Index == Index &&
10703       Other.IsIndexSignExt == IsIndexSignExt;
10704   }
10705
10706   /// Parses tree in Ptr for base, index, offset addresses.
10707   static BaseIndexOffset match(SDValue Ptr) {
10708     bool IsIndexSignExt = false;
10709
10710     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10711     // instruction, then it could be just the BASE or everything else we don't
10712     // know how to handle. Just use Ptr as BASE and give up.
10713     if (Ptr->getOpcode() != ISD::ADD)
10714       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10715
10716     // We know that we have at least an ADD instruction. Try to pattern match
10717     // the simple case of BASE + OFFSET.
10718     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10719       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10720       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10721                               IsIndexSignExt);
10722     }
10723
10724     // Inside a loop the current BASE pointer is calculated using an ADD and a
10725     // MUL instruction. In this case Ptr is the actual BASE pointer.
10726     // (i64 add (i64 %array_ptr)
10727     //          (i64 mul (i64 %induction_var)
10728     //                   (i64 %element_size)))
10729     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10730       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10731
10732     // Look at Base + Index + Offset cases.
10733     SDValue Base = Ptr->getOperand(0);
10734     SDValue IndexOffset = Ptr->getOperand(1);
10735
10736     // Skip signextends.
10737     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10738       IndexOffset = IndexOffset->getOperand(0);
10739       IsIndexSignExt = true;
10740     }
10741
10742     // Either the case of Base + Index (no offset) or something else.
10743     if (IndexOffset->getOpcode() != ISD::ADD)
10744       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10745
10746     // Now we have the case of Base + Index + offset.
10747     SDValue Index = IndexOffset->getOperand(0);
10748     SDValue Offset = IndexOffset->getOperand(1);
10749
10750     if (!isa<ConstantSDNode>(Offset))
10751       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10752
10753     // Ignore signextends.
10754     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10755       Index = Index->getOperand(0);
10756       IsIndexSignExt = true;
10757     } else IsIndexSignExt = false;
10758
10759     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10760     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10761   }
10762 };
10763 } // namespace
10764
10765 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10766                                                   SDLoc SL,
10767                                                   ArrayRef<MemOpLink> Stores,
10768                                                   SmallVectorImpl<SDValue> &Chains,
10769                                                   EVT Ty) const {
10770   SmallVector<SDValue, 8> BuildVector;
10771
10772   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10773     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10774     Chains.push_back(St->getChain());
10775     BuildVector.push_back(St->getValue());
10776   }
10777
10778   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10779 }
10780
10781 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10782                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10783                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10784   // Make sure we have something to merge.
10785   if (NumStores < 2)
10786     return false;
10787
10788   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10789   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10790   unsigned LatestNodeUsed = 0;
10791
10792   for (unsigned i=0; i < NumStores; ++i) {
10793     // Find a chain for the new wide-store operand. Notice that some
10794     // of the store nodes that we found may not be selected for inclusion
10795     // in the wide store. The chain we use needs to be the chain of the
10796     // latest store node which is *used* and replaced by the wide store.
10797     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10798       LatestNodeUsed = i;
10799   }
10800
10801   SmallVector<SDValue, 8> Chains;
10802
10803   // The latest Node in the DAG.
10804   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10805   SDLoc DL(StoreNodes[0].MemNode);
10806
10807   SDValue StoredVal;
10808   if (UseVector) {
10809     bool IsVec = MemVT.isVector();
10810     unsigned Elts = NumStores;
10811     if (IsVec) {
10812       // When merging vector stores, get the total number of elements.
10813       Elts *= MemVT.getVectorNumElements();
10814     }
10815     // Get the type for the merged vector store.
10816     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10817     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10818
10819     if (IsConstantSrc) {
10820       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10821     } else {
10822       SmallVector<SDValue, 8> Ops;
10823       for (unsigned i = 0; i < NumStores; ++i) {
10824         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10825         SDValue Val = St->getValue();
10826         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10827         if (Val.getValueType() != MemVT)
10828           return false;
10829         Ops.push_back(Val);
10830         Chains.push_back(St->getChain());
10831       }
10832
10833       // Build the extracted vector elements back into a vector.
10834       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10835                               DL, Ty, Ops);    }
10836   } else {
10837     // We should always use a vector store when merging extracted vector
10838     // elements, so this path implies a store of constants.
10839     assert(IsConstantSrc && "Merged vector elements should use vector store");
10840
10841     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10842     APInt StoreInt(SizeInBits, 0);
10843
10844     // Construct a single integer constant which is made of the smaller
10845     // constant inputs.
10846     bool IsLE = DAG.getDataLayout().isLittleEndian();
10847     for (unsigned i = 0; i < NumStores; ++i) {
10848       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10849       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10850       Chains.push_back(St->getChain());
10851
10852       SDValue Val = St->getValue();
10853       StoreInt <<= ElementSizeBytes * 8;
10854       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10855         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10856       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10857         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10858       } else {
10859         llvm_unreachable("Invalid constant element type");
10860       }
10861     }
10862
10863     // Create the new Load and Store operations.
10864     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10865     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10866   }
10867
10868   assert(!Chains.empty());
10869
10870   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10871   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
10872                                   FirstInChain->getBasePtr(),
10873                                   FirstInChain->getPointerInfo(),
10874                                   false, false,
10875                                   FirstInChain->getAlignment());
10876
10877   // Replace the last store with the new store
10878   CombineTo(LatestOp, NewStore);
10879   // Erase all other stores.
10880   for (unsigned i = 0; i < NumStores; ++i) {
10881     if (StoreNodes[i].MemNode == LatestOp)
10882       continue;
10883     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10884     // ReplaceAllUsesWith will replace all uses that existed when it was
10885     // called, but graph optimizations may cause new ones to appear. For
10886     // example, the case in pr14333 looks like
10887     //
10888     //  St's chain -> St -> another store -> X
10889     //
10890     // And the only difference from St to the other store is the chain.
10891     // When we change it's chain to be St's chain they become identical,
10892     // get CSEed and the net result is that X is now a use of St.
10893     // Since we know that St is redundant, just iterate.
10894     while (!St->use_empty())
10895       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10896     deleteAndRecombine(St);
10897   }
10898
10899   return true;
10900 }
10901
10902 void DAGCombiner::getStoreMergeAndAliasCandidates(
10903     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10904     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10905   // This holds the base pointer, index, and the offset in bytes from the base
10906   // pointer.
10907   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10908
10909   // We must have a base and an offset.
10910   if (!BasePtr.Base.getNode())
10911     return;
10912
10913   // Do not handle stores to undef base pointers.
10914   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10915     return;
10916
10917   // Walk up the chain and look for nodes with offsets from the same
10918   // base pointer. Stop when reaching an instruction with a different kind
10919   // or instruction which has a different base pointer.
10920   EVT MemVT = St->getMemoryVT();
10921   unsigned Seq = 0;
10922   StoreSDNode *Index = St;
10923
10924
10925   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10926                                                   : DAG.getSubtarget().useAA();
10927
10928   if (UseAA) {
10929     // Look at other users of the same chain. Stores on the same chain do not
10930     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10931     // to be on the same chain, so don't bother looking at adjacent chains.
10932
10933     SDValue Chain = St->getChain();
10934     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10935       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10936         if (I.getOperandNo() != 0)
10937           continue;
10938
10939         if (OtherST->isVolatile() || OtherST->isIndexed())
10940           continue;
10941
10942         if (OtherST->getMemoryVT() != MemVT)
10943           continue;
10944
10945         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10946
10947         if (Ptr.equalBaseIndex(BasePtr))
10948           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
10949       }
10950     }
10951
10952     return;
10953   }
10954
10955   while (Index) {
10956     // If the chain has more than one use, then we can't reorder the mem ops.
10957     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10958       break;
10959
10960     // Find the base pointer and offset for this memory node.
10961     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10962
10963     // Check that the base pointer is the same as the original one.
10964     if (!Ptr.equalBaseIndex(BasePtr))
10965       break;
10966
10967     // The memory operands must not be volatile.
10968     if (Index->isVolatile() || Index->isIndexed())
10969       break;
10970
10971     // No truncation.
10972     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10973       if (St->isTruncatingStore())
10974         break;
10975
10976     // The stored memory type must be the same.
10977     if (Index->getMemoryVT() != MemVT)
10978       break;
10979
10980     // We found a potential memory operand to merge.
10981     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10982
10983     // Find the next memory operand in the chain. If the next operand in the
10984     // chain is a store then move up and continue the scan with the next
10985     // memory operand. If the next operand is a load save it and use alias
10986     // information to check if it interferes with anything.
10987     SDNode *NextInChain = Index->getChain().getNode();
10988     while (1) {
10989       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10990         // We found a store node. Use it for the next iteration.
10991         Index = STn;
10992         break;
10993       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10994         if (Ldn->isVolatile()) {
10995           Index = nullptr;
10996           break;
10997         }
10998
10999         // Save the load node for later. Continue the scan.
11000         AliasLoadNodes.push_back(Ldn);
11001         NextInChain = Ldn->getChain().getNode();
11002         continue;
11003       } else {
11004         Index = nullptr;
11005         break;
11006       }
11007     }
11008   }
11009 }
11010
11011 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11012   if (OptLevel == CodeGenOpt::None)
11013     return false;
11014
11015   EVT MemVT = St->getMemoryVT();
11016   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11017   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11018       Attribute::NoImplicitFloat);
11019
11020   // This function cannot currently deal with non-byte-sized memory sizes.
11021   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11022     return false;
11023
11024   if (!MemVT.isSimple())
11025     return false;
11026
11027   // Perform an early exit check. Do not bother looking at stored values that
11028   // are not constants, loads, or extracted vector elements.
11029   SDValue StoredVal = St->getValue();
11030   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11031   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11032                        isa<ConstantFPSDNode>(StoredVal);
11033   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11034                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11035
11036   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11037     return false;
11038
11039   // Don't merge vectors into wider vectors if the source data comes from loads.
11040   // TODO: This restriction can be lifted by using logic similar to the
11041   // ExtractVecSrc case.
11042   if (MemVT.isVector() && IsLoadSrc)
11043     return false;
11044
11045   // Only look at ends of store sequences.
11046   SDValue Chain = SDValue(St, 0);
11047   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11048     return false;
11049
11050   // Save the LoadSDNodes that we find in the chain.
11051   // We need to make sure that these nodes do not interfere with
11052   // any of the store nodes.
11053   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11054
11055   // Save the StoreSDNodes that we find in the chain.
11056   SmallVector<MemOpLink, 8> StoreNodes;
11057
11058   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11059
11060   // Check if there is anything to merge.
11061   if (StoreNodes.size() < 2)
11062     return false;
11063
11064   // Sort the memory operands according to their distance from the base pointer.
11065   std::sort(StoreNodes.begin(), StoreNodes.end(),
11066             [](MemOpLink LHS, MemOpLink RHS) {
11067     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11068            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11069             LHS.SequenceNum > RHS.SequenceNum);
11070   });
11071
11072   // Scan the memory operations on the chain and find the first non-consecutive
11073   // store memory address.
11074   unsigned LastConsecutiveStore = 0;
11075   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11076   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11077
11078     // Check that the addresses are consecutive starting from the second
11079     // element in the list of stores.
11080     if (i > 0) {
11081       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11082       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11083         break;
11084     }
11085
11086     bool Alias = false;
11087     // Check if this store interferes with any of the loads that we found.
11088     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11089       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11090         Alias = true;
11091         break;
11092       }
11093     // We found a load that alias with this store. Stop the sequence.
11094     if (Alias)
11095       break;
11096
11097     // Mark this node as useful.
11098     LastConsecutiveStore = i;
11099   }
11100
11101   // The node with the lowest store address.
11102   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11103   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11104   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11105   LLVMContext &Context = *DAG.getContext();
11106   const DataLayout &DL = DAG.getDataLayout();
11107
11108   // Store the constants into memory as one consecutive store.
11109   if (IsConstantSrc) {
11110     unsigned LastLegalType = 0;
11111     unsigned LastLegalVectorType = 0;
11112     bool NonZero = false;
11113     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11114       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11115       SDValue StoredVal = St->getValue();
11116
11117       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11118         NonZero |= !C->isNullValue();
11119       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11120         NonZero |= !C->getConstantFPValue()->isNullValue();
11121       } else {
11122         // Non-constant.
11123         break;
11124       }
11125
11126       // Find a legal type for the constant store.
11127       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11128       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11129       bool IsFast;
11130       if (TLI.isTypeLegal(StoreTy) &&
11131           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11132                                  FirstStoreAlign, &IsFast) && IsFast) {
11133         LastLegalType = i+1;
11134       // Or check whether a truncstore is legal.
11135       } else if (TLI.getTypeAction(Context, StoreTy) ==
11136                  TargetLowering::TypePromoteInteger) {
11137         EVT LegalizedStoredValueTy =
11138           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11139         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11140             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11141                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11142             IsFast) {
11143           LastLegalType = i + 1;
11144         }
11145       }
11146
11147       // We only use vectors if the constant is known to be zero or the target
11148       // allows it and the function is not marked with the noimplicitfloat
11149       // attribute.
11150       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11151                                                         FirstStoreAS)) &&
11152           !NoVectors) {
11153         // Find a legal type for the vector store.
11154         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11155         if (TLI.isTypeLegal(Ty) &&
11156             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11157                                    FirstStoreAlign, &IsFast) && IsFast)
11158           LastLegalVectorType = i + 1;
11159       }
11160     }
11161
11162     // Check if we found a legal integer type to store.
11163     if (LastLegalType == 0 && LastLegalVectorType == 0)
11164       return false;
11165
11166     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11167     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11168
11169     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11170                                            true, UseVector);
11171   }
11172
11173   // When extracting multiple vector elements, try to store them
11174   // in one vector store rather than a sequence of scalar stores.
11175   if (IsExtractVecSrc) {
11176     unsigned NumStoresToMerge = 0;
11177     bool IsVec = MemVT.isVector();
11178     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11179       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11180       unsigned StoreValOpcode = St->getValue().getOpcode();
11181       // This restriction could be loosened.
11182       // Bail out if any stored values are not elements extracted from a vector.
11183       // It should be possible to handle mixed sources, but load sources need
11184       // more careful handling (see the block of code below that handles
11185       // consecutive loads).
11186       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11187           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11188         return false;
11189
11190       // Find a legal type for the vector store.
11191       unsigned Elts = i + 1;
11192       if (IsVec) {
11193         // When merging vector stores, get the total number of elements.
11194         Elts *= MemVT.getVectorNumElements();
11195       }
11196       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11197       bool IsFast;
11198       if (TLI.isTypeLegal(Ty) &&
11199           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11200                                  FirstStoreAlign, &IsFast) && IsFast)
11201         NumStoresToMerge = i + 1;
11202     }
11203
11204     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11205                                            false, true);
11206   }
11207
11208   // Below we handle the case of multiple consecutive stores that
11209   // come from multiple consecutive loads. We merge them into a single
11210   // wide load and a single wide store.
11211
11212   // Look for load nodes which are used by the stored values.
11213   SmallVector<MemOpLink, 8> LoadNodes;
11214
11215   // Find acceptable loads. Loads need to have the same chain (token factor),
11216   // must not be zext, volatile, indexed, and they must be consecutive.
11217   BaseIndexOffset LdBasePtr;
11218   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11219     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11220     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11221     if (!Ld) break;
11222
11223     // Loads must only have one use.
11224     if (!Ld->hasNUsesOfValue(1, 0))
11225       break;
11226
11227     // The memory operands must not be volatile.
11228     if (Ld->isVolatile() || Ld->isIndexed())
11229       break;
11230
11231     // We do not accept ext loads.
11232     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11233       break;
11234
11235     // The stored memory type must be the same.
11236     if (Ld->getMemoryVT() != MemVT)
11237       break;
11238
11239     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11240     // If this is not the first ptr that we check.
11241     if (LdBasePtr.Base.getNode()) {
11242       // The base ptr must be the same.
11243       if (!LdPtr.equalBaseIndex(LdBasePtr))
11244         break;
11245     } else {
11246       // Check that all other base pointers are the same as this one.
11247       LdBasePtr = LdPtr;
11248     }
11249
11250     // We found a potential memory operand to merge.
11251     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11252   }
11253
11254   if (LoadNodes.size() < 2)
11255     return false;
11256
11257   // If we have load/store pair instructions and we only have two values,
11258   // don't bother.
11259   unsigned RequiredAlignment;
11260   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11261       St->getAlignment() >= RequiredAlignment)
11262     return false;
11263
11264   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11265   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11266   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11267
11268   // Scan the memory operations on the chain and find the first non-consecutive
11269   // load memory address. These variables hold the index in the store node
11270   // array.
11271   unsigned LastConsecutiveLoad = 0;
11272   // This variable refers to the size and not index in the array.
11273   unsigned LastLegalVectorType = 0;
11274   unsigned LastLegalIntegerType = 0;
11275   StartAddress = LoadNodes[0].OffsetFromBase;
11276   SDValue FirstChain = FirstLoad->getChain();
11277   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11278     // All loads much share the same chain.
11279     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11280       break;
11281
11282     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11283     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11284       break;
11285     LastConsecutiveLoad = i;
11286     // Find a legal type for the vector store.
11287     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11288     bool IsFastSt, IsFastLd;
11289     if (TLI.isTypeLegal(StoreTy) &&
11290         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11291                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11292         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11293                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11294       LastLegalVectorType = i + 1;
11295     }
11296
11297     // Find a legal type for the integer store.
11298     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11299     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11300     if (TLI.isTypeLegal(StoreTy) &&
11301         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11302                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11303         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11304                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11305       LastLegalIntegerType = i + 1;
11306     // Or check whether a truncstore and extload is legal.
11307     else if (TLI.getTypeAction(Context, StoreTy) ==
11308              TargetLowering::TypePromoteInteger) {
11309       EVT LegalizedStoredValueTy =
11310         TLI.getTypeToTransformTo(Context, StoreTy);
11311       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11312           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11313           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11314           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11315           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11316                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11317           IsFastSt &&
11318           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11319                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11320           IsFastLd)
11321         LastLegalIntegerType = i+1;
11322     }
11323   }
11324
11325   // Only use vector types if the vector type is larger than the integer type.
11326   // If they are the same, use integers.
11327   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11328   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11329
11330   // We add +1 here because the LastXXX variables refer to location while
11331   // the NumElem refers to array/index size.
11332   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11333   NumElem = std::min(LastLegalType, NumElem);
11334
11335   if (NumElem < 2)
11336     return false;
11337
11338   // Collect the chains from all merged stores.
11339   SmallVector<SDValue, 8> MergeStoreChains;
11340   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11341
11342   // The latest Node in the DAG.
11343   unsigned LatestNodeUsed = 0;
11344   for (unsigned i=1; i<NumElem; ++i) {
11345     // Find a chain for the new wide-store operand. Notice that some
11346     // of the store nodes that we found may not be selected for inclusion
11347     // in the wide store. The chain we use needs to be the chain of the
11348     // latest store node which is *used* and replaced by the wide store.
11349     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11350       LatestNodeUsed = i;
11351
11352     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11353   }
11354
11355   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11356
11357   // Find if it is better to use vectors or integers to load and store
11358   // to memory.
11359   EVT JointMemOpVT;
11360   if (UseVectorTy) {
11361     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11362   } else {
11363     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11364     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11365   }
11366
11367   SDLoc LoadDL(LoadNodes[0].MemNode);
11368   SDLoc StoreDL(StoreNodes[0].MemNode);
11369
11370   // The merged loads are required to have the same chain, so using the first's
11371   // chain is acceptable.
11372   SDValue NewLoad = DAG.getLoad(
11373       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11374       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11375
11376   SDValue NewStoreChain =
11377     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11378
11379   SDValue NewStore = DAG.getStore(
11380     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11381       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11382
11383   // Replace one of the loads with the new load.
11384   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11385   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11386                                 SDValue(NewLoad.getNode(), 1));
11387
11388   // Remove the rest of the load chains.
11389   for (unsigned i = 1; i < NumElem ; ++i) {
11390     // Replace all chain users of the old load nodes with the chain of the new
11391     // load node.
11392     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11393     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11394   }
11395
11396   // Replace the last store with the new store.
11397   CombineTo(LatestOp, NewStore);
11398   // Erase all other stores.
11399   for (unsigned i = 0; i < NumElem ; ++i) {
11400     // Remove all Store nodes.
11401     if (StoreNodes[i].MemNode == LatestOp)
11402       continue;
11403     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11404     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11405     deleteAndRecombine(St);
11406   }
11407
11408   return true;
11409 }
11410
11411 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11412   SDLoc SL(ST);
11413   SDValue ReplStore;
11414
11415   // Replace the chain to avoid dependency.
11416   if (ST->isTruncatingStore()) {
11417     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11418                                   ST->getBasePtr(), ST->getMemoryVT(),
11419                                   ST->getMemOperand());
11420   } else {
11421     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11422                              ST->getMemOperand());
11423   }
11424
11425   // Create token to keep both nodes around.
11426   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11427                               MVT::Other, ST->getChain(), ReplStore);
11428
11429   // Make sure the new and old chains are cleaned up.
11430   AddToWorklist(Token.getNode());
11431
11432   // Don't add users to work list.
11433   return CombineTo(ST, Token, false);
11434 }
11435
11436 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11437   SDValue Value = ST->getValue();
11438   if (Value.getOpcode() == ISD::TargetConstantFP)
11439     return SDValue();
11440
11441   SDLoc DL(ST);
11442
11443   SDValue Chain = ST->getChain();
11444   SDValue Ptr = ST->getBasePtr();
11445
11446   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11447
11448   // NOTE: If the original store is volatile, this transform must not increase
11449   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11450   // processor operation but an i64 (which is not legal) requires two.  So the
11451   // transform should not be done in this case.
11452
11453   SDValue Tmp;
11454   switch (CFP->getSimpleValueType(0).SimpleTy) {
11455   default:
11456     llvm_unreachable("Unknown FP type");
11457   case MVT::f16:    // We don't do this for these yet.
11458   case MVT::f80:
11459   case MVT::f128:
11460   case MVT::ppcf128:
11461     return SDValue();
11462   case MVT::f32:
11463     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11464         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11465       ;
11466       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11467                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11468                             MVT::i32);
11469       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11470     }
11471
11472     return SDValue();
11473   case MVT::f64:
11474     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11475          !ST->isVolatile()) ||
11476         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11477       ;
11478       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11479                             getZExtValue(), SDLoc(CFP), MVT::i64);
11480       return DAG.getStore(Chain, DL, Tmp,
11481                           Ptr, ST->getMemOperand());
11482     }
11483
11484     if (!ST->isVolatile() &&
11485         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11486       // Many FP stores are not made apparent until after legalize, e.g. for
11487       // argument passing.  Since this is so common, custom legalize the
11488       // 64-bit integer store into two 32-bit stores.
11489       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11490       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11491       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11492       if (DAG.getDataLayout().isBigEndian())
11493         std::swap(Lo, Hi);
11494
11495       unsigned Alignment = ST->getAlignment();
11496       bool isVolatile = ST->isVolatile();
11497       bool isNonTemporal = ST->isNonTemporal();
11498       AAMDNodes AAInfo = ST->getAAInfo();
11499
11500       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11501                                  Ptr, ST->getPointerInfo(),
11502                                  isVolatile, isNonTemporal,
11503                                  ST->getAlignment(), AAInfo);
11504       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11505                         DAG.getConstant(4, DL, Ptr.getValueType()));
11506       Alignment = MinAlign(Alignment, 4U);
11507       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11508                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11509                                  isVolatile, isNonTemporal,
11510                                  Alignment, AAInfo);
11511       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11512                          St0, St1);
11513     }
11514
11515     return SDValue();
11516   }
11517 }
11518
11519 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11520   StoreSDNode *ST  = cast<StoreSDNode>(N);
11521   SDValue Chain = ST->getChain();
11522   SDValue Value = ST->getValue();
11523   SDValue Ptr   = ST->getBasePtr();
11524
11525   // If this is a store of a bit convert, store the input value if the
11526   // resultant store does not need a higher alignment than the original.
11527   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11528       ST->isUnindexed()) {
11529     unsigned OrigAlign = ST->getAlignment();
11530     EVT SVT = Value.getOperand(0).getValueType();
11531     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11532         SVT.getTypeForEVT(*DAG.getContext()));
11533     if (Align <= OrigAlign &&
11534         ((!LegalOperations && !ST->isVolatile()) ||
11535          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11536       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11537                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11538                           ST->isNonTemporal(), OrigAlign,
11539                           ST->getAAInfo());
11540   }
11541
11542   // Turn 'store undef, Ptr' -> nothing.
11543   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11544     return Chain;
11545
11546   // Try to infer better alignment information than the store already has.
11547   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11548     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11549       if (Align > ST->getAlignment()) {
11550         SDValue NewStore =
11551                DAG.getTruncStore(Chain, SDLoc(N), Value,
11552                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11553                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11554                                  ST->getAAInfo());
11555         if (NewStore.getNode() != N)
11556           return CombineTo(ST, NewStore, true);
11557       }
11558     }
11559   }
11560
11561   // Try transforming a pair floating point load / store ops to integer
11562   // load / store ops.
11563   if (SDValue NewST = TransformFPLoadStorePair(N))
11564     return NewST;
11565
11566   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11567                                                   : DAG.getSubtarget().useAA();
11568 #ifndef NDEBUG
11569   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11570       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11571     UseAA = false;
11572 #endif
11573   if (UseAA && ST->isUnindexed()) {
11574     // FIXME: We should do this even without AA enabled. AA will just allow
11575     // FindBetterChain to work in more situations. The problem with this is that
11576     // any combine that expects memory operations to be on consecutive chains
11577     // first needs to be updated to look for users of the same chain.
11578
11579     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11580     // adjacent stores.
11581     if (findBetterNeighborChains(ST)) {
11582       // replaceStoreChain uses CombineTo, which handled all of the worklist
11583       // manipulation. Return the original node to not do anything else.
11584       return SDValue(ST, 0);
11585     }
11586   }
11587
11588   // Try transforming N to an indexed store.
11589   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11590     return SDValue(N, 0);
11591
11592   // FIXME: is there such a thing as a truncating indexed store?
11593   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11594       Value.getValueType().isInteger()) {
11595     // See if we can simplify the input to this truncstore with knowledge that
11596     // only the low bits are being used.  For example:
11597     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11598     SDValue Shorter =
11599       GetDemandedBits(Value,
11600                       APInt::getLowBitsSet(
11601                         Value.getValueType().getScalarType().getSizeInBits(),
11602                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11603     AddToWorklist(Value.getNode());
11604     if (Shorter.getNode())
11605       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11606                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11607
11608     // Otherwise, see if we can simplify the operation with
11609     // SimplifyDemandedBits, which only works if the value has a single use.
11610     if (SimplifyDemandedBits(Value,
11611                         APInt::getLowBitsSet(
11612                           Value.getValueType().getScalarType().getSizeInBits(),
11613                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11614       return SDValue(N, 0);
11615   }
11616
11617   // If this is a load followed by a store to the same location, then the store
11618   // is dead/noop.
11619   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11620     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11621         ST->isUnindexed() && !ST->isVolatile() &&
11622         // There can't be any side effects between the load and store, such as
11623         // a call or store.
11624         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11625       // The store is dead, remove it.
11626       return Chain;
11627     }
11628   }
11629
11630   // If this is a store followed by a store with the same value to the same
11631   // location, then the store is dead/noop.
11632   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11633     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11634         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11635         ST1->isUnindexed() && !ST1->isVolatile()) {
11636       // The store is dead, remove it.
11637       return Chain;
11638     }
11639   }
11640
11641   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11642   // truncating store.  We can do this even if this is already a truncstore.
11643   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11644       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11645       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11646                             ST->getMemoryVT())) {
11647     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11648                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11649   }
11650
11651   // Only perform this optimization before the types are legal, because we
11652   // don't want to perform this optimization on every DAGCombine invocation.
11653   if (!LegalTypes) {
11654     bool EverChanged = false;
11655
11656     do {
11657       // There can be multiple store sequences on the same chain.
11658       // Keep trying to merge store sequences until we are unable to do so
11659       // or until we merge the last store on the chain.
11660       bool Changed = MergeConsecutiveStores(ST);
11661       EverChanged |= Changed;
11662       if (!Changed) break;
11663     } while (ST->getOpcode() != ISD::DELETED_NODE);
11664
11665     if (EverChanged)
11666       return SDValue(N, 0);
11667   }
11668
11669   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11670   //
11671   // Make sure to do this only after attempting to merge stores in order to
11672   //  avoid changing the types of some subset of stores due to visit order,
11673   //  preventing their merging.
11674   if (isa<ConstantFPSDNode>(Value)) {
11675     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11676       return NewSt;
11677   }
11678
11679   return ReduceLoadOpStoreWidth(N);
11680 }
11681
11682 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11683   SDValue InVec = N->getOperand(0);
11684   SDValue InVal = N->getOperand(1);
11685   SDValue EltNo = N->getOperand(2);
11686   SDLoc dl(N);
11687
11688   // If the inserted element is an UNDEF, just use the input vector.
11689   if (InVal.getOpcode() == ISD::UNDEF)
11690     return InVec;
11691
11692   EVT VT = InVec.getValueType();
11693
11694   // If we can't generate a legal BUILD_VECTOR, exit
11695   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11696     return SDValue();
11697
11698   // Check that we know which element is being inserted
11699   if (!isa<ConstantSDNode>(EltNo))
11700     return SDValue();
11701   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11702
11703   // Canonicalize insert_vector_elt dag nodes.
11704   // Example:
11705   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11706   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11707   //
11708   // Do this only if the child insert_vector node has one use; also
11709   // do this only if indices are both constants and Idx1 < Idx0.
11710   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11711       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11712     unsigned OtherElt =
11713       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11714     if (Elt < OtherElt) {
11715       // Swap nodes.
11716       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11717                                   InVec.getOperand(0), InVal, EltNo);
11718       AddToWorklist(NewOp.getNode());
11719       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11720                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11721     }
11722   }
11723
11724   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11725   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11726   // vector elements.
11727   SmallVector<SDValue, 8> Ops;
11728   // Do not combine these two vectors if the output vector will not replace
11729   // the input vector.
11730   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11731     Ops.append(InVec.getNode()->op_begin(),
11732                InVec.getNode()->op_end());
11733   } else if (InVec.getOpcode() == ISD::UNDEF) {
11734     unsigned NElts = VT.getVectorNumElements();
11735     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11736   } else {
11737     return SDValue();
11738   }
11739
11740   // Insert the element
11741   if (Elt < Ops.size()) {
11742     // All the operands of BUILD_VECTOR must have the same type;
11743     // we enforce that here.
11744     EVT OpVT = Ops[0].getValueType();
11745     if (InVal.getValueType() != OpVT)
11746       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11747                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11748                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11749     Ops[Elt] = InVal;
11750   }
11751
11752   // Return the new vector
11753   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11754 }
11755
11756 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11757     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11758   EVT ResultVT = EVE->getValueType(0);
11759   EVT VecEltVT = InVecVT.getVectorElementType();
11760   unsigned Align = OriginalLoad->getAlignment();
11761   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11762       VecEltVT.getTypeForEVT(*DAG.getContext()));
11763
11764   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11765     return SDValue();
11766
11767   Align = NewAlign;
11768
11769   SDValue NewPtr = OriginalLoad->getBasePtr();
11770   SDValue Offset;
11771   EVT PtrType = NewPtr.getValueType();
11772   MachinePointerInfo MPI;
11773   SDLoc DL(EVE);
11774   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11775     int Elt = ConstEltNo->getZExtValue();
11776     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11777     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11778     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11779   } else {
11780     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11781     Offset = DAG.getNode(
11782         ISD::MUL, DL, PtrType, Offset,
11783         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11784     MPI = OriginalLoad->getPointerInfo();
11785   }
11786   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11787
11788   // The replacement we need to do here is a little tricky: we need to
11789   // replace an extractelement of a load with a load.
11790   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11791   // Note that this replacement assumes that the extractvalue is the only
11792   // use of the load; that's okay because we don't want to perform this
11793   // transformation in other cases anyway.
11794   SDValue Load;
11795   SDValue Chain;
11796   if (ResultVT.bitsGT(VecEltVT)) {
11797     // If the result type of vextract is wider than the load, then issue an
11798     // extending load instead.
11799     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11800                                                   VecEltVT)
11801                                    ? ISD::ZEXTLOAD
11802                                    : ISD::EXTLOAD;
11803     Load = DAG.getExtLoad(
11804         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11805         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11806         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11807     Chain = Load.getValue(1);
11808   } else {
11809     Load = DAG.getLoad(
11810         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11811         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11812         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11813     Chain = Load.getValue(1);
11814     if (ResultVT.bitsLT(VecEltVT))
11815       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11816     else
11817       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11818   }
11819   WorklistRemover DeadNodes(*this);
11820   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11821   SDValue To[] = { Load, Chain };
11822   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11823   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11824   // worklist explicitly as well.
11825   AddToWorklist(Load.getNode());
11826   AddUsersToWorklist(Load.getNode()); // Add users too
11827   // Make sure to revisit this node to clean it up; it will usually be dead.
11828   AddToWorklist(EVE);
11829   ++OpsNarrowed;
11830   return SDValue(EVE, 0);
11831 }
11832
11833 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11834   // (vextract (scalar_to_vector val, 0) -> val
11835   SDValue InVec = N->getOperand(0);
11836   EVT VT = InVec.getValueType();
11837   EVT NVT = N->getValueType(0);
11838
11839   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11840     // Check if the result type doesn't match the inserted element type. A
11841     // SCALAR_TO_VECTOR may truncate the inserted element and the
11842     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11843     SDValue InOp = InVec.getOperand(0);
11844     if (InOp.getValueType() != NVT) {
11845       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11846       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11847     }
11848     return InOp;
11849   }
11850
11851   SDValue EltNo = N->getOperand(1);
11852   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
11853
11854   // extract_vector_elt (build_vector x, y), 1 -> y
11855   if (ConstEltNo &&
11856       InVec.getOpcode() == ISD::BUILD_VECTOR &&
11857       TLI.isTypeLegal(VT) &&
11858       (InVec.hasOneUse() ||
11859        TLI.aggressivelyPreferBuildVectorSources(VT))) {
11860     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
11861     EVT InEltVT = Elt.getValueType();
11862
11863     // Sometimes build_vector's scalar input types do not match result type.
11864     if (NVT == InEltVT)
11865       return Elt;
11866
11867     // TODO: It may be useful to truncate if free if the build_vector implicitly
11868     // converts.
11869   }
11870
11871   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11872   // We only perform this optimization before the op legalization phase because
11873   // we may introduce new vector instructions which are not backed by TD
11874   // patterns. For example on AVX, extracting elements from a wide vector
11875   // without using extract_subvector. However, if we can find an underlying
11876   // scalar value, then we can always use that.
11877   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
11878     int NumElem = VT.getVectorNumElements();
11879     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11880     // Find the new index to extract from.
11881     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
11882
11883     // Extracting an undef index is undef.
11884     if (OrigElt == -1)
11885       return DAG.getUNDEF(NVT);
11886
11887     // Select the right vector half to extract from.
11888     SDValue SVInVec;
11889     if (OrigElt < NumElem) {
11890       SVInVec = InVec->getOperand(0);
11891     } else {
11892       SVInVec = InVec->getOperand(1);
11893       OrigElt -= NumElem;
11894     }
11895
11896     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11897       SDValue InOp = SVInVec.getOperand(OrigElt);
11898       if (InOp.getValueType() != NVT) {
11899         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11900         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11901       }
11902
11903       return InOp;
11904     }
11905
11906     // FIXME: We should handle recursing on other vector shuffles and
11907     // scalar_to_vector here as well.
11908
11909     if (!LegalOperations) {
11910       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11911       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11912                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11913     }
11914   }
11915
11916   bool BCNumEltsChanged = false;
11917   EVT ExtVT = VT.getVectorElementType();
11918   EVT LVT = ExtVT;
11919
11920   // If the result of load has to be truncated, then it's not necessarily
11921   // profitable.
11922   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11923     return SDValue();
11924
11925   if (InVec.getOpcode() == ISD::BITCAST) {
11926     // Don't duplicate a load with other uses.
11927     if (!InVec.hasOneUse())
11928       return SDValue();
11929
11930     EVT BCVT = InVec.getOperand(0).getValueType();
11931     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11932       return SDValue();
11933     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11934       BCNumEltsChanged = true;
11935     InVec = InVec.getOperand(0);
11936     ExtVT = BCVT.getVectorElementType();
11937   }
11938
11939   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11940   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11941       ISD::isNormalLoad(InVec.getNode()) &&
11942       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11943     SDValue Index = N->getOperand(1);
11944     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11945       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11946                                                            OrigLoad);
11947   }
11948
11949   // Perform only after legalization to ensure build_vector / vector_shuffle
11950   // optimizations have already been done.
11951   if (!LegalOperations) return SDValue();
11952
11953   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11954   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11955   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11956
11957   if (ConstEltNo) {
11958     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11959
11960     LoadSDNode *LN0 = nullptr;
11961     const ShuffleVectorSDNode *SVN = nullptr;
11962     if (ISD::isNormalLoad(InVec.getNode())) {
11963       LN0 = cast<LoadSDNode>(InVec);
11964     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11965                InVec.getOperand(0).getValueType() == ExtVT &&
11966                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11967       // Don't duplicate a load with other uses.
11968       if (!InVec.hasOneUse())
11969         return SDValue();
11970
11971       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11972     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11973       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11974       // =>
11975       // (load $addr+1*size)
11976
11977       // Don't duplicate a load with other uses.
11978       if (!InVec.hasOneUse())
11979         return SDValue();
11980
11981       // If the bit convert changed the number of elements, it is unsafe
11982       // to examine the mask.
11983       if (BCNumEltsChanged)
11984         return SDValue();
11985
11986       // Select the input vector, guarding against out of range extract vector.
11987       unsigned NumElems = VT.getVectorNumElements();
11988       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11989       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11990
11991       if (InVec.getOpcode() == ISD::BITCAST) {
11992         // Don't duplicate a load with other uses.
11993         if (!InVec.hasOneUse())
11994           return SDValue();
11995
11996         InVec = InVec.getOperand(0);
11997       }
11998       if (ISD::isNormalLoad(InVec.getNode())) {
11999         LN0 = cast<LoadSDNode>(InVec);
12000         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12001         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12002       }
12003     }
12004
12005     // Make sure we found a non-volatile load and the extractelement is
12006     // the only use.
12007     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12008       return SDValue();
12009
12010     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12011     if (Elt == -1)
12012       return DAG.getUNDEF(LVT);
12013
12014     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12015   }
12016
12017   return SDValue();
12018 }
12019
12020 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12021 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12022   // We perform this optimization post type-legalization because
12023   // the type-legalizer often scalarizes integer-promoted vectors.
12024   // Performing this optimization before may create bit-casts which
12025   // will be type-legalized to complex code sequences.
12026   // We perform this optimization only before the operation legalizer because we
12027   // may introduce illegal operations.
12028   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12029     return SDValue();
12030
12031   unsigned NumInScalars = N->getNumOperands();
12032   SDLoc dl(N);
12033   EVT VT = N->getValueType(0);
12034
12035   // Check to see if this is a BUILD_VECTOR of a bunch of values
12036   // which come from any_extend or zero_extend nodes. If so, we can create
12037   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12038   // optimizations. We do not handle sign-extend because we can't fill the sign
12039   // using shuffles.
12040   EVT SourceType = MVT::Other;
12041   bool AllAnyExt = true;
12042
12043   for (unsigned i = 0; i != NumInScalars; ++i) {
12044     SDValue In = N->getOperand(i);
12045     // Ignore undef inputs.
12046     if (In.getOpcode() == ISD::UNDEF) continue;
12047
12048     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12049     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12050
12051     // Abort if the element is not an extension.
12052     if (!ZeroExt && !AnyExt) {
12053       SourceType = MVT::Other;
12054       break;
12055     }
12056
12057     // The input is a ZeroExt or AnyExt. Check the original type.
12058     EVT InTy = In.getOperand(0).getValueType();
12059
12060     // Check that all of the widened source types are the same.
12061     if (SourceType == MVT::Other)
12062       // First time.
12063       SourceType = InTy;
12064     else if (InTy != SourceType) {
12065       // Multiple income types. Abort.
12066       SourceType = MVT::Other;
12067       break;
12068     }
12069
12070     // Check if all of the extends are ANY_EXTENDs.
12071     AllAnyExt &= AnyExt;
12072   }
12073
12074   // In order to have valid types, all of the inputs must be extended from the
12075   // same source type and all of the inputs must be any or zero extend.
12076   // Scalar sizes must be a power of two.
12077   EVT OutScalarTy = VT.getScalarType();
12078   bool ValidTypes = SourceType != MVT::Other &&
12079                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12080                  isPowerOf2_32(SourceType.getSizeInBits());
12081
12082   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12083   // turn into a single shuffle instruction.
12084   if (!ValidTypes)
12085     return SDValue();
12086
12087   bool isLE = DAG.getDataLayout().isLittleEndian();
12088   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12089   assert(ElemRatio > 1 && "Invalid element size ratio");
12090   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12091                                DAG.getConstant(0, SDLoc(N), SourceType);
12092
12093   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12094   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12095
12096   // Populate the new build_vector
12097   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12098     SDValue Cast = N->getOperand(i);
12099     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12100             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12101             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12102     SDValue In;
12103     if (Cast.getOpcode() == ISD::UNDEF)
12104       In = DAG.getUNDEF(SourceType);
12105     else
12106       In = Cast->getOperand(0);
12107     unsigned Index = isLE ? (i * ElemRatio) :
12108                             (i * ElemRatio + (ElemRatio - 1));
12109
12110     assert(Index < Ops.size() && "Invalid index");
12111     Ops[Index] = In;
12112   }
12113
12114   // The type of the new BUILD_VECTOR node.
12115   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12116   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12117          "Invalid vector size");
12118   // Check if the new vector type is legal.
12119   if (!isTypeLegal(VecVT)) return SDValue();
12120
12121   // Make the new BUILD_VECTOR.
12122   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12123
12124   // The new BUILD_VECTOR node has the potential to be further optimized.
12125   AddToWorklist(BV.getNode());
12126   // Bitcast to the desired type.
12127   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12128 }
12129
12130 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12131   EVT VT = N->getValueType(0);
12132
12133   unsigned NumInScalars = N->getNumOperands();
12134   SDLoc dl(N);
12135
12136   EVT SrcVT = MVT::Other;
12137   unsigned Opcode = ISD::DELETED_NODE;
12138   unsigned NumDefs = 0;
12139
12140   for (unsigned i = 0; i != NumInScalars; ++i) {
12141     SDValue In = N->getOperand(i);
12142     unsigned Opc = In.getOpcode();
12143
12144     if (Opc == ISD::UNDEF)
12145       continue;
12146
12147     // If all scalar values are floats and converted from integers.
12148     if (Opcode == ISD::DELETED_NODE &&
12149         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12150       Opcode = Opc;
12151     }
12152
12153     if (Opc != Opcode)
12154       return SDValue();
12155
12156     EVT InVT = In.getOperand(0).getValueType();
12157
12158     // If all scalar values are typed differently, bail out. It's chosen to
12159     // simplify BUILD_VECTOR of integer types.
12160     if (SrcVT == MVT::Other)
12161       SrcVT = InVT;
12162     if (SrcVT != InVT)
12163       return SDValue();
12164     NumDefs++;
12165   }
12166
12167   // If the vector has just one element defined, it's not worth to fold it into
12168   // a vectorized one.
12169   if (NumDefs < 2)
12170     return SDValue();
12171
12172   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12173          && "Should only handle conversion from integer to float.");
12174   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12175
12176   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12177
12178   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12179     return SDValue();
12180
12181   // Just because the floating-point vector type is legal does not necessarily
12182   // mean that the corresponding integer vector type is.
12183   if (!isTypeLegal(NVT))
12184     return SDValue();
12185
12186   SmallVector<SDValue, 8> Opnds;
12187   for (unsigned i = 0; i != NumInScalars; ++i) {
12188     SDValue In = N->getOperand(i);
12189
12190     if (In.getOpcode() == ISD::UNDEF)
12191       Opnds.push_back(DAG.getUNDEF(SrcVT));
12192     else
12193       Opnds.push_back(In.getOperand(0));
12194   }
12195   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12196   AddToWorklist(BV.getNode());
12197
12198   return DAG.getNode(Opcode, dl, VT, BV);
12199 }
12200
12201 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12202   unsigned NumInScalars = N->getNumOperands();
12203   SDLoc dl(N);
12204   EVT VT = N->getValueType(0);
12205
12206   // A vector built entirely of undefs is undef.
12207   if (ISD::allOperandsUndef(N))
12208     return DAG.getUNDEF(VT);
12209
12210   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12211     return V;
12212
12213   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12214     return V;
12215
12216   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12217   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12218   // at most two distinct vectors, turn this into a shuffle node.
12219
12220   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12221   if (!isTypeLegal(VT))
12222     return SDValue();
12223
12224   // May only combine to shuffle after legalize if shuffle is legal.
12225   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12226     return SDValue();
12227
12228   SDValue VecIn1, VecIn2;
12229   bool UsesZeroVector = false;
12230   for (unsigned i = 0; i != NumInScalars; ++i) {
12231     SDValue Op = N->getOperand(i);
12232     // Ignore undef inputs.
12233     if (Op.getOpcode() == ISD::UNDEF) continue;
12234
12235     // See if we can combine this build_vector into a blend with a zero vector.
12236     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12237       UsesZeroVector = true;
12238       continue;
12239     }
12240
12241     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12242     // constant index, bail out.
12243     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12244         !isa<ConstantSDNode>(Op.getOperand(1))) {
12245       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12246       break;
12247     }
12248
12249     // We allow up to two distinct input vectors.
12250     SDValue ExtractedFromVec = Op.getOperand(0);
12251     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12252       continue;
12253
12254     if (!VecIn1.getNode()) {
12255       VecIn1 = ExtractedFromVec;
12256     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12257       VecIn2 = ExtractedFromVec;
12258     } else {
12259       // Too many inputs.
12260       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12261       break;
12262     }
12263   }
12264
12265   // If everything is good, we can make a shuffle operation.
12266   if (VecIn1.getNode()) {
12267     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12268     SmallVector<int, 8> Mask;
12269     for (unsigned i = 0; i != NumInScalars; ++i) {
12270       unsigned Opcode = N->getOperand(i).getOpcode();
12271       if (Opcode == ISD::UNDEF) {
12272         Mask.push_back(-1);
12273         continue;
12274       }
12275
12276       // Operands can also be zero.
12277       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12278         assert(UsesZeroVector &&
12279                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12280                "Unexpected node found!");
12281         Mask.push_back(NumInScalars+i);
12282         continue;
12283       }
12284
12285       // If extracting from the first vector, just use the index directly.
12286       SDValue Extract = N->getOperand(i);
12287       SDValue ExtVal = Extract.getOperand(1);
12288       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12289       if (Extract.getOperand(0) == VecIn1) {
12290         Mask.push_back(ExtIndex);
12291         continue;
12292       }
12293
12294       // Otherwise, use InIdx + InputVecSize
12295       Mask.push_back(InNumElements + ExtIndex);
12296     }
12297
12298     // Avoid introducing illegal shuffles with zero.
12299     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12300       return SDValue();
12301
12302     // We can't generate a shuffle node with mismatched input and output types.
12303     // Attempt to transform a single input vector to the correct type.
12304     if ((VT != VecIn1.getValueType())) {
12305       // If the input vector type has a different base type to the output
12306       // vector type, bail out.
12307       EVT VTElemType = VT.getVectorElementType();
12308       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12309           (VecIn2.getNode() &&
12310            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12311         return SDValue();
12312
12313       // If the input vector is too small, widen it.
12314       // We only support widening of vectors which are half the size of the
12315       // output registers. For example XMM->YMM widening on X86 with AVX.
12316       EVT VecInT = VecIn1.getValueType();
12317       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12318         // If we only have one small input, widen it by adding undef values.
12319         if (!VecIn2.getNode())
12320           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12321                                DAG.getUNDEF(VecIn1.getValueType()));
12322         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12323           // If we have two small inputs of the same type, try to concat them.
12324           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12325           VecIn2 = SDValue(nullptr, 0);
12326         } else
12327           return SDValue();
12328       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12329         // If the input vector is too large, try to split it.
12330         // We don't support having two input vectors that are too large.
12331         // If the zero vector was used, we can not split the vector,
12332         // since we'd need 3 inputs.
12333         if (UsesZeroVector || VecIn2.getNode())
12334           return SDValue();
12335
12336         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12337           return SDValue();
12338
12339         // Try to replace VecIn1 with two extract_subvectors
12340         // No need to update the masks, they should still be correct.
12341         VecIn2 = DAG.getNode(
12342             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12343             DAG.getConstant(VT.getVectorNumElements(), dl,
12344                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12345         VecIn1 = DAG.getNode(
12346             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12347             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12348       } else
12349         return SDValue();
12350     }
12351
12352     if (UsesZeroVector)
12353       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12354                                 DAG.getConstantFP(0.0, dl, VT);
12355     else
12356       // If VecIn2 is unused then change it to undef.
12357       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12358
12359     // Check that we were able to transform all incoming values to the same
12360     // type.
12361     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12362         VecIn1.getValueType() != VT)
12363           return SDValue();
12364
12365     // Return the new VECTOR_SHUFFLE node.
12366     SDValue Ops[2];
12367     Ops[0] = VecIn1;
12368     Ops[1] = VecIn2;
12369     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12370   }
12371
12372   return SDValue();
12373 }
12374
12375 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12376   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12377   EVT OpVT = N->getOperand(0).getValueType();
12378
12379   // If the operands are legal vectors, leave them alone.
12380   if (TLI.isTypeLegal(OpVT))
12381     return SDValue();
12382
12383   SDLoc DL(N);
12384   EVT VT = N->getValueType(0);
12385   SmallVector<SDValue, 8> Ops;
12386
12387   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12388   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12389
12390   // Keep track of what we encounter.
12391   bool AnyInteger = false;
12392   bool AnyFP = false;
12393   for (const SDValue &Op : N->ops()) {
12394     if (ISD::BITCAST == Op.getOpcode() &&
12395         !Op.getOperand(0).getValueType().isVector())
12396       Ops.push_back(Op.getOperand(0));
12397     else if (ISD::UNDEF == Op.getOpcode())
12398       Ops.push_back(ScalarUndef);
12399     else
12400       return SDValue();
12401
12402     // Note whether we encounter an integer or floating point scalar.
12403     // If it's neither, bail out, it could be something weird like x86mmx.
12404     EVT LastOpVT = Ops.back().getValueType();
12405     if (LastOpVT.isFloatingPoint())
12406       AnyFP = true;
12407     else if (LastOpVT.isInteger())
12408       AnyInteger = true;
12409     else
12410       return SDValue();
12411   }
12412
12413   // If any of the operands is a floating point scalar bitcast to a vector,
12414   // use floating point types throughout, and bitcast everything.
12415   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12416   if (AnyFP) {
12417     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12418     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12419     if (AnyInteger) {
12420       for (SDValue &Op : Ops) {
12421         if (Op.getValueType() == SVT)
12422           continue;
12423         if (Op.getOpcode() == ISD::UNDEF)
12424           Op = ScalarUndef;
12425         else
12426           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12427       }
12428     }
12429   }
12430
12431   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12432                                VT.getSizeInBits() / SVT.getSizeInBits());
12433   return DAG.getNode(ISD::BITCAST, DL, VT,
12434                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12435 }
12436
12437 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12438 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12439 // most two distinct vectors the same size as the result, attempt to turn this
12440 // into a legal shuffle.
12441 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12442   EVT VT = N->getValueType(0);
12443   EVT OpVT = N->getOperand(0).getValueType();
12444   int NumElts = VT.getVectorNumElements();
12445   int NumOpElts = OpVT.getVectorNumElements();
12446
12447   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12448   SmallVector<int, 8> Mask;
12449
12450   for (SDValue Op : N->ops()) {
12451     // Peek through any bitcast.
12452     while (Op.getOpcode() == ISD::BITCAST)
12453       Op = Op.getOperand(0);
12454
12455     // UNDEF nodes convert to UNDEF shuffle mask values.
12456     if (Op.getOpcode() == ISD::UNDEF) {
12457       Mask.append((unsigned)NumOpElts, -1);
12458       continue;
12459     }
12460
12461     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12462       return SDValue();
12463
12464     // What vector are we extracting the subvector from and at what index?
12465     SDValue ExtVec = Op.getOperand(0);
12466
12467     // We want the EVT of the original extraction to correctly scale the
12468     // extraction index.
12469     EVT ExtVT = ExtVec.getValueType();
12470
12471     // Peek through any bitcast.
12472     while (ExtVec.getOpcode() == ISD::BITCAST)
12473       ExtVec = ExtVec.getOperand(0);
12474
12475     // UNDEF nodes convert to UNDEF shuffle mask values.
12476     if (ExtVec.getOpcode() == ISD::UNDEF) {
12477       Mask.append((unsigned)NumOpElts, -1);
12478       continue;
12479     }
12480
12481     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12482       return SDValue();
12483     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12484
12485     // Ensure that we are extracting a subvector from a vector the same
12486     // size as the result.
12487     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12488       return SDValue();
12489
12490     // Scale the subvector index to account for any bitcast.
12491     int NumExtElts = ExtVT.getVectorNumElements();
12492     if (0 == (NumExtElts % NumElts))
12493       ExtIdx /= (NumExtElts / NumElts);
12494     else if (0 == (NumElts % NumExtElts))
12495       ExtIdx *= (NumElts / NumExtElts);
12496     else
12497       return SDValue();
12498
12499     // At most we can reference 2 inputs in the final shuffle.
12500     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12501       SV0 = ExtVec;
12502       for (int i = 0; i != NumOpElts; ++i)
12503         Mask.push_back(i + ExtIdx);
12504     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12505       SV1 = ExtVec;
12506       for (int i = 0; i != NumOpElts; ++i)
12507         Mask.push_back(i + ExtIdx + NumElts);
12508     } else {
12509       return SDValue();
12510     }
12511   }
12512
12513   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12514     return SDValue();
12515
12516   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12517                               DAG.getBitcast(VT, SV1), Mask);
12518 }
12519
12520 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12521   // If we only have one input vector, we don't need to do any concatenation.
12522   if (N->getNumOperands() == 1)
12523     return N->getOperand(0);
12524
12525   // Check if all of the operands are undefs.
12526   EVT VT = N->getValueType(0);
12527   if (ISD::allOperandsUndef(N))
12528     return DAG.getUNDEF(VT);
12529
12530   // Optimize concat_vectors where all but the first of the vectors are undef.
12531   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12532         return Op.getOpcode() == ISD::UNDEF;
12533       })) {
12534     SDValue In = N->getOperand(0);
12535     assert(In.getValueType().isVector() && "Must concat vectors");
12536
12537     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12538     if (In->getOpcode() == ISD::BITCAST &&
12539         !In->getOperand(0)->getValueType(0).isVector()) {
12540       SDValue Scalar = In->getOperand(0);
12541
12542       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12543       // look through the trunc so we can still do the transform:
12544       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12545       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12546           !TLI.isTypeLegal(Scalar.getValueType()) &&
12547           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12548         Scalar = Scalar->getOperand(0);
12549
12550       EVT SclTy = Scalar->getValueType(0);
12551
12552       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12553         return SDValue();
12554
12555       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12556                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12557       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12558         return SDValue();
12559
12560       SDLoc dl = SDLoc(N);
12561       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12562       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12563     }
12564   }
12565
12566   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12567   // We have already tested above for an UNDEF only concatenation.
12568   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12569   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12570   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12571     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12572   };
12573   bool AllBuildVectorsOrUndefs =
12574       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12575   if (AllBuildVectorsOrUndefs) {
12576     SmallVector<SDValue, 8> Opnds;
12577     EVT SVT = VT.getScalarType();
12578
12579     EVT MinVT = SVT;
12580     if (!SVT.isFloatingPoint()) {
12581       // If BUILD_VECTOR are from built from integer, they may have different
12582       // operand types. Get the smallest type and truncate all operands to it.
12583       bool FoundMinVT = false;
12584       for (const SDValue &Op : N->ops())
12585         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12586           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12587           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12588           FoundMinVT = true;
12589         }
12590       assert(FoundMinVT && "Concat vector type mismatch");
12591     }
12592
12593     for (const SDValue &Op : N->ops()) {
12594       EVT OpVT = Op.getValueType();
12595       unsigned NumElts = OpVT.getVectorNumElements();
12596
12597       if (ISD::UNDEF == Op.getOpcode())
12598         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12599
12600       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12601         if (SVT.isFloatingPoint()) {
12602           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12603           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12604         } else {
12605           for (unsigned i = 0; i != NumElts; ++i)
12606             Opnds.push_back(
12607                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12608         }
12609       }
12610     }
12611
12612     assert(VT.getVectorNumElements() == Opnds.size() &&
12613            "Concat vector type mismatch");
12614     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12615   }
12616
12617   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12618   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12619     return V;
12620
12621   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12622   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12623     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12624       return V;
12625
12626   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12627   // nodes often generate nop CONCAT_VECTOR nodes.
12628   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12629   // place the incoming vectors at the exact same location.
12630   SDValue SingleSource = SDValue();
12631   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12632
12633   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12634     SDValue Op = N->getOperand(i);
12635
12636     if (Op.getOpcode() == ISD::UNDEF)
12637       continue;
12638
12639     // Check if this is the identity extract:
12640     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12641       return SDValue();
12642
12643     // Find the single incoming vector for the extract_subvector.
12644     if (SingleSource.getNode()) {
12645       if (Op.getOperand(0) != SingleSource)
12646         return SDValue();
12647     } else {
12648       SingleSource = Op.getOperand(0);
12649
12650       // Check the source type is the same as the type of the result.
12651       // If not, this concat may extend the vector, so we can not
12652       // optimize it away.
12653       if (SingleSource.getValueType() != N->getValueType(0))
12654         return SDValue();
12655     }
12656
12657     unsigned IdentityIndex = i * PartNumElem;
12658     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12659     // The extract index must be constant.
12660     if (!CS)
12661       return SDValue();
12662
12663     // Check that we are reading from the identity index.
12664     if (CS->getZExtValue() != IdentityIndex)
12665       return SDValue();
12666   }
12667
12668   if (SingleSource.getNode())
12669     return SingleSource;
12670
12671   return SDValue();
12672 }
12673
12674 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12675   EVT NVT = N->getValueType(0);
12676   SDValue V = N->getOperand(0);
12677
12678   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12679     // Combine:
12680     //    (extract_subvec (concat V1, V2, ...), i)
12681     // Into:
12682     //    Vi if possible
12683     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12684     // type.
12685     if (V->getOperand(0).getValueType() != NVT)
12686       return SDValue();
12687     unsigned Idx = N->getConstantOperandVal(1);
12688     unsigned NumElems = NVT.getVectorNumElements();
12689     assert((Idx % NumElems) == 0 &&
12690            "IDX in concat is not a multiple of the result vector length.");
12691     return V->getOperand(Idx / NumElems);
12692   }
12693
12694   // Skip bitcasting
12695   if (V->getOpcode() == ISD::BITCAST)
12696     V = V.getOperand(0);
12697
12698   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12699     SDLoc dl(N);
12700     // Handle only simple case where vector being inserted and vector
12701     // being extracted are of same type, and are half size of larger vectors.
12702     EVT BigVT = V->getOperand(0).getValueType();
12703     EVT SmallVT = V->getOperand(1).getValueType();
12704     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12705       return SDValue();
12706
12707     // Only handle cases where both indexes are constants with the same type.
12708     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12709     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12710
12711     if (InsIdx && ExtIdx &&
12712         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12713         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12714       // Combine:
12715       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12716       // Into:
12717       //    indices are equal or bit offsets are equal => V1
12718       //    otherwise => (extract_subvec V1, ExtIdx)
12719       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12720           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12721         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12722       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12723                          DAG.getNode(ISD::BITCAST, dl,
12724                                      N->getOperand(0).getValueType(),
12725                                      V->getOperand(0)), N->getOperand(1));
12726     }
12727   }
12728
12729   return SDValue();
12730 }
12731
12732 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12733                                                  SDValue V, SelectionDAG &DAG) {
12734   SDLoc DL(V);
12735   EVT VT = V.getValueType();
12736
12737   switch (V.getOpcode()) {
12738   default:
12739     return V;
12740
12741   case ISD::CONCAT_VECTORS: {
12742     EVT OpVT = V->getOperand(0).getValueType();
12743     int OpSize = OpVT.getVectorNumElements();
12744     SmallBitVector OpUsedElements(OpSize, false);
12745     bool FoundSimplification = false;
12746     SmallVector<SDValue, 4> NewOps;
12747     NewOps.reserve(V->getNumOperands());
12748     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12749       SDValue Op = V->getOperand(i);
12750       bool OpUsed = false;
12751       for (int j = 0; j < OpSize; ++j)
12752         if (UsedElements[i * OpSize + j]) {
12753           OpUsedElements[j] = true;
12754           OpUsed = true;
12755         }
12756       NewOps.push_back(
12757           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12758                  : DAG.getUNDEF(OpVT));
12759       FoundSimplification |= Op == NewOps.back();
12760       OpUsedElements.reset();
12761     }
12762     if (FoundSimplification)
12763       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12764     return V;
12765   }
12766
12767   case ISD::INSERT_SUBVECTOR: {
12768     SDValue BaseV = V->getOperand(0);
12769     SDValue SubV = V->getOperand(1);
12770     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12771     if (!IdxN)
12772       return V;
12773
12774     int SubSize = SubV.getValueType().getVectorNumElements();
12775     int Idx = IdxN->getZExtValue();
12776     bool SubVectorUsed = false;
12777     SmallBitVector SubUsedElements(SubSize, false);
12778     for (int i = 0; i < SubSize; ++i)
12779       if (UsedElements[i + Idx]) {
12780         SubVectorUsed = true;
12781         SubUsedElements[i] = true;
12782         UsedElements[i + Idx] = false;
12783       }
12784
12785     // Now recurse on both the base and sub vectors.
12786     SDValue SimplifiedSubV =
12787         SubVectorUsed
12788             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12789             : DAG.getUNDEF(SubV.getValueType());
12790     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12791     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12792       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12793                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12794     return V;
12795   }
12796   }
12797 }
12798
12799 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12800                                        SDValue N1, SelectionDAG &DAG) {
12801   EVT VT = SVN->getValueType(0);
12802   int NumElts = VT.getVectorNumElements();
12803   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12804   for (int M : SVN->getMask())
12805     if (M >= 0 && M < NumElts)
12806       N0UsedElements[M] = true;
12807     else if (M >= NumElts)
12808       N1UsedElements[M - NumElts] = true;
12809
12810   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12811   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12812   if (S0 == N0 && S1 == N1)
12813     return SDValue();
12814
12815   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12816 }
12817
12818 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12819 // or turn a shuffle of a single concat into simpler shuffle then concat.
12820 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12821   EVT VT = N->getValueType(0);
12822   unsigned NumElts = VT.getVectorNumElements();
12823
12824   SDValue N0 = N->getOperand(0);
12825   SDValue N1 = N->getOperand(1);
12826   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12827
12828   SmallVector<SDValue, 4> Ops;
12829   EVT ConcatVT = N0.getOperand(0).getValueType();
12830   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12831   unsigned NumConcats = NumElts / NumElemsPerConcat;
12832
12833   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12834   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12835   // half vector elements.
12836   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12837       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12838                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12839     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12840                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
12841     N1 = DAG.getUNDEF(ConcatVT);
12842     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12843   }
12844
12845   // Look at every vector that's inserted. We're looking for exact
12846   // subvector-sized copies from a concatenated vector
12847   for (unsigned I = 0; I != NumConcats; ++I) {
12848     // Make sure we're dealing with a copy.
12849     unsigned Begin = I * NumElemsPerConcat;
12850     bool AllUndef = true, NoUndef = true;
12851     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12852       if (SVN->getMaskElt(J) >= 0)
12853         AllUndef = false;
12854       else
12855         NoUndef = false;
12856     }
12857
12858     if (NoUndef) {
12859       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12860         return SDValue();
12861
12862       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12863         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12864           return SDValue();
12865
12866       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12867       if (FirstElt < N0.getNumOperands())
12868         Ops.push_back(N0.getOperand(FirstElt));
12869       else
12870         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12871
12872     } else if (AllUndef) {
12873       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12874     } else { // Mixed with general masks and undefs, can't do optimization.
12875       return SDValue();
12876     }
12877   }
12878
12879   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12880 }
12881
12882 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12883   EVT VT = N->getValueType(0);
12884   unsigned NumElts = VT.getVectorNumElements();
12885
12886   SDValue N0 = N->getOperand(0);
12887   SDValue N1 = N->getOperand(1);
12888
12889   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12890
12891   // Canonicalize shuffle undef, undef -> undef
12892   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12893     return DAG.getUNDEF(VT);
12894
12895   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12896
12897   // Canonicalize shuffle v, v -> v, undef
12898   if (N0 == N1) {
12899     SmallVector<int, 8> NewMask;
12900     for (unsigned i = 0; i != NumElts; ++i) {
12901       int Idx = SVN->getMaskElt(i);
12902       if (Idx >= (int)NumElts) Idx -= NumElts;
12903       NewMask.push_back(Idx);
12904     }
12905     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12906                                 &NewMask[0]);
12907   }
12908
12909   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12910   if (N0.getOpcode() == ISD::UNDEF) {
12911     SmallVector<int, 8> NewMask;
12912     for (unsigned i = 0; i != NumElts; ++i) {
12913       int Idx = SVN->getMaskElt(i);
12914       if (Idx >= 0) {
12915         if (Idx >= (int)NumElts)
12916           Idx -= NumElts;
12917         else
12918           Idx = -1; // remove reference to lhs
12919       }
12920       NewMask.push_back(Idx);
12921     }
12922     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12923                                 &NewMask[0]);
12924   }
12925
12926   // Remove references to rhs if it is undef
12927   if (N1.getOpcode() == ISD::UNDEF) {
12928     bool Changed = false;
12929     SmallVector<int, 8> NewMask;
12930     for (unsigned i = 0; i != NumElts; ++i) {
12931       int Idx = SVN->getMaskElt(i);
12932       if (Idx >= (int)NumElts) {
12933         Idx = -1;
12934         Changed = true;
12935       }
12936       NewMask.push_back(Idx);
12937     }
12938     if (Changed)
12939       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12940   }
12941
12942   // If it is a splat, check if the argument vector is another splat or a
12943   // build_vector.
12944   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12945     SDNode *V = N0.getNode();
12946
12947     // If this is a bit convert that changes the element type of the vector but
12948     // not the number of vector elements, look through it.  Be careful not to
12949     // look though conversions that change things like v4f32 to v2f64.
12950     if (V->getOpcode() == ISD::BITCAST) {
12951       SDValue ConvInput = V->getOperand(0);
12952       if (ConvInput.getValueType().isVector() &&
12953           ConvInput.getValueType().getVectorNumElements() == NumElts)
12954         V = ConvInput.getNode();
12955     }
12956
12957     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12958       assert(V->getNumOperands() == NumElts &&
12959              "BUILD_VECTOR has wrong number of operands");
12960       SDValue Base;
12961       bool AllSame = true;
12962       for (unsigned i = 0; i != NumElts; ++i) {
12963         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12964           Base = V->getOperand(i);
12965           break;
12966         }
12967       }
12968       // Splat of <u, u, u, u>, return <u, u, u, u>
12969       if (!Base.getNode())
12970         return N0;
12971       for (unsigned i = 0; i != NumElts; ++i) {
12972         if (V->getOperand(i) != Base) {
12973           AllSame = false;
12974           break;
12975         }
12976       }
12977       // Splat of <x, x, x, x>, return <x, x, x, x>
12978       if (AllSame)
12979         return N0;
12980
12981       // Canonicalize any other splat as a build_vector.
12982       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12983       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12984       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12985                                   V->getValueType(0), Ops);
12986
12987       // We may have jumped through bitcasts, so the type of the
12988       // BUILD_VECTOR may not match the type of the shuffle.
12989       if (V->getValueType(0) != VT)
12990         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12991       return NewBV;
12992     }
12993   }
12994
12995   // There are various patterns used to build up a vector from smaller vectors,
12996   // subvectors, or elements. Scan chains of these and replace unused insertions
12997   // or components with undef.
12998   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12999     return S;
13000
13001   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13002       Level < AfterLegalizeVectorOps &&
13003       (N1.getOpcode() == ISD::UNDEF ||
13004       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13005        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13006     SDValue V = partitionShuffleOfConcats(N, DAG);
13007
13008     if (V.getNode())
13009       return V;
13010   }
13011
13012   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13013   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13014   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13015     SmallVector<SDValue, 8> Ops;
13016     for (int M : SVN->getMask()) {
13017       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13018       if (M >= 0) {
13019         int Idx = M % NumElts;
13020         SDValue &S = (M < (int)NumElts ? N0 : N1);
13021         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13022           Op = S.getOperand(Idx);
13023         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13024           if (Idx == 0)
13025             Op = S.getOperand(0);
13026         } else {
13027           // Operand can't be combined - bail out.
13028           break;
13029         }
13030       }
13031       Ops.push_back(Op);
13032     }
13033     if (Ops.size() == VT.getVectorNumElements()) {
13034       // BUILD_VECTOR requires all inputs to be of the same type, find the
13035       // maximum type and extend them all.
13036       EVT SVT = VT.getScalarType();
13037       if (SVT.isInteger())
13038         for (SDValue &Op : Ops)
13039           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13040       if (SVT != VT.getScalarType())
13041         for (SDValue &Op : Ops)
13042           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13043                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13044                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13045       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13046     }
13047   }
13048
13049   // If this shuffle only has a single input that is a bitcasted shuffle,
13050   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13051   // back to their original types.
13052   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13053       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13054       TLI.isTypeLegal(VT)) {
13055
13056     // Peek through the bitcast only if there is one user.
13057     SDValue BC0 = N0;
13058     while (BC0.getOpcode() == ISD::BITCAST) {
13059       if (!BC0.hasOneUse())
13060         break;
13061       BC0 = BC0.getOperand(0);
13062     }
13063
13064     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13065       if (Scale == 1)
13066         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13067
13068       SmallVector<int, 8> NewMask;
13069       for (int M : Mask)
13070         for (int s = 0; s != Scale; ++s)
13071           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13072       return NewMask;
13073     };
13074
13075     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13076       EVT SVT = VT.getScalarType();
13077       EVT InnerVT = BC0->getValueType(0);
13078       EVT InnerSVT = InnerVT.getScalarType();
13079
13080       // Determine which shuffle works with the smaller scalar type.
13081       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13082       EVT ScaleSVT = ScaleVT.getScalarType();
13083
13084       if (TLI.isTypeLegal(ScaleVT) &&
13085           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13086           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13087
13088         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13089         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13090
13091         // Scale the shuffle masks to the smaller scalar type.
13092         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13093         SmallVector<int, 8> InnerMask =
13094             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13095         SmallVector<int, 8> OuterMask =
13096             ScaleShuffleMask(SVN->getMask(), OuterScale);
13097
13098         // Merge the shuffle masks.
13099         SmallVector<int, 8> NewMask;
13100         for (int M : OuterMask)
13101           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13102
13103         // Test for shuffle mask legality over both commutations.
13104         SDValue SV0 = BC0->getOperand(0);
13105         SDValue SV1 = BC0->getOperand(1);
13106         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13107         if (!LegalMask) {
13108           std::swap(SV0, SV1);
13109           ShuffleVectorSDNode::commuteMask(NewMask);
13110           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13111         }
13112
13113         if (LegalMask) {
13114           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13115           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13116           return DAG.getNode(
13117               ISD::BITCAST, SDLoc(N), VT,
13118               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13119         }
13120       }
13121     }
13122   }
13123
13124   // Canonicalize shuffles according to rules:
13125   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13126   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13127   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13128   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13129       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13130       TLI.isTypeLegal(VT)) {
13131     // The incoming shuffle must be of the same type as the result of the
13132     // current shuffle.
13133     assert(N1->getOperand(0).getValueType() == VT &&
13134            "Shuffle types don't match");
13135
13136     SDValue SV0 = N1->getOperand(0);
13137     SDValue SV1 = N1->getOperand(1);
13138     bool HasSameOp0 = N0 == SV0;
13139     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13140     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13141       // Commute the operands of this shuffle so that next rule
13142       // will trigger.
13143       return DAG.getCommutedVectorShuffle(*SVN);
13144   }
13145
13146   // Try to fold according to rules:
13147   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13148   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13149   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13150   // Don't try to fold shuffles with illegal type.
13151   // Only fold if this shuffle is the only user of the other shuffle.
13152   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13153       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13154     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13155
13156     // The incoming shuffle must be of the same type as the result of the
13157     // current shuffle.
13158     assert(OtherSV->getOperand(0).getValueType() == VT &&
13159            "Shuffle types don't match");
13160
13161     SDValue SV0, SV1;
13162     SmallVector<int, 4> Mask;
13163     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13164     // operand, and SV1 as the second operand.
13165     for (unsigned i = 0; i != NumElts; ++i) {
13166       int Idx = SVN->getMaskElt(i);
13167       if (Idx < 0) {
13168         // Propagate Undef.
13169         Mask.push_back(Idx);
13170         continue;
13171       }
13172
13173       SDValue CurrentVec;
13174       if (Idx < (int)NumElts) {
13175         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13176         // shuffle mask to identify which vector is actually referenced.
13177         Idx = OtherSV->getMaskElt(Idx);
13178         if (Idx < 0) {
13179           // Propagate Undef.
13180           Mask.push_back(Idx);
13181           continue;
13182         }
13183
13184         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13185                                            : OtherSV->getOperand(1);
13186       } else {
13187         // This shuffle index references an element within N1.
13188         CurrentVec = N1;
13189       }
13190
13191       // Simple case where 'CurrentVec' is UNDEF.
13192       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13193         Mask.push_back(-1);
13194         continue;
13195       }
13196
13197       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13198       // will be the first or second operand of the combined shuffle.
13199       Idx = Idx % NumElts;
13200       if (!SV0.getNode() || SV0 == CurrentVec) {
13201         // Ok. CurrentVec is the left hand side.
13202         // Update the mask accordingly.
13203         SV0 = CurrentVec;
13204         Mask.push_back(Idx);
13205         continue;
13206       }
13207
13208       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13209       if (SV1.getNode() && SV1 != CurrentVec)
13210         return SDValue();
13211
13212       // Ok. CurrentVec is the right hand side.
13213       // Update the mask accordingly.
13214       SV1 = CurrentVec;
13215       Mask.push_back(Idx + NumElts);
13216     }
13217
13218     // Check if all indices in Mask are Undef. In case, propagate Undef.
13219     bool isUndefMask = true;
13220     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13221       isUndefMask &= Mask[i] < 0;
13222
13223     if (isUndefMask)
13224       return DAG.getUNDEF(VT);
13225
13226     if (!SV0.getNode())
13227       SV0 = DAG.getUNDEF(VT);
13228     if (!SV1.getNode())
13229       SV1 = DAG.getUNDEF(VT);
13230
13231     // Avoid introducing shuffles with illegal mask.
13232     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13233       ShuffleVectorSDNode::commuteMask(Mask);
13234
13235       if (!TLI.isShuffleMaskLegal(Mask, VT))
13236         return SDValue();
13237
13238       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13239       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13240       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13241       std::swap(SV0, SV1);
13242     }
13243
13244     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13245     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13246     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13247     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13248   }
13249
13250   return SDValue();
13251 }
13252
13253 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13254   SDValue InVal = N->getOperand(0);
13255   EVT VT = N->getValueType(0);
13256
13257   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13258   // with a VECTOR_SHUFFLE.
13259   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13260     SDValue InVec = InVal->getOperand(0);
13261     SDValue EltNo = InVal->getOperand(1);
13262
13263     // FIXME: We could support implicit truncation if the shuffle can be
13264     // scaled to a smaller vector scalar type.
13265     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13266     if (C0 && VT == InVec.getValueType() &&
13267         VT.getScalarType() == InVal.getValueType()) {
13268       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13269       int Elt = C0->getZExtValue();
13270       NewMask[0] = Elt;
13271
13272       if (TLI.isShuffleMaskLegal(NewMask, VT))
13273         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13274                                     NewMask);
13275     }
13276   }
13277
13278   return SDValue();
13279 }
13280
13281 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13282   SDValue N0 = N->getOperand(0);
13283   SDValue N2 = N->getOperand(2);
13284
13285   // If the input vector is a concatenation, and the insert replaces
13286   // one of the halves, we can optimize into a single concat_vectors.
13287   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13288       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13289     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13290     EVT VT = N->getValueType(0);
13291
13292     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13293     // (concat_vectors Z, Y)
13294     if (InsIdx == 0)
13295       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13296                          N->getOperand(1), N0.getOperand(1));
13297
13298     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13299     // (concat_vectors X, Z)
13300     if (InsIdx == VT.getVectorNumElements()/2)
13301       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13302                          N0.getOperand(0), N->getOperand(1));
13303   }
13304
13305   return SDValue();
13306 }
13307
13308 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13309   SDValue N0 = N->getOperand(0);
13310
13311   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13312   if (N0->getOpcode() == ISD::FP16_TO_FP)
13313     return N0->getOperand(0);
13314
13315   return SDValue();
13316 }
13317
13318 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13319   SDValue N0 = N->getOperand(0);
13320
13321   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13322   if (N0->getOpcode() == ISD::AND) {
13323     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13324     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13325       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13326                          N0.getOperand(0));
13327     }
13328   }
13329
13330   return SDValue();
13331 }
13332
13333 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13334 /// with the destination vector and a zero vector.
13335 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13336 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13337 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13338   EVT VT = N->getValueType(0);
13339   SDValue LHS = N->getOperand(0);
13340   SDValue RHS = N->getOperand(1);
13341   SDLoc dl(N);
13342
13343   // Make sure we're not running after operation legalization where it
13344   // may have custom lowered the vector shuffles.
13345   if (LegalOperations)
13346     return SDValue();
13347
13348   if (N->getOpcode() != ISD::AND)
13349     return SDValue();
13350
13351   if (RHS.getOpcode() == ISD::BITCAST)
13352     RHS = RHS.getOperand(0);
13353
13354   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13355     return SDValue();
13356
13357   EVT RVT = RHS.getValueType();
13358   unsigned NumElts = RHS.getNumOperands();
13359
13360   // Attempt to create a valid clear mask, splitting the mask into
13361   // sub elements and checking to see if each is
13362   // all zeros or all ones - suitable for shuffle masking.
13363   auto BuildClearMask = [&](int Split) {
13364     int NumSubElts = NumElts * Split;
13365     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13366
13367     SmallVector<int, 8> Indices;
13368     for (int i = 0; i != NumSubElts; ++i) {
13369       int EltIdx = i / Split;
13370       int SubIdx = i % Split;
13371       SDValue Elt = RHS.getOperand(EltIdx);
13372       if (Elt.getOpcode() == ISD::UNDEF) {
13373         Indices.push_back(-1);
13374         continue;
13375       }
13376
13377       APInt Bits;
13378       if (isa<ConstantSDNode>(Elt))
13379         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13380       else if (isa<ConstantFPSDNode>(Elt))
13381         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13382       else
13383         return SDValue();
13384
13385       // Extract the sub element from the constant bit mask.
13386       if (DAG.getDataLayout().isBigEndian()) {
13387         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13388       } else {
13389         Bits = Bits.lshr(SubIdx * NumSubBits);
13390       }
13391
13392       if (Split > 1)
13393         Bits = Bits.trunc(NumSubBits);
13394
13395       if (Bits.isAllOnesValue())
13396         Indices.push_back(i);
13397       else if (Bits == 0)
13398         Indices.push_back(i + NumSubElts);
13399       else
13400         return SDValue();
13401     }
13402
13403     // Let's see if the target supports this vector_shuffle.
13404     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13405     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13406     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13407       return SDValue();
13408
13409     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13410     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13411                                                    DAG.getBitcast(ClearVT, LHS),
13412                                                    Zero, &Indices[0]));
13413   };
13414
13415   // Determine maximum split level (byte level masking).
13416   int MaxSplit = 1;
13417   if (RVT.getScalarSizeInBits() % 8 == 0)
13418     MaxSplit = RVT.getScalarSizeInBits() / 8;
13419
13420   for (int Split = 1; Split <= MaxSplit; ++Split)
13421     if (RVT.getScalarSizeInBits() % Split == 0)
13422       if (SDValue S = BuildClearMask(Split))
13423         return S;
13424
13425   return SDValue();
13426 }
13427
13428 /// Visit a binary vector operation, like ADD.
13429 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13430   assert(N->getValueType(0).isVector() &&
13431          "SimplifyVBinOp only works on vectors!");
13432
13433   SDValue LHS = N->getOperand(0);
13434   SDValue RHS = N->getOperand(1);
13435   SDValue Ops[] = {LHS, RHS};
13436
13437   // See if we can constant fold the vector operation.
13438   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13439           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13440     return Fold;
13441
13442   // Try to convert a constant mask AND into a shuffle clear mask.
13443   if (SDValue Shuffle = XformToShuffleWithZero(N))
13444     return Shuffle;
13445
13446   // Type legalization might introduce new shuffles in the DAG.
13447   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13448   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13449   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13450       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13451       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13452       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13453     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13454     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13455
13456     if (SVN0->getMask().equals(SVN1->getMask())) {
13457       EVT VT = N->getValueType(0);
13458       SDValue UndefVector = LHS.getOperand(1);
13459       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13460                                      LHS.getOperand(0), RHS.getOperand(0),
13461                                      N->getFlags());
13462       AddUsersToWorklist(N);
13463       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13464                                   &SVN0->getMask()[0]);
13465     }
13466   }
13467
13468   return SDValue();
13469 }
13470
13471 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13472                                     SDValue N1, SDValue N2){
13473   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13474
13475   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13476                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13477
13478   // If we got a simplified select_cc node back from SimplifySelectCC, then
13479   // break it down into a new SETCC node, and a new SELECT node, and then return
13480   // the SELECT node, since we were called with a SELECT node.
13481   if (SCC.getNode()) {
13482     // Check to see if we got a select_cc back (to turn into setcc/select).
13483     // Otherwise, just return whatever node we got back, like fabs.
13484     if (SCC.getOpcode() == ISD::SELECT_CC) {
13485       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13486                                   N0.getValueType(),
13487                                   SCC.getOperand(0), SCC.getOperand(1),
13488                                   SCC.getOperand(4));
13489       AddToWorklist(SETCC.getNode());
13490       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13491                            SCC.getOperand(2), SCC.getOperand(3));
13492     }
13493
13494     return SCC;
13495   }
13496   return SDValue();
13497 }
13498
13499 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13500 /// being selected between, see if we can simplify the select.  Callers of this
13501 /// should assume that TheSelect is deleted if this returns true.  As such, they
13502 /// should return the appropriate thing (e.g. the node) back to the top-level of
13503 /// the DAG combiner loop to avoid it being looked at.
13504 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13505                                     SDValue RHS) {
13506
13507   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13508   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13509   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13510     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13511       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13512       SDValue Sqrt = RHS;
13513       ISD::CondCode CC;
13514       SDValue CmpLHS;
13515       const ConstantFPSDNode *NegZero = nullptr;
13516
13517       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13518         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13519         CmpLHS = TheSelect->getOperand(0);
13520         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13521       } else {
13522         // SELECT or VSELECT
13523         SDValue Cmp = TheSelect->getOperand(0);
13524         if (Cmp.getOpcode() == ISD::SETCC) {
13525           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13526           CmpLHS = Cmp.getOperand(0);
13527           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13528         }
13529       }
13530       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13531           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13532           CC == ISD::SETULT || CC == ISD::SETLT)) {
13533         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13534         CombineTo(TheSelect, Sqrt);
13535         return true;
13536       }
13537     }
13538   }
13539   // Cannot simplify select with vector condition
13540   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13541
13542   // If this is a select from two identical things, try to pull the operation
13543   // through the select.
13544   if (LHS.getOpcode() != RHS.getOpcode() ||
13545       !LHS.hasOneUse() || !RHS.hasOneUse())
13546     return false;
13547
13548   // If this is a load and the token chain is identical, replace the select
13549   // of two loads with a load through a select of the address to load from.
13550   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13551   // constants have been dropped into the constant pool.
13552   if (LHS.getOpcode() == ISD::LOAD) {
13553     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13554     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13555
13556     // Token chains must be identical.
13557     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13558         // Do not let this transformation reduce the number of volatile loads.
13559         LLD->isVolatile() || RLD->isVolatile() ||
13560         // FIXME: If either is a pre/post inc/dec load,
13561         // we'd need to split out the address adjustment.
13562         LLD->isIndexed() || RLD->isIndexed() ||
13563         // If this is an EXTLOAD, the VT's must match.
13564         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13565         // If this is an EXTLOAD, the kind of extension must match.
13566         (LLD->getExtensionType() != RLD->getExtensionType() &&
13567          // The only exception is if one of the extensions is anyext.
13568          LLD->getExtensionType() != ISD::EXTLOAD &&
13569          RLD->getExtensionType() != ISD::EXTLOAD) ||
13570         // FIXME: this discards src value information.  This is
13571         // over-conservative. It would be beneficial to be able to remember
13572         // both potential memory locations.  Since we are discarding
13573         // src value info, don't do the transformation if the memory
13574         // locations are not in the default address space.
13575         LLD->getPointerInfo().getAddrSpace() != 0 ||
13576         RLD->getPointerInfo().getAddrSpace() != 0 ||
13577         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13578                                       LLD->getBasePtr().getValueType()))
13579       return false;
13580
13581     // Check that the select condition doesn't reach either load.  If so,
13582     // folding this will induce a cycle into the DAG.  If not, this is safe to
13583     // xform, so create a select of the addresses.
13584     SDValue Addr;
13585     if (TheSelect->getOpcode() == ISD::SELECT) {
13586       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13587       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13588           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13589         return false;
13590       // The loads must not depend on one another.
13591       if (LLD->isPredecessorOf(RLD) ||
13592           RLD->isPredecessorOf(LLD))
13593         return false;
13594       Addr = DAG.getSelect(SDLoc(TheSelect),
13595                            LLD->getBasePtr().getValueType(),
13596                            TheSelect->getOperand(0), LLD->getBasePtr(),
13597                            RLD->getBasePtr());
13598     } else {  // Otherwise SELECT_CC
13599       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13600       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13601
13602       if ((LLD->hasAnyUseOfValue(1) &&
13603            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13604           (RLD->hasAnyUseOfValue(1) &&
13605            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13606         return false;
13607
13608       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13609                          LLD->getBasePtr().getValueType(),
13610                          TheSelect->getOperand(0),
13611                          TheSelect->getOperand(1),
13612                          LLD->getBasePtr(), RLD->getBasePtr(),
13613                          TheSelect->getOperand(4));
13614     }
13615
13616     SDValue Load;
13617     // It is safe to replace the two loads if they have different alignments,
13618     // but the new load must be the minimum (most restrictive) alignment of the
13619     // inputs.
13620     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13621     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13622     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13623       Load = DAG.getLoad(TheSelect->getValueType(0),
13624                          SDLoc(TheSelect),
13625                          // FIXME: Discards pointer and AA info.
13626                          LLD->getChain(), Addr, MachinePointerInfo(),
13627                          LLD->isVolatile(), LLD->isNonTemporal(),
13628                          isInvariant, Alignment);
13629     } else {
13630       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13631                             RLD->getExtensionType() : LLD->getExtensionType(),
13632                             SDLoc(TheSelect),
13633                             TheSelect->getValueType(0),
13634                             // FIXME: Discards pointer and AA info.
13635                             LLD->getChain(), Addr, MachinePointerInfo(),
13636                             LLD->getMemoryVT(), LLD->isVolatile(),
13637                             LLD->isNonTemporal(), isInvariant, Alignment);
13638     }
13639
13640     // Users of the select now use the result of the load.
13641     CombineTo(TheSelect, Load);
13642
13643     // Users of the old loads now use the new load's chain.  We know the
13644     // old-load value is dead now.
13645     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13646     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13647     return true;
13648   }
13649
13650   return false;
13651 }
13652
13653 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13654 /// where 'cond' is the comparison specified by CC.
13655 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13656                                       SDValue N2, SDValue N3,
13657                                       ISD::CondCode CC, bool NotExtCompare) {
13658   // (x ? y : y) -> y.
13659   if (N2 == N3) return N2;
13660
13661   EVT VT = N2.getValueType();
13662   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13663   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13664
13665   // Determine if the condition we're dealing with is constant
13666   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13667                               N0, N1, CC, DL, false);
13668   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13669
13670   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13671     // fold select_cc true, x, y -> x
13672     // fold select_cc false, x, y -> y
13673     return !SCCC->isNullValue() ? N2 : N3;
13674   }
13675
13676   // Check to see if we can simplify the select into an fabs node
13677   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13678     // Allow either -0.0 or 0.0
13679     if (CFP->isZero()) {
13680       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13681       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13682           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13683           N2 == N3.getOperand(0))
13684         return DAG.getNode(ISD::FABS, DL, VT, N0);
13685
13686       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13687       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13688           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13689           N2.getOperand(0) == N3)
13690         return DAG.getNode(ISD::FABS, DL, VT, N3);
13691     }
13692   }
13693
13694   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13695   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13696   // in it.  This is a win when the constant is not otherwise available because
13697   // it replaces two constant pool loads with one.  We only do this if the FP
13698   // type is known to be legal, because if it isn't, then we are before legalize
13699   // types an we want the other legalization to happen first (e.g. to avoid
13700   // messing with soft float) and if the ConstantFP is not legal, because if
13701   // it is legal, we may not need to store the FP constant in a constant pool.
13702   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13703     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13704       if (TLI.isTypeLegal(N2.getValueType()) &&
13705           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13706                TargetLowering::Legal &&
13707            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13708            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13709           // If both constants have multiple uses, then we won't need to do an
13710           // extra load, they are likely around in registers for other users.
13711           (TV->hasOneUse() || FV->hasOneUse())) {
13712         Constant *Elts[] = {
13713           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13714           const_cast<ConstantFP*>(TV->getConstantFPValue())
13715         };
13716         Type *FPTy = Elts[0]->getType();
13717         const DataLayout &TD = DAG.getDataLayout();
13718
13719         // Create a ConstantArray of the two constants.
13720         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13721         SDValue CPIdx =
13722             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13723                                 TD.getPrefTypeAlignment(FPTy));
13724         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13725
13726         // Get the offsets to the 0 and 1 element of the array so that we can
13727         // select between them.
13728         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13729         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13730         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13731
13732         SDValue Cond = DAG.getSetCC(DL,
13733                                     getSetCCResultType(N0.getValueType()),
13734                                     N0, N1, CC);
13735         AddToWorklist(Cond.getNode());
13736         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13737                                           Cond, One, Zero);
13738         AddToWorklist(CstOffset.getNode());
13739         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13740                             CstOffset);
13741         AddToWorklist(CPIdx.getNode());
13742         return DAG.getLoad(
13743             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13744             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13745             false, false, false, Alignment);
13746       }
13747     }
13748
13749   // Check to see if we can perform the "gzip trick", transforming
13750   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13751   if (isNullConstant(N3) && CC == ISD::SETLT &&
13752       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13753        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13754     EVT XType = N0.getValueType();
13755     EVT AType = N2.getValueType();
13756     if (XType.bitsGE(AType)) {
13757       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13758       // single-bit constant.
13759       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13760         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13761         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13762         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13763                                        getShiftAmountTy(N0.getValueType()));
13764         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13765                                     XType, N0, ShCt);
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       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13777                                   XType, N0,
13778                                   DAG.getConstant(XType.getSizeInBits() - 1,
13779                                                   SDLoc(N0),
13780                                          getShiftAmountTy(N0.getValueType())));
13781       AddToWorklist(Shift.getNode());
13782
13783       if (XType.bitsGT(AType)) {
13784         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13785         AddToWorklist(Shift.getNode());
13786       }
13787
13788       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13789     }
13790   }
13791
13792   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13793   // where y is has a single bit set.
13794   // A plaintext description would be, we can turn the SELECT_CC into an AND
13795   // when the condition can be materialized as an all-ones register.  Any
13796   // single bit-test can be materialized as an all-ones register with
13797   // shift-left and shift-right-arith.
13798   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13799       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13800     SDValue AndLHS = N0->getOperand(0);
13801     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13802     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13803       // Shift the tested bit over the sign bit.
13804       APInt AndMask = ConstAndRHS->getAPIntValue();
13805       SDValue ShlAmt =
13806         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13807                         getShiftAmountTy(AndLHS.getValueType()));
13808       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13809
13810       // Now arithmetic right shift it all the way over, so the result is either
13811       // all-ones, or zero.
13812       SDValue ShrAmt =
13813         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13814                         getShiftAmountTy(Shl.getValueType()));
13815       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13816
13817       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13818     }
13819   }
13820
13821   // fold select C, 16, 0 -> shl C, 4
13822   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13823       TLI.getBooleanContents(N0.getValueType()) ==
13824           TargetLowering::ZeroOrOneBooleanContent) {
13825
13826     // If the caller doesn't want us to simplify this into a zext of a compare,
13827     // don't do it.
13828     if (NotExtCompare && N2C->isOne())
13829       return SDValue();
13830
13831     // Get a SetCC of the condition
13832     // NOTE: Don't create a SETCC if it's not legal on this target.
13833     if (!LegalOperations ||
13834         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13835       SDValue Temp, SCC;
13836       // cast from setcc result type to select result type
13837       if (LegalTypes) {
13838         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13839                             N0, N1, CC);
13840         if (N2.getValueType().bitsLT(SCC.getValueType()))
13841           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13842                                         N2.getValueType());
13843         else
13844           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13845                              N2.getValueType(), SCC);
13846       } else {
13847         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13848         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13849                            N2.getValueType(), SCC);
13850       }
13851
13852       AddToWorklist(SCC.getNode());
13853       AddToWorklist(Temp.getNode());
13854
13855       if (N2C->isOne())
13856         return Temp;
13857
13858       // shl setcc result by log2 n2c
13859       return DAG.getNode(
13860           ISD::SHL, DL, N2.getValueType(), Temp,
13861           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13862                           getShiftAmountTy(Temp.getValueType())));
13863     }
13864   }
13865
13866   // Check to see if this is an integer abs.
13867   // select_cc setg[te] X,  0,  X, -X ->
13868   // select_cc setgt    X, -1,  X, -X ->
13869   // select_cc setl[te] X,  0, -X,  X ->
13870   // select_cc setlt    X,  1, -X,  X ->
13871   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13872   if (N1C) {
13873     ConstantSDNode *SubC = nullptr;
13874     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13875          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13876         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13877       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13878     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13879               (N1C->isOne() && CC == ISD::SETLT)) &&
13880              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13881       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13882
13883     EVT XType = N0.getValueType();
13884     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13885       SDLoc DL(N0);
13886       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13887                                   N0,
13888                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13889                                          getShiftAmountTy(N0.getValueType())));
13890       SDValue Add = DAG.getNode(ISD::ADD, DL,
13891                                 XType, N0, Shift);
13892       AddToWorklist(Shift.getNode());
13893       AddToWorklist(Add.getNode());
13894       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13895     }
13896   }
13897
13898   return SDValue();
13899 }
13900
13901 /// This is a stub for TargetLowering::SimplifySetCC.
13902 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13903                                    SDValue N1, ISD::CondCode Cond,
13904                                    SDLoc DL, bool foldBooleans) {
13905   TargetLowering::DAGCombinerInfo
13906     DagCombineInfo(DAG, Level, false, this);
13907   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13908 }
13909
13910 /// Given an ISD::SDIV node expressing a divide by constant, return
13911 /// a DAG expression to select that will generate the same value by multiplying
13912 /// by a magic number.
13913 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13914 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13915   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13916   if (!C)
13917     return SDValue();
13918
13919   // Avoid division by zero.
13920   if (C->isNullValue())
13921     return SDValue();
13922
13923   std::vector<SDNode*> Built;
13924   SDValue S =
13925       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13926
13927   for (SDNode *N : Built)
13928     AddToWorklist(N);
13929   return S;
13930 }
13931
13932 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13933 /// DAG expression that will generate the same value by right shifting.
13934 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13935   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13936   if (!C)
13937     return SDValue();
13938
13939   // Avoid division by zero.
13940   if (C->isNullValue())
13941     return SDValue();
13942
13943   std::vector<SDNode *> Built;
13944   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13945
13946   for (SDNode *N : Built)
13947     AddToWorklist(N);
13948   return S;
13949 }
13950
13951 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13952 /// expression that will generate the same value by multiplying by a magic
13953 /// number.
13954 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13955 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13956   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13957   if (!C)
13958     return SDValue();
13959
13960   // Avoid division by zero.
13961   if (C->isNullValue())
13962     return SDValue();
13963
13964   std::vector<SDNode*> Built;
13965   SDValue S =
13966       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13967
13968   for (SDNode *N : Built)
13969     AddToWorklist(N);
13970   return S;
13971 }
13972
13973 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
13974   if (Level >= AfterLegalizeDAG)
13975     return SDValue();
13976
13977   // Expose the DAG combiner to the target combiner implementations.
13978   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13979
13980   unsigned Iterations = 0;
13981   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13982     if (Iterations) {
13983       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13984       // For the reciprocal, we need to find the zero of the function:
13985       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13986       //     =>
13987       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13988       //     does not require additional intermediate precision]
13989       EVT VT = Op.getValueType();
13990       SDLoc DL(Op);
13991       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13992
13993       AddToWorklist(Est.getNode());
13994
13995       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13996       for (unsigned i = 0; i < Iterations; ++i) {
13997         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
13998         AddToWorklist(NewEst.getNode());
13999
14000         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14001         AddToWorklist(NewEst.getNode());
14002
14003         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14004         AddToWorklist(NewEst.getNode());
14005
14006         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14007         AddToWorklist(Est.getNode());
14008       }
14009     }
14010     return Est;
14011   }
14012
14013   return SDValue();
14014 }
14015
14016 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14017 /// For the reciprocal sqrt, we need to find the zero of the function:
14018 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14019 ///     =>
14020 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14021 /// As a result, we precompute A/2 prior to the iteration loop.
14022 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14023                                           unsigned Iterations,
14024                                           SDNodeFlags *Flags) {
14025   EVT VT = Arg.getValueType();
14026   SDLoc DL(Arg);
14027   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14028
14029   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14030   // this entire sequence requires only one FP constant.
14031   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14032   AddToWorklist(HalfArg.getNode());
14033
14034   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14035   AddToWorklist(HalfArg.getNode());
14036
14037   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14038   for (unsigned i = 0; i < Iterations; ++i) {
14039     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14040     AddToWorklist(NewEst.getNode());
14041
14042     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14043     AddToWorklist(NewEst.getNode());
14044
14045     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14046     AddToWorklist(NewEst.getNode());
14047
14048     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14049     AddToWorklist(Est.getNode());
14050   }
14051   return Est;
14052 }
14053
14054 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14055 /// For the reciprocal sqrt, we need to find the zero of the function:
14056 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14057 ///     =>
14058 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14059 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14060                                           unsigned Iterations,
14061                                           SDNodeFlags *Flags) {
14062   EVT VT = Arg.getValueType();
14063   SDLoc DL(Arg);
14064   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14065   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14066
14067   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14068   for (unsigned i = 0; i < Iterations; ++i) {
14069     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14070     AddToWorklist(HalfEst.getNode());
14071
14072     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14073     AddToWorklist(Est.getNode());
14074
14075     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14076     AddToWorklist(Est.getNode());
14077
14078     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14079     AddToWorklist(Est.getNode());
14080
14081     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14082     AddToWorklist(Est.getNode());
14083   }
14084   return Est;
14085 }
14086
14087 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14088   if (Level >= AfterLegalizeDAG)
14089     return SDValue();
14090
14091   // Expose the DAG combiner to the target combiner implementations.
14092   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14093   unsigned Iterations = 0;
14094   bool UseOneConstNR = false;
14095   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14096     AddToWorklist(Est.getNode());
14097     if (Iterations) {
14098       Est = UseOneConstNR ?
14099         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14100         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14101     }
14102     return Est;
14103   }
14104
14105   return SDValue();
14106 }
14107
14108 /// Return true if base is a frame index, which is known not to alias with
14109 /// anything but itself.  Provides base object and offset as results.
14110 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14111                            const GlobalValue *&GV, const void *&CV) {
14112   // Assume it is a primitive operation.
14113   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14114
14115   // If it's an adding a simple constant then integrate the offset.
14116   if (Base.getOpcode() == ISD::ADD) {
14117     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14118       Base = Base.getOperand(0);
14119       Offset += C->getZExtValue();
14120     }
14121   }
14122
14123   // Return the underlying GlobalValue, and update the Offset.  Return false
14124   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14125   // by multiple nodes with different offsets.
14126   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14127     GV = G->getGlobal();
14128     Offset += G->getOffset();
14129     return false;
14130   }
14131
14132   // Return the underlying Constant value, and update the Offset.  Return false
14133   // for ConstantSDNodes since the same constant pool entry may be represented
14134   // by multiple nodes with different offsets.
14135   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14136     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14137                                          : (const void *)C->getConstVal();
14138     Offset += C->getOffset();
14139     return false;
14140   }
14141   // If it's any of the following then it can't alias with anything but itself.
14142   return isa<FrameIndexSDNode>(Base);
14143 }
14144
14145 /// Return true if there is any possibility that the two addresses overlap.
14146 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14147   // If they are the same then they must be aliases.
14148   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14149
14150   // If they are both volatile then they cannot be reordered.
14151   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14152
14153   // If one operation reads from invariant memory, and the other may store, they
14154   // cannot alias. These should really be checking the equivalent of mayWrite,
14155   // but it only matters for memory nodes other than load /store.
14156   if (Op0->isInvariant() && Op1->writeMem())
14157     return false;
14158
14159   if (Op1->isInvariant() && Op0->writeMem())
14160     return false;
14161
14162   // Gather base node and offset information.
14163   SDValue Base1, Base2;
14164   int64_t Offset1, Offset2;
14165   const GlobalValue *GV1, *GV2;
14166   const void *CV1, *CV2;
14167   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14168                                       Base1, Offset1, GV1, CV1);
14169   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14170                                       Base2, Offset2, GV2, CV2);
14171
14172   // If they have a same base address then check to see if they overlap.
14173   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14174     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14175              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14176
14177   // It is possible for different frame indices to alias each other, mostly
14178   // when tail call optimization reuses return address slots for arguments.
14179   // To catch this case, look up the actual index of frame indices to compute
14180   // the real alias relationship.
14181   if (isFrameIndex1 && isFrameIndex2) {
14182     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14183     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14184     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14185     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14186              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14187   }
14188
14189   // Otherwise, if we know what the bases are, and they aren't identical, then
14190   // we know they cannot alias.
14191   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14192     return false;
14193
14194   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14195   // compared to the size and offset of the access, we may be able to prove they
14196   // do not alias.  This check is conservative for now to catch cases created by
14197   // splitting vector types.
14198   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14199       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14200       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14201        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14202       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14203     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14204     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14205
14206     // There is no overlap between these relatively aligned accesses of similar
14207     // size, return no alias.
14208     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14209         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14210       return false;
14211   }
14212
14213   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14214                    ? CombinerGlobalAA
14215                    : DAG.getSubtarget().useAA();
14216 #ifndef NDEBUG
14217   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14218       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14219     UseAA = false;
14220 #endif
14221   if (UseAA &&
14222       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14223     // Use alias analysis information.
14224     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14225                                  Op1->getSrcValueOffset());
14226     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14227         Op0->getSrcValueOffset() - MinOffset;
14228     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14229         Op1->getSrcValueOffset() - MinOffset;
14230     AliasResult AAResult =
14231         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14232                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14233                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14234                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14235     if (AAResult == NoAlias)
14236       return false;
14237   }
14238
14239   // Otherwise we have to assume they alias.
14240   return true;
14241 }
14242
14243 /// Walk up chain skipping non-aliasing memory nodes,
14244 /// looking for aliasing nodes and adding them to the Aliases vector.
14245 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14246                                    SmallVectorImpl<SDValue> &Aliases) {
14247   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14248   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14249
14250   // Get alias information for node.
14251   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14252
14253   // Starting off.
14254   Chains.push_back(OriginalChain);
14255   unsigned Depth = 0;
14256
14257   // Look at each chain and determine if it is an alias.  If so, add it to the
14258   // aliases list.  If not, then continue up the chain looking for the next
14259   // candidate.
14260   while (!Chains.empty()) {
14261     SDValue Chain = Chains.pop_back_val();
14262
14263     // For TokenFactor nodes, look at each operand and only continue up the
14264     // chain until we reach the depth limit.
14265     //
14266     // FIXME: The depth check could be made to return the last non-aliasing
14267     // chain we found before we hit a tokenfactor rather than the original
14268     // chain.
14269     if (Depth > 6) {
14270       Aliases.clear();
14271       Aliases.push_back(OriginalChain);
14272       return;
14273     }
14274
14275     // Don't bother if we've been before.
14276     if (!Visited.insert(Chain.getNode()).second)
14277       continue;
14278
14279     switch (Chain.getOpcode()) {
14280     case ISD::EntryToken:
14281       // Entry token is ideal chain operand, but handled in FindBetterChain.
14282       break;
14283
14284     case ISD::LOAD:
14285     case ISD::STORE: {
14286       // Get alias information for Chain.
14287       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14288           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14289
14290       // If chain is alias then stop here.
14291       if (!(IsLoad && IsOpLoad) &&
14292           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14293         Aliases.push_back(Chain);
14294       } else {
14295         // Look further up the chain.
14296         Chains.push_back(Chain.getOperand(0));
14297         ++Depth;
14298       }
14299       break;
14300     }
14301
14302     case ISD::TokenFactor:
14303       // We have to check each of the operands of the token factor for "small"
14304       // token factors, so we queue them up.  Adding the operands to the queue
14305       // (stack) in reverse order maintains the original order and increases the
14306       // likelihood that getNode will find a matching token factor (CSE.)
14307       if (Chain.getNumOperands() > 16) {
14308         Aliases.push_back(Chain);
14309         break;
14310       }
14311       for (unsigned n = Chain.getNumOperands(); n;)
14312         Chains.push_back(Chain.getOperand(--n));
14313       ++Depth;
14314       break;
14315
14316     default:
14317       // For all other instructions we will just have to take what we can get.
14318       Aliases.push_back(Chain);
14319       break;
14320     }
14321   }
14322
14323   // We need to be careful here to also search for aliases through the
14324   // value operand of a store, etc. Consider the following situation:
14325   //   Token1 = ...
14326   //   L1 = load Token1, %52
14327   //   S1 = store Token1, L1, %51
14328   //   L2 = load Token1, %52+8
14329   //   S2 = store Token1, L2, %51+8
14330   //   Token2 = Token(S1, S2)
14331   //   L3 = load Token2, %53
14332   //   S3 = store Token2, L3, %52
14333   //   L4 = load Token2, %53+8
14334   //   S4 = store Token2, L4, %52+8
14335   // If we search for aliases of S3 (which loads address %52), and we look
14336   // only through the chain, then we'll miss the trivial dependence on L1
14337   // (which also loads from %52). We then might change all loads and
14338   // stores to use Token1 as their chain operand, which could result in
14339   // copying %53 into %52 before copying %52 into %51 (which should
14340   // happen first).
14341   //
14342   // The problem is, however, that searching for such data dependencies
14343   // can become expensive, and the cost is not directly related to the
14344   // chain depth. Instead, we'll rule out such configurations here by
14345   // insisting that we've visited all chain users (except for users
14346   // of the original chain, which is not necessary). When doing this,
14347   // we need to look through nodes we don't care about (otherwise, things
14348   // like register copies will interfere with trivial cases).
14349
14350   SmallVector<const SDNode *, 16> Worklist;
14351   for (const SDNode *N : Visited)
14352     if (N != OriginalChain.getNode())
14353       Worklist.push_back(N);
14354
14355   while (!Worklist.empty()) {
14356     const SDNode *M = Worklist.pop_back_val();
14357
14358     // We have already visited M, and want to make sure we've visited any uses
14359     // of M that we care about. For uses that we've not visisted, and don't
14360     // care about, queue them to the worklist.
14361
14362     for (SDNode::use_iterator UI = M->use_begin(),
14363          UIE = M->use_end(); UI != UIE; ++UI)
14364       if (UI.getUse().getValueType() == MVT::Other &&
14365           Visited.insert(*UI).second) {
14366         if (isa<MemSDNode>(*UI)) {
14367           // We've not visited this use, and we care about it (it could have an
14368           // ordering dependency with the original node).
14369           Aliases.clear();
14370           Aliases.push_back(OriginalChain);
14371           return;
14372         }
14373
14374         // We've not visited this use, but we don't care about it. Mark it as
14375         // visited and enqueue it to the worklist.
14376         Worklist.push_back(*UI);
14377       }
14378   }
14379 }
14380
14381 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14382 /// (aliasing node.)
14383 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14384   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14385
14386   // Accumulate all the aliases to this node.
14387   GatherAllAliases(N, OldChain, Aliases);
14388
14389   // If no operands then chain to entry token.
14390   if (Aliases.size() == 0)
14391     return DAG.getEntryNode();
14392
14393   // If a single operand then chain to it.  We don't need to revisit it.
14394   if (Aliases.size() == 1)
14395     return Aliases[0];
14396
14397   // Construct a custom tailored token factor.
14398   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14399 }
14400
14401 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14402   // This holds the base pointer, index, and the offset in bytes from the base
14403   // pointer.
14404   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14405
14406   // We must have a base and an offset.
14407   if (!BasePtr.Base.getNode())
14408     return false;
14409
14410   // Do not handle stores to undef base pointers.
14411   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14412     return false;
14413
14414   SmallVector<StoreSDNode *, 8> ChainedStores;
14415   ChainedStores.push_back(St);
14416
14417   // Walk up the chain and look for nodes with offsets from the same
14418   // base pointer. Stop when reaching an instruction with a different kind
14419   // or instruction which has a different base pointer.
14420   StoreSDNode *Index = St;
14421   while (Index) {
14422     // If the chain has more than one use, then we can't reorder the mem ops.
14423     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14424       break;
14425
14426     if (Index->isVolatile() || Index->isIndexed())
14427       break;
14428
14429     // Find the base pointer and offset for this memory node.
14430     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14431
14432     // Check that the base pointer is the same as the original one.
14433     if (!Ptr.equalBaseIndex(BasePtr))
14434       break;
14435
14436     // Find the next memory operand in the chain. If the next operand in the
14437     // chain is a store then move up and continue the scan with the next
14438     // memory operand. If the next operand is a load save it and use alias
14439     // information to check if it interferes with anything.
14440     SDNode *NextInChain = Index->getChain().getNode();
14441     while (true) {
14442       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14443         // We found a store node. Use it for the next iteration.
14444         ChainedStores.push_back(STn);
14445         Index = STn;
14446         break;
14447       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14448         NextInChain = Ldn->getChain().getNode();
14449         continue;
14450       } else {
14451         Index = nullptr;
14452         break;
14453       }
14454     }
14455   }
14456
14457   bool MadeChange = false;
14458   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14459
14460   for (StoreSDNode *ChainedStore : ChainedStores) {
14461     SDValue Chain = ChainedStore->getChain();
14462     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14463
14464     if (Chain != BetterChain) {
14465       MadeChange = true;
14466       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14467     }
14468   }
14469
14470   // Do all replacements after finding the replacements to make to avoid making
14471   // the chains more complicated by introducing new TokenFactors.
14472   for (auto Replacement : BetterChains)
14473     replaceStoreChain(Replacement.first, Replacement.second);
14474
14475   return MadeChange;
14476 }
14477
14478 /// This is the entry point for the file.
14479 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14480                            CodeGenOpt::Level OptLevel) {
14481   /// This is the main entry point to this class.
14482   DAGCombiner(*this, AA, OptLevel).Run(Level);
14483 }