ae2fc14fb50c44663a19af64d3c148f154da7bba
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitIMINMAX(SDNode *N);
249     SDValue visitAND(SDNode *N);
250     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
251     SDValue visitOR(SDNode *N);
252     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitXOR(SDNode *N);
254     SDValue SimplifyVBinOp(SDNode *N);
255     SDValue visitSHL(SDNode *N);
256     SDValue visitSRA(SDNode *N);
257     SDValue visitSRL(SDNode *N);
258     SDValue visitRotate(SDNode *N);
259     SDValue visitBSWAP(SDNode *N);
260     SDValue visitCTLZ(SDNode *N);
261     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTTZ(SDNode *N);
263     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
264     SDValue visitCTPOP(SDNode *N);
265     SDValue visitSELECT(SDNode *N);
266     SDValue visitVSELECT(SDNode *N);
267     SDValue visitSELECT_CC(SDNode *N);
268     SDValue visitSETCC(SDNode *N);
269     SDValue visitSIGN_EXTEND(SDNode *N);
270     SDValue visitZERO_EXTEND(SDNode *N);
271     SDValue visitANY_EXTEND(SDNode *N);
272     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
273     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
274     SDValue visitTRUNCATE(SDNode *N);
275     SDValue visitBITCAST(SDNode *N);
276     SDValue visitBUILD_PAIR(SDNode *N);
277     SDValue visitFADD(SDNode *N);
278     SDValue visitFSUB(SDNode *N);
279     SDValue visitFMUL(SDNode *N);
280     SDValue visitFMA(SDNode *N);
281     SDValue visitFDIV(SDNode *N);
282     SDValue visitFREM(SDNode *N);
283     SDValue visitFSQRT(SDNode *N);
284     SDValue visitFCOPYSIGN(SDNode *N);
285     SDValue visitSINT_TO_FP(SDNode *N);
286     SDValue visitUINT_TO_FP(SDNode *N);
287     SDValue visitFP_TO_SINT(SDNode *N);
288     SDValue visitFP_TO_UINT(SDNode *N);
289     SDValue visitFP_ROUND(SDNode *N);
290     SDValue visitFP_ROUND_INREG(SDNode *N);
291     SDValue visitFP_EXTEND(SDNode *N);
292     SDValue visitFNEG(SDNode *N);
293     SDValue visitFABS(SDNode *N);
294     SDValue visitFCEIL(SDNode *N);
295     SDValue visitFTRUNC(SDNode *N);
296     SDValue visitFFLOOR(SDNode *N);
297     SDValue visitFMINNUM(SDNode *N);
298     SDValue visitFMAXNUM(SDNode *N);
299     SDValue visitBRCOND(SDNode *N);
300     SDValue visitBR_CC(SDNode *N);
301     SDValue visitLOAD(SDNode *N);
302
303     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
304
305     SDValue visitSTORE(SDNode *N);
306     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
307     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
308     SDValue visitBUILD_VECTOR(SDNode *N);
309     SDValue visitCONCAT_VECTORS(SDNode *N);
310     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
311     SDValue visitVECTOR_SHUFFLE(SDNode *N);
312     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
313     SDValue visitINSERT_SUBVECTOR(SDNode *N);
314     SDValue visitMLOAD(SDNode *N);
315     SDValue visitMSTORE(SDNode *N);
316     SDValue visitMGATHER(SDNode *N);
317     SDValue visitMSCATTER(SDNode *N);
318     SDValue visitFP_TO_FP16(SDNode *N);
319     SDValue visitFP16_TO_FP(SDNode *N);
320
321     SDValue visitFADDForFMACombine(SDNode *N);
322     SDValue visitFSUBForFMACombine(SDNode *N);
323
324     SDValue XformToShuffleWithZero(SDNode *N);
325     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
326
327     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
328
329     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
330     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
331     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
332     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
333                              SDValue N3, ISD::CondCode CC,
334                              bool NotExtCompare = false);
335     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
336                           SDLoc DL, bool foldBooleans = true);
337
338     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
339                            SDValue &CC) const;
340     bool isOneUseSetCC(SDValue N) const;
341
342     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
343                                          unsigned HiOp);
344     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
345     SDValue CombineExtLoad(SDNode *N);
346     SDValue combineRepeatedFPDivisors(SDNode *N);
347     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
348     SDValue BuildSDIV(SDNode *N);
349     SDValue BuildSDIVPow2(SDNode *N);
350     SDValue BuildUDIV(SDNode *N);
351     SDValue BuildReciprocalEstimate(SDValue Op);
352     SDValue BuildRsqrtEstimate(SDValue Op);
353     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
354     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
355     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
356                                bool DemandHighBits = true);
357     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
358     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
359                               SDValue InnerPos, SDValue InnerNeg,
360                               unsigned PosOpcode, unsigned NegOpcode,
361                               SDLoc DL);
362     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
363     SDValue ReduceLoadWidth(SDNode *N);
364     SDValue ReduceLoadOpStoreWidth(SDNode *N);
365     SDValue TransformFPLoadStorePair(SDNode *N);
366     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
367     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
368
369     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
370
371     /// Walk up chain skipping non-aliasing memory nodes,
372     /// looking for aliasing nodes and adding them to the Aliases vector.
373     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
374                           SmallVectorImpl<SDValue> &Aliases);
375
376     /// Return true if there is any possibility that the two addresses overlap.
377     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
378
379     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
380     /// chain (aliasing node.)
381     SDValue FindBetterChain(SDNode *N, SDValue Chain);
382
383     /// Do FindBetterChain for a store and any possibly adjacent stores on
384     /// consecutive chains.
385     bool findBetterNeighborChains(StoreSDNode *St);
386
387     /// Holds a pointer to an LSBaseSDNode as well as information on where it
388     /// is located in a sequence of memory operations connected by a chain.
389     struct MemOpLink {
390       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
391       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
392       // Ptr to the mem node.
393       LSBaseSDNode *MemNode;
394       // Offset from the base ptr.
395       int64_t OffsetFromBase;
396       // What is the sequence number of this mem node.
397       // Lowest mem operand in the DAG starts at zero.
398       unsigned SequenceNum;
399     };
400
401     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
402     /// constant build_vector of the stored constant values in Stores.
403     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
404                                          SDLoc SL,
405                                          ArrayRef<MemOpLink> Stores,
406                                          EVT Ty) const;
407
408     /// This is a helper function for MergeConsecutiveStores. When the source
409     /// elements of the consecutive stores are all constants or all extracted
410     /// vector elements, try to merge them into one larger store.
411     /// \return True if a merged store was created.
412     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
413                                          EVT MemVT, unsigned NumStores,
414                                          bool IsConstantSrc, bool UseVector);
415
416     /// This is a helper function for MergeConsecutiveStores.
417     /// Stores that may be merged are placed in StoreNodes.
418     /// Loads that may alias with those stores are placed in AliasLoadNodes.
419     void getStoreMergeAndAliasCandidates(
420         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
421         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
422
423     /// Merge consecutive store operations into a wide store.
424     /// This optimization uses wide integers or vectors when possible.
425     /// \return True if some memory operations were changed.
426     bool MergeConsecutiveStores(StoreSDNode *N);
427
428     /// \brief Try to transform a truncation where C is a constant:
429     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
430     ///
431     /// \p N needs to be a truncation and its first operand an AND. Other
432     /// requirements are checked by the function (e.g. that trunc is
433     /// single-use) and if missed an empty SDValue is returned.
434     SDValue distributeTruncateThroughAnd(SDNode *N);
435
436   public:
437     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
438         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
439           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
440       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
441     }
442
443     /// Runs the dag combiner on all nodes in the work list
444     void Run(CombineLevel AtLevel);
445
446     SelectionDAG &getDAG() const { return DAG; }
447
448     /// Returns a type large enough to hold any valid shift amount - before type
449     /// legalization these can be huge.
450     EVT getShiftAmountTy(EVT LHSTy) {
451       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
452       if (LHSTy.isVector())
453         return LHSTy;
454       auto &DL = DAG.getDataLayout();
455       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
456                         : TLI.getPointerTy(DL);
457     }
458
459     /// This method returns true if we are running before type legalization or
460     /// if the specified VT is legal.
461     bool isTypeLegal(const EVT &VT) {
462       if (!LegalTypes) return true;
463       return TLI.isTypeLegal(VT);
464     }
465
466     /// Convenience wrapper around TargetLowering::getSetCCResultType
467     EVT getSetCCResultType(EVT VT) const {
468       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
469     }
470   };
471 }
472
473
474 namespace {
475 /// This class is a DAGUpdateListener that removes any deleted
476 /// nodes from the worklist.
477 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
478   DAGCombiner &DC;
479 public:
480   explicit WorklistRemover(DAGCombiner &dc)
481     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
482
483   void NodeDeleted(SDNode *N, SDNode *E) override {
484     DC.removeFromWorklist(N);
485   }
486 };
487 }
488
489 //===----------------------------------------------------------------------===//
490 //  TargetLowering::DAGCombinerInfo implementation
491 //===----------------------------------------------------------------------===//
492
493 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
494   ((DAGCombiner*)DC)->AddToWorklist(N);
495 }
496
497 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
498   ((DAGCombiner*)DC)->removeFromWorklist(N);
499 }
500
501 SDValue TargetLowering::DAGCombinerInfo::
502 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
503   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
504 }
505
506 SDValue TargetLowering::DAGCombinerInfo::
507 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
508   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
509 }
510
511
512 SDValue TargetLowering::DAGCombinerInfo::
513 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
514   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
515 }
516
517 void TargetLowering::DAGCombinerInfo::
518 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
519   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
520 }
521
522 //===----------------------------------------------------------------------===//
523 // Helper Functions
524 //===----------------------------------------------------------------------===//
525
526 void DAGCombiner::deleteAndRecombine(SDNode *N) {
527   removeFromWorklist(N);
528
529   // If the operands of this node are only used by the node, they will now be
530   // dead. Make sure to re-visit them and recursively delete dead nodes.
531   for (const SDValue &Op : N->ops())
532     // For an operand generating multiple values, one of the values may
533     // become dead allowing further simplification (e.g. split index
534     // arithmetic from an indexed load).
535     if (Op->hasOneUse() || Op->getNumValues() > 1)
536       AddToWorklist(Op.getNode());
537
538   DAG.DeleteNode(N);
539 }
540
541 /// Return 1 if we can compute the negated form of the specified expression for
542 /// the same cost as the expression itself, or 2 if we can compute the negated
543 /// form more cheaply than the expression itself.
544 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
545                                const TargetLowering &TLI,
546                                const TargetOptions *Options,
547                                unsigned Depth = 0) {
548   // fneg is removable even if it has multiple uses.
549   if (Op.getOpcode() == ISD::FNEG) return 2;
550
551   // Don't allow anything with multiple uses.
552   if (!Op.hasOneUse()) return 0;
553
554   // Don't recurse exponentially.
555   if (Depth > 6) return 0;
556
557   switch (Op.getOpcode()) {
558   default: return false;
559   case ISD::ConstantFP:
560     // Don't invert constant FP values after legalize.  The negated constant
561     // isn't necessarily legal.
562     return LegalOperations ? 0 : 1;
563   case ISD::FADD:
564     // FIXME: determine better conditions for this xform.
565     if (!Options->UnsafeFPMath) return 0;
566
567     // After operation legalization, it might not be legal to create new FSUBs.
568     if (LegalOperations &&
569         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
570       return 0;
571
572     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
573     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
574                                     Options, Depth + 1))
575       return V;
576     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
577     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
578                               Depth + 1);
579   case ISD::FSUB:
580     // We can't turn -(A-B) into B-A when we honor signed zeros.
581     if (!Options->UnsafeFPMath) return 0;
582
583     // fold (fneg (fsub A, B)) -> (fsub B, A)
584     return 1;
585
586   case ISD::FMUL:
587   case ISD::FDIV:
588     if (Options->HonorSignDependentRoundingFPMath()) return 0;
589
590     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
591     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
592                                     Options, Depth + 1))
593       return V;
594
595     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
596                               Depth + 1);
597
598   case ISD::FP_EXTEND:
599   case ISD::FP_ROUND:
600   case ISD::FSIN:
601     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
602                               Depth + 1);
603   }
604 }
605
606 /// If isNegatibleForFree returns true, return the newly negated expression.
607 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
608                                     bool LegalOperations, unsigned Depth = 0) {
609   const TargetOptions &Options = DAG.getTarget().Options;
610   // fneg is removable even if it has multiple uses.
611   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
612
613   // Don't allow anything with multiple uses.
614   assert(Op.hasOneUse() && "Unknown reuse!");
615
616   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
617   switch (Op.getOpcode()) {
618   default: llvm_unreachable("Unknown code");
619   case ISD::ConstantFP: {
620     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
621     V.changeSign();
622     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
623   }
624   case ISD::FADD:
625     // FIXME: determine better conditions for this xform.
626     assert(Options.UnsafeFPMath);
627
628     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
629     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
630                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
631       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
632                          GetNegatedExpression(Op.getOperand(0), DAG,
633                                               LegalOperations, Depth+1),
634                          Op.getOperand(1));
635     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
636     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
637                        GetNegatedExpression(Op.getOperand(1), DAG,
638                                             LegalOperations, Depth+1),
639                        Op.getOperand(0));
640   case ISD::FSUB:
641     // We can't turn -(A-B) into B-A when we honor signed zeros.
642     assert(Options.UnsafeFPMath);
643
644     // fold (fneg (fsub 0, B)) -> B
645     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
646       if (N0CFP->isZero())
647         return Op.getOperand(1);
648
649     // fold (fneg (fsub A, B)) -> (fsub B, A)
650     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
651                        Op.getOperand(1), Op.getOperand(0));
652
653   case ISD::FMUL:
654   case ISD::FDIV:
655     assert(!Options.HonorSignDependentRoundingFPMath());
656
657     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
658     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
659                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
660       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
661                          GetNegatedExpression(Op.getOperand(0), DAG,
662                                               LegalOperations, Depth+1),
663                          Op.getOperand(1));
664
665     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
666     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
667                        Op.getOperand(0),
668                        GetNegatedExpression(Op.getOperand(1), DAG,
669                                             LegalOperations, Depth+1));
670
671   case ISD::FP_EXTEND:
672   case ISD::FSIN:
673     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
674                        GetNegatedExpression(Op.getOperand(0), DAG,
675                                             LegalOperations, Depth+1));
676   case ISD::FP_ROUND:
677       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
678                          GetNegatedExpression(Op.getOperand(0), DAG,
679                                               LegalOperations, Depth+1),
680                          Op.getOperand(1));
681   }
682 }
683
684 // Return true if this node is a setcc, or is a select_cc
685 // that selects between the target values used for true and false, making it
686 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
687 // the appropriate nodes based on the type of node we are checking. This
688 // simplifies life a bit for the callers.
689 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
690                                     SDValue &CC) const {
691   if (N.getOpcode() == ISD::SETCC) {
692     LHS = N.getOperand(0);
693     RHS = N.getOperand(1);
694     CC  = N.getOperand(2);
695     return true;
696   }
697
698   if (N.getOpcode() != ISD::SELECT_CC ||
699       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
700       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
701     return false;
702
703   if (TLI.getBooleanContents(N.getValueType()) ==
704       TargetLowering::UndefinedBooleanContent)
705     return false;
706
707   LHS = N.getOperand(0);
708   RHS = N.getOperand(1);
709   CC  = N.getOperand(4);
710   return true;
711 }
712
713 /// Return true if this is a SetCC-equivalent operation with only one use.
714 /// If this is true, it allows the users to invert the operation for free when
715 /// it is profitable to do so.
716 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
717   SDValue N0, N1, N2;
718   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
719     return true;
720   return false;
721 }
722
723 /// Returns true if N is a BUILD_VECTOR node whose
724 /// elements are all the same constant or undefined.
725 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
726   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
727   if (!C)
728     return false;
729
730   APInt SplatUndef;
731   unsigned SplatBitSize;
732   bool HasAnyUndefs;
733   EVT EltVT = N->getValueType(0).getVectorElementType();
734   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
735                              HasAnyUndefs) &&
736           EltVT.getSizeInBits() >= SplatBitSize);
737 }
738
739 // \brief Returns the SDNode if it is a constant integer BuildVector
740 // or constant integer.
741 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
742   if (isa<ConstantSDNode>(N))
743     return N.getNode();
744   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
745     return N.getNode();
746   return nullptr;
747 }
748
749 // \brief Returns the SDNode if it is a constant float BuildVector
750 // or constant float.
751 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
752   if (isa<ConstantFPSDNode>(N))
753     return N.getNode();
754   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
755     return N.getNode();
756   return nullptr;
757 }
758
759 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
760 // int.
761 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
762   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
763     return CN;
764
765   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
766     BitVector UndefElements;
767     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
768
769     // BuildVectors can truncate their operands. Ignore that case here.
770     // FIXME: We blindly ignore splats which include undef which is overly
771     // pessimistic.
772     if (CN && UndefElements.none() &&
773         CN->getValueType(0) == N.getValueType().getScalarType())
774       return CN;
775   }
776
777   return nullptr;
778 }
779
780 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
781 // float.
782 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
783   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
784     return CN;
785
786   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
787     BitVector UndefElements;
788     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
789
790     if (CN && UndefElements.none())
791       return CN;
792   }
793
794   return nullptr;
795 }
796
797 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
798                                     SDValue N0, SDValue N1) {
799   EVT VT = N0.getValueType();
800   if (N0.getOpcode() == Opc) {
801     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
802       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
803         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
804         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
805           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
806         return SDValue();
807       }
808       if (N0.hasOneUse()) {
809         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
810         // use
811         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
812         if (!OpNode.getNode())
813           return SDValue();
814         AddToWorklist(OpNode.getNode());
815         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
816       }
817     }
818   }
819
820   if (N1.getOpcode() == Opc) {
821     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
822       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
823         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
824         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
825           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
826         return SDValue();
827       }
828       if (N1.hasOneUse()) {
829         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
830         // use
831         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
832         if (!OpNode.getNode())
833           return SDValue();
834         AddToWorklist(OpNode.getNode());
835         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
836       }
837     }
838   }
839
840   return SDValue();
841 }
842
843 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
844                                bool AddTo) {
845   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
846   ++NodesCombined;
847   DEBUG(dbgs() << "\nReplacing.1 ";
848         N->dump(&DAG);
849         dbgs() << "\nWith: ";
850         To[0].getNode()->dump(&DAG);
851         dbgs() << " and " << NumTo-1 << " other values\n");
852   for (unsigned i = 0, e = NumTo; i != e; ++i)
853     assert((!To[i].getNode() ||
854             N->getValueType(i) == To[i].getValueType()) &&
855            "Cannot combine value to value of different type!");
856
857   WorklistRemover DeadNodes(*this);
858   DAG.ReplaceAllUsesWith(N, To);
859   if (AddTo) {
860     // Push the new nodes and any users onto the worklist
861     for (unsigned i = 0, e = NumTo; i != e; ++i) {
862       if (To[i].getNode()) {
863         AddToWorklist(To[i].getNode());
864         AddUsersToWorklist(To[i].getNode());
865       }
866     }
867   }
868
869   // Finally, if the node is now dead, remove it from the graph.  The node
870   // may not be dead if the replacement process recursively simplified to
871   // something else needing this node.
872   if (N->use_empty())
873     deleteAndRecombine(N);
874   return SDValue(N, 0);
875 }
876
877 void DAGCombiner::
878 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
879   // Replace all uses.  If any nodes become isomorphic to other nodes and
880   // are deleted, make sure to remove them from our worklist.
881   WorklistRemover DeadNodes(*this);
882   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
883
884   // Push the new node and any (possibly new) users onto the worklist.
885   AddToWorklist(TLO.New.getNode());
886   AddUsersToWorklist(TLO.New.getNode());
887
888   // Finally, if the node is now dead, remove it from the graph.  The node
889   // may not be dead if the replacement process recursively simplified to
890   // something else needing this node.
891   if (TLO.Old.getNode()->use_empty())
892     deleteAndRecombine(TLO.Old.getNode());
893 }
894
895 /// Check the specified integer node value to see if it can be simplified or if
896 /// things it uses can be simplified by bit propagation. If so, return true.
897 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
898   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
899   APInt KnownZero, KnownOne;
900   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
901     return false;
902
903   // Revisit the node.
904   AddToWorklist(Op.getNode());
905
906   // Replace the old value with the new one.
907   ++NodesCombined;
908   DEBUG(dbgs() << "\nReplacing.2 ";
909         TLO.Old.getNode()->dump(&DAG);
910         dbgs() << "\nWith: ";
911         TLO.New.getNode()->dump(&DAG);
912         dbgs() << '\n');
913
914   CommitTargetLoweringOpt(TLO);
915   return true;
916 }
917
918 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
919   SDLoc dl(Load);
920   EVT VT = Load->getValueType(0);
921   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
922
923   DEBUG(dbgs() << "\nReplacing.9 ";
924         Load->dump(&DAG);
925         dbgs() << "\nWith: ";
926         Trunc.getNode()->dump(&DAG);
927         dbgs() << '\n');
928   WorklistRemover DeadNodes(*this);
929   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
930   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
931   deleteAndRecombine(Load);
932   AddToWorklist(Trunc.getNode());
933 }
934
935 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
936   Replace = false;
937   SDLoc dl(Op);
938   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
939     EVT MemVT = LD->getMemoryVT();
940     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
941       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
942                                                        : ISD::EXTLOAD)
943       : LD->getExtensionType();
944     Replace = true;
945     return DAG.getExtLoad(ExtType, dl, PVT,
946                           LD->getChain(), LD->getBasePtr(),
947                           MemVT, LD->getMemOperand());
948   }
949
950   unsigned Opc = Op.getOpcode();
951   switch (Opc) {
952   default: break;
953   case ISD::AssertSext:
954     return DAG.getNode(ISD::AssertSext, dl, PVT,
955                        SExtPromoteOperand(Op.getOperand(0), PVT),
956                        Op.getOperand(1));
957   case ISD::AssertZext:
958     return DAG.getNode(ISD::AssertZext, dl, PVT,
959                        ZExtPromoteOperand(Op.getOperand(0), PVT),
960                        Op.getOperand(1));
961   case ISD::Constant: {
962     unsigned ExtOpc =
963       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
964     return DAG.getNode(ExtOpc, dl, PVT, Op);
965   }
966   }
967
968   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
969     return SDValue();
970   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
971 }
972
973 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
974   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
975     return SDValue();
976   EVT OldVT = Op.getValueType();
977   SDLoc dl(Op);
978   bool Replace = false;
979   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
980   if (!NewOp.getNode())
981     return SDValue();
982   AddToWorklist(NewOp.getNode());
983
984   if (Replace)
985     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
986   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
987                      DAG.getValueType(OldVT));
988 }
989
990 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
991   EVT OldVT = Op.getValueType();
992   SDLoc dl(Op);
993   bool Replace = false;
994   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
995   if (!NewOp.getNode())
996     return SDValue();
997   AddToWorklist(NewOp.getNode());
998
999   if (Replace)
1000     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1001   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1002 }
1003
1004 /// Promote the specified integer binary operation if the target indicates it is
1005 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1006 /// i32 since i16 instructions are longer.
1007 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1008   if (!LegalOperations)
1009     return SDValue();
1010
1011   EVT VT = Op.getValueType();
1012   if (VT.isVector() || !VT.isInteger())
1013     return SDValue();
1014
1015   // If operation type is 'undesirable', e.g. i16 on x86, consider
1016   // promoting it.
1017   unsigned Opc = Op.getOpcode();
1018   if (TLI.isTypeDesirableForOp(Opc, VT))
1019     return SDValue();
1020
1021   EVT PVT = VT;
1022   // Consult target whether it is a good idea to promote this operation and
1023   // what's the right type to promote it to.
1024   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1025     assert(PVT != VT && "Don't know what type to promote to!");
1026
1027     bool Replace0 = false;
1028     SDValue N0 = Op.getOperand(0);
1029     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1030     if (!NN0.getNode())
1031       return SDValue();
1032
1033     bool Replace1 = false;
1034     SDValue N1 = Op.getOperand(1);
1035     SDValue NN1;
1036     if (N0 == N1)
1037       NN1 = NN0;
1038     else {
1039       NN1 = PromoteOperand(N1, PVT, Replace1);
1040       if (!NN1.getNode())
1041         return SDValue();
1042     }
1043
1044     AddToWorklist(NN0.getNode());
1045     if (NN1.getNode())
1046       AddToWorklist(NN1.getNode());
1047
1048     if (Replace0)
1049       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1050     if (Replace1)
1051       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1052
1053     DEBUG(dbgs() << "\nPromoting ";
1054           Op.getNode()->dump(&DAG));
1055     SDLoc dl(Op);
1056     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1057                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1058   }
1059   return SDValue();
1060 }
1061
1062 /// Promote the specified integer shift operation if the target indicates it is
1063 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1064 /// i32 since i16 instructions are longer.
1065 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1066   if (!LegalOperations)
1067     return SDValue();
1068
1069   EVT VT = Op.getValueType();
1070   if (VT.isVector() || !VT.isInteger())
1071     return SDValue();
1072
1073   // If operation type is 'undesirable', e.g. i16 on x86, consider
1074   // promoting it.
1075   unsigned Opc = Op.getOpcode();
1076   if (TLI.isTypeDesirableForOp(Opc, VT))
1077     return SDValue();
1078
1079   EVT PVT = VT;
1080   // Consult target whether it is a good idea to promote this operation and
1081   // what's the right type to promote it to.
1082   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1083     assert(PVT != VT && "Don't know what type to promote to!");
1084
1085     bool Replace = false;
1086     SDValue N0 = Op.getOperand(0);
1087     if (Opc == ISD::SRA)
1088       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1089     else if (Opc == ISD::SRL)
1090       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1091     else
1092       N0 = PromoteOperand(N0, PVT, Replace);
1093     if (!N0.getNode())
1094       return SDValue();
1095
1096     AddToWorklist(N0.getNode());
1097     if (Replace)
1098       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1099
1100     DEBUG(dbgs() << "\nPromoting ";
1101           Op.getNode()->dump(&DAG));
1102     SDLoc dl(Op);
1103     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1104                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1105   }
1106   return SDValue();
1107 }
1108
1109 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1110   if (!LegalOperations)
1111     return SDValue();
1112
1113   EVT VT = Op.getValueType();
1114   if (VT.isVector() || !VT.isInteger())
1115     return SDValue();
1116
1117   // If operation type is 'undesirable', e.g. i16 on x86, consider
1118   // promoting it.
1119   unsigned Opc = Op.getOpcode();
1120   if (TLI.isTypeDesirableForOp(Opc, VT))
1121     return SDValue();
1122
1123   EVT PVT = VT;
1124   // Consult target whether it is a good idea to promote this operation and
1125   // what's the right type to promote it to.
1126   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1127     assert(PVT != VT && "Don't know what type to promote to!");
1128     // fold (aext (aext x)) -> (aext x)
1129     // fold (aext (zext x)) -> (zext x)
1130     // fold (aext (sext x)) -> (sext x)
1131     DEBUG(dbgs() << "\nPromoting ";
1132           Op.getNode()->dump(&DAG));
1133     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1134   }
1135   return SDValue();
1136 }
1137
1138 bool DAGCombiner::PromoteLoad(SDValue Op) {
1139   if (!LegalOperations)
1140     return false;
1141
1142   EVT VT = Op.getValueType();
1143   if (VT.isVector() || !VT.isInteger())
1144     return false;
1145
1146   // If operation type is 'undesirable', e.g. i16 on x86, consider
1147   // promoting it.
1148   unsigned Opc = Op.getOpcode();
1149   if (TLI.isTypeDesirableForOp(Opc, VT))
1150     return false;
1151
1152   EVT PVT = VT;
1153   // Consult target whether it is a good idea to promote this operation and
1154   // what's the right type to promote it to.
1155   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1156     assert(PVT != VT && "Don't know what type to promote to!");
1157
1158     SDLoc dl(Op);
1159     SDNode *N = Op.getNode();
1160     LoadSDNode *LD = cast<LoadSDNode>(N);
1161     EVT MemVT = LD->getMemoryVT();
1162     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1163       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1164                                                        : ISD::EXTLOAD)
1165       : LD->getExtensionType();
1166     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1167                                    LD->getChain(), LD->getBasePtr(),
1168                                    MemVT, LD->getMemOperand());
1169     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1170
1171     DEBUG(dbgs() << "\nPromoting ";
1172           N->dump(&DAG);
1173           dbgs() << "\nTo: ";
1174           Result.getNode()->dump(&DAG);
1175           dbgs() << '\n');
1176     WorklistRemover DeadNodes(*this);
1177     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1178     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1179     deleteAndRecombine(N);
1180     AddToWorklist(Result.getNode());
1181     return true;
1182   }
1183   return false;
1184 }
1185
1186 /// \brief Recursively delete a node which has no uses and any operands for
1187 /// which it is the only use.
1188 ///
1189 /// Note that this both deletes the nodes and removes them from the worklist.
1190 /// It also adds any nodes who have had a user deleted to the worklist as they
1191 /// may now have only one use and subject to other combines.
1192 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1193   if (!N->use_empty())
1194     return false;
1195
1196   SmallSetVector<SDNode *, 16> Nodes;
1197   Nodes.insert(N);
1198   do {
1199     N = Nodes.pop_back_val();
1200     if (!N)
1201       continue;
1202
1203     if (N->use_empty()) {
1204       for (const SDValue &ChildN : N->op_values())
1205         Nodes.insert(ChildN.getNode());
1206
1207       removeFromWorklist(N);
1208       DAG.DeleteNode(N);
1209     } else {
1210       AddToWorklist(N);
1211     }
1212   } while (!Nodes.empty());
1213   return true;
1214 }
1215
1216 //===----------------------------------------------------------------------===//
1217 //  Main DAG Combiner implementation
1218 //===----------------------------------------------------------------------===//
1219
1220 void DAGCombiner::Run(CombineLevel AtLevel) {
1221   // set the instance variables, so that the various visit routines may use it.
1222   Level = AtLevel;
1223   LegalOperations = Level >= AfterLegalizeVectorOps;
1224   LegalTypes = Level >= AfterLegalizeTypes;
1225
1226   // Add all the dag nodes to the worklist.
1227   for (SDNode &Node : DAG.allnodes())
1228     AddToWorklist(&Node);
1229
1230   // Create a dummy node (which is not added to allnodes), that adds a reference
1231   // to the root node, preventing it from being deleted, and tracking any
1232   // changes of the root.
1233   HandleSDNode Dummy(DAG.getRoot());
1234
1235   // while the worklist isn't empty, find a node and
1236   // try and combine it.
1237   while (!WorklistMap.empty()) {
1238     SDNode *N;
1239     // The Worklist holds the SDNodes in order, but it may contain null entries.
1240     do {
1241       N = Worklist.pop_back_val();
1242     } while (!N);
1243
1244     bool GoodWorklistEntry = WorklistMap.erase(N);
1245     (void)GoodWorklistEntry;
1246     assert(GoodWorklistEntry &&
1247            "Found a worklist entry without a corresponding map entry!");
1248
1249     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1250     // N is deleted from the DAG, since they too may now be dead or may have a
1251     // reduced number of uses, allowing other xforms.
1252     if (recursivelyDeleteUnusedNodes(N))
1253       continue;
1254
1255     WorklistRemover DeadNodes(*this);
1256
1257     // If this combine is running after legalizing the DAG, re-legalize any
1258     // nodes pulled off the worklist.
1259     if (Level == AfterLegalizeDAG) {
1260       SmallSetVector<SDNode *, 16> UpdatedNodes;
1261       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1262
1263       for (SDNode *LN : UpdatedNodes) {
1264         AddToWorklist(LN);
1265         AddUsersToWorklist(LN);
1266       }
1267       if (!NIsValid)
1268         continue;
1269     }
1270
1271     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1272
1273     // Add any operands of the new node which have not yet been combined to the
1274     // worklist as well. Because the worklist uniques things already, this
1275     // won't repeatedly process the same operand.
1276     CombinedNodes.insert(N);
1277     for (const SDValue &ChildN : N->op_values())
1278       if (!CombinedNodes.count(ChildN.getNode()))
1279         AddToWorklist(ChildN.getNode());
1280
1281     SDValue RV = combine(N);
1282
1283     if (!RV.getNode())
1284       continue;
1285
1286     ++NodesCombined;
1287
1288     // If we get back the same node we passed in, rather than a new node or
1289     // zero, we know that the node must have defined multiple values and
1290     // CombineTo was used.  Since CombineTo takes care of the worklist
1291     // mechanics for us, we have no work to do in this case.
1292     if (RV.getNode() == N)
1293       continue;
1294
1295     assert(N->getOpcode() != ISD::DELETED_NODE &&
1296            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1297            "Node was deleted but visit returned new node!");
1298
1299     DEBUG(dbgs() << " ... into: ";
1300           RV.getNode()->dump(&DAG));
1301
1302     // Transfer debug value.
1303     DAG.TransferDbgValues(SDValue(N, 0), RV);
1304     if (N->getNumValues() == RV.getNode()->getNumValues())
1305       DAG.ReplaceAllUsesWith(N, RV.getNode());
1306     else {
1307       assert(N->getValueType(0) == RV.getValueType() &&
1308              N->getNumValues() == 1 && "Type mismatch");
1309       SDValue OpV = RV;
1310       DAG.ReplaceAllUsesWith(N, &OpV);
1311     }
1312
1313     // Push the new node and any users onto the worklist
1314     AddToWorklist(RV.getNode());
1315     AddUsersToWorklist(RV.getNode());
1316
1317     // Finally, if the node is now dead, remove it from the graph.  The node
1318     // may not be dead if the replacement process recursively simplified to
1319     // something else needing this node. This will also take care of adding any
1320     // operands which have lost a user to the worklist.
1321     recursivelyDeleteUnusedNodes(N);
1322   }
1323
1324   // If the root changed (e.g. it was a dead load, update the root).
1325   DAG.setRoot(Dummy.getValue());
1326   DAG.RemoveDeadNodes();
1327 }
1328
1329 SDValue DAGCombiner::visit(SDNode *N) {
1330   switch (N->getOpcode()) {
1331   default: break;
1332   case ISD::TokenFactor:        return visitTokenFactor(N);
1333   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1334   case ISD::ADD:                return visitADD(N);
1335   case ISD::SUB:                return visitSUB(N);
1336   case ISD::ADDC:               return visitADDC(N);
1337   case ISD::SUBC:               return visitSUBC(N);
1338   case ISD::ADDE:               return visitADDE(N);
1339   case ISD::SUBE:               return visitSUBE(N);
1340   case ISD::MUL:                return visitMUL(N);
1341   case ISD::SDIV:               return visitSDIV(N);
1342   case ISD::UDIV:               return visitUDIV(N);
1343   case ISD::SREM:               return visitSREM(N);
1344   case ISD::UREM:               return visitUREM(N);
1345   case ISD::MULHU:              return visitMULHU(N);
1346   case ISD::MULHS:              return visitMULHS(N);
1347   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1348   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1349   case ISD::SMULO:              return visitSMULO(N);
1350   case ISD::UMULO:              return visitUMULO(N);
1351   case ISD::SDIVREM:            return visitSDIVREM(N);
1352   case ISD::UDIVREM:            return visitUDIVREM(N);
1353   case ISD::SMIN:
1354   case ISD::SMAX:
1355   case ISD::UMIN:
1356   case ISD::UMAX:               return visitIMINMAX(N);
1357   case ISD::AND:                return visitAND(N);
1358   case ISD::OR:                 return visitOR(N);
1359   case ISD::XOR:                return visitXOR(N);
1360   case ISD::SHL:                return visitSHL(N);
1361   case ISD::SRA:                return visitSRA(N);
1362   case ISD::SRL:                return visitSRL(N);
1363   case ISD::ROTR:
1364   case ISD::ROTL:               return visitRotate(N);
1365   case ISD::BSWAP:              return visitBSWAP(N);
1366   case ISD::CTLZ:               return visitCTLZ(N);
1367   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1368   case ISD::CTTZ:               return visitCTTZ(N);
1369   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1370   case ISD::CTPOP:              return visitCTPOP(N);
1371   case ISD::SELECT:             return visitSELECT(N);
1372   case ISD::VSELECT:            return visitVSELECT(N);
1373   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1374   case ISD::SETCC:              return visitSETCC(N);
1375   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1376   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1377   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1378   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1379   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1380   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1381   case ISD::BITCAST:            return visitBITCAST(N);
1382   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1383   case ISD::FADD:               return visitFADD(N);
1384   case ISD::FSUB:               return visitFSUB(N);
1385   case ISD::FMUL:               return visitFMUL(N);
1386   case ISD::FMA:                return visitFMA(N);
1387   case ISD::FDIV:               return visitFDIV(N);
1388   case ISD::FREM:               return visitFREM(N);
1389   case ISD::FSQRT:              return visitFSQRT(N);
1390   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1391   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1392   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1393   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1394   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1395   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1396   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1397   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1398   case ISD::FNEG:               return visitFNEG(N);
1399   case ISD::FABS:               return visitFABS(N);
1400   case ISD::FFLOOR:             return visitFFLOOR(N);
1401   case ISD::FMINNUM:            return visitFMINNUM(N);
1402   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1403   case ISD::FCEIL:              return visitFCEIL(N);
1404   case ISD::FTRUNC:             return visitFTRUNC(N);
1405   case ISD::BRCOND:             return visitBRCOND(N);
1406   case ISD::BR_CC:              return visitBR_CC(N);
1407   case ISD::LOAD:               return visitLOAD(N);
1408   case ISD::STORE:              return visitSTORE(N);
1409   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1410   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1411   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1412   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1413   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1414   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1415   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1416   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1417   case ISD::MGATHER:            return visitMGATHER(N);
1418   case ISD::MLOAD:              return visitMLOAD(N);
1419   case ISD::MSCATTER:           return visitMSCATTER(N);
1420   case ISD::MSTORE:             return visitMSTORE(N);
1421   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1422   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1423   }
1424   return SDValue();
1425 }
1426
1427 SDValue DAGCombiner::combine(SDNode *N) {
1428   SDValue RV = visit(N);
1429
1430   // If nothing happened, try a target-specific DAG combine.
1431   if (!RV.getNode()) {
1432     assert(N->getOpcode() != ISD::DELETED_NODE &&
1433            "Node was deleted but visit returned NULL!");
1434
1435     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1436         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1437
1438       // Expose the DAG combiner to the target combiner impls.
1439       TargetLowering::DAGCombinerInfo
1440         DagCombineInfo(DAG, Level, false, this);
1441
1442       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1443     }
1444   }
1445
1446   // If nothing happened still, try promoting the operation.
1447   if (!RV.getNode()) {
1448     switch (N->getOpcode()) {
1449     default: break;
1450     case ISD::ADD:
1451     case ISD::SUB:
1452     case ISD::MUL:
1453     case ISD::AND:
1454     case ISD::OR:
1455     case ISD::XOR:
1456       RV = PromoteIntBinOp(SDValue(N, 0));
1457       break;
1458     case ISD::SHL:
1459     case ISD::SRA:
1460     case ISD::SRL:
1461       RV = PromoteIntShiftOp(SDValue(N, 0));
1462       break;
1463     case ISD::SIGN_EXTEND:
1464     case ISD::ZERO_EXTEND:
1465     case ISD::ANY_EXTEND:
1466       RV = PromoteExtend(SDValue(N, 0));
1467       break;
1468     case ISD::LOAD:
1469       if (PromoteLoad(SDValue(N, 0)))
1470         RV = SDValue(N, 0);
1471       break;
1472     }
1473   }
1474
1475   // If N is a commutative binary node, try commuting it to enable more
1476   // sdisel CSE.
1477   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1478       N->getNumValues() == 1) {
1479     SDValue N0 = N->getOperand(0);
1480     SDValue N1 = N->getOperand(1);
1481
1482     // Constant operands are canonicalized to RHS.
1483     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1484       SDValue Ops[] = {N1, N0};
1485       SDNode *CSENode;
1486       if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1487         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1488                                       &BinNode->Flags);
1489       } else {
1490         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1491       }
1492       if (CSENode)
1493         return SDValue(CSENode, 0);
1494     }
1495   }
1496
1497   return RV;
1498 }
1499
1500 /// Given a node, return its input chain if it has one, otherwise return a null
1501 /// sd operand.
1502 static SDValue getInputChainForNode(SDNode *N) {
1503   if (unsigned NumOps = N->getNumOperands()) {
1504     if (N->getOperand(0).getValueType() == MVT::Other)
1505       return N->getOperand(0);
1506     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1507       return N->getOperand(NumOps-1);
1508     for (unsigned i = 1; i < NumOps-1; ++i)
1509       if (N->getOperand(i).getValueType() == MVT::Other)
1510         return N->getOperand(i);
1511   }
1512   return SDValue();
1513 }
1514
1515 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1516   // If N has two operands, where one has an input chain equal to the other,
1517   // the 'other' chain is redundant.
1518   if (N->getNumOperands() == 2) {
1519     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1520       return N->getOperand(0);
1521     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1522       return N->getOperand(1);
1523   }
1524
1525   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1526   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1527   SmallPtrSet<SDNode*, 16> SeenOps;
1528   bool Changed = false;             // If we should replace this token factor.
1529
1530   // Start out with this token factor.
1531   TFs.push_back(N);
1532
1533   // Iterate through token factors.  The TFs grows when new token factors are
1534   // encountered.
1535   for (unsigned i = 0; i < TFs.size(); ++i) {
1536     SDNode *TF = TFs[i];
1537
1538     // Check each of the operands.
1539     for (const SDValue &Op : TF->op_values()) {
1540
1541       switch (Op.getOpcode()) {
1542       case ISD::EntryToken:
1543         // Entry tokens don't need to be added to the list. They are
1544         // redundant.
1545         Changed = true;
1546         break;
1547
1548       case ISD::TokenFactor:
1549         if (Op.hasOneUse() &&
1550             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1551           // Queue up for processing.
1552           TFs.push_back(Op.getNode());
1553           // Clean up in case the token factor is removed.
1554           AddToWorklist(Op.getNode());
1555           Changed = true;
1556           break;
1557         }
1558         // Fall thru
1559
1560       default:
1561         // Only add if it isn't already in the list.
1562         if (SeenOps.insert(Op.getNode()).second)
1563           Ops.push_back(Op);
1564         else
1565           Changed = true;
1566         break;
1567       }
1568     }
1569   }
1570
1571   SDValue Result;
1572
1573   // If we've changed things around then replace token factor.
1574   if (Changed) {
1575     if (Ops.empty()) {
1576       // The entry token is the only possible outcome.
1577       Result = DAG.getEntryNode();
1578     } else {
1579       // New and improved token factor.
1580       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1581     }
1582
1583     // Add users to worklist if AA is enabled, since it may introduce
1584     // a lot of new chained token factors while removing memory deps.
1585     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1586       : DAG.getSubtarget().useAA();
1587     return CombineTo(N, Result, UseAA /*add to worklist*/);
1588   }
1589
1590   return Result;
1591 }
1592
1593 /// MERGE_VALUES can always be eliminated.
1594 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1595   WorklistRemover DeadNodes(*this);
1596   // Replacing results may cause a different MERGE_VALUES to suddenly
1597   // be CSE'd with N, and carry its uses with it. Iterate until no
1598   // uses remain, to ensure that the node can be safely deleted.
1599   // First add the users of this node to the work list so that they
1600   // can be tried again once they have new operands.
1601   AddUsersToWorklist(N);
1602   do {
1603     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1604       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1605   } while (!N->use_empty());
1606   deleteAndRecombine(N);
1607   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1608 }
1609
1610 static bool isNullConstant(SDValue V) {
1611   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1612   return Const != nullptr && Const->isNullValue();
1613 }
1614
1615 static bool isNullFPConstant(SDValue V) {
1616   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1617   return Const != nullptr && Const->isZero() && !Const->isNegative();
1618 }
1619
1620 static bool isAllOnesConstant(SDValue V) {
1621   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1622   return Const != nullptr && Const->isAllOnesValue();
1623 }
1624
1625 static bool isOneConstant(SDValue V) {
1626   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1627   return Const != nullptr && Const->isOne();
1628 }
1629
1630 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1631 /// ContantSDNode pointer else nullptr.
1632 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1633   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1634   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1635 }
1636
1637 SDValue DAGCombiner::visitADD(SDNode *N) {
1638   SDValue N0 = N->getOperand(0);
1639   SDValue N1 = N->getOperand(1);
1640   EVT VT = N0.getValueType();
1641
1642   // fold vector ops
1643   if (VT.isVector()) {
1644     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1645       return FoldedVOp;
1646
1647     // fold (add x, 0) -> x, vector edition
1648     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1649       return N0;
1650     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1651       return N1;
1652   }
1653
1654   // fold (add x, undef) -> undef
1655   if (N0.getOpcode() == ISD::UNDEF)
1656     return N0;
1657   if (N1.getOpcode() == ISD::UNDEF)
1658     return N1;
1659   // fold (add c1, c2) -> c1+c2
1660   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1661   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1662   if (N0C && N1C)
1663     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1664   // canonicalize constant to RHS
1665   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1666      !isConstantIntBuildVectorOrConstantInt(N1))
1667     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1668   // fold (add x, 0) -> x
1669   if (isNullConstant(N1))
1670     return N0;
1671   // fold (add Sym, c) -> Sym+c
1672   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1673     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1674         GA->getOpcode() == ISD::GlobalAddress)
1675       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1676                                   GA->getOffset() +
1677                                     (uint64_t)N1C->getSExtValue());
1678   // fold ((c1-A)+c2) -> (c1+c2)-A
1679   if (N1C && N0.getOpcode() == ISD::SUB)
1680     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1681       SDLoc DL(N);
1682       return DAG.getNode(ISD::SUB, DL, VT,
1683                          DAG.getConstant(N1C->getAPIntValue()+
1684                                          N0C->getAPIntValue(), DL, VT),
1685                          N0.getOperand(1));
1686     }
1687   // reassociate add
1688   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1689     return RADD;
1690   // fold ((0-A) + B) -> B-A
1691   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1692     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1693   // fold (A + (0-B)) -> A-B
1694   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1695     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1696   // fold (A+(B-A)) -> B
1697   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1698     return N1.getOperand(0);
1699   // fold ((B-A)+A) -> B
1700   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1701     return N0.getOperand(0);
1702   // fold (A+(B-(A+C))) to (B-C)
1703   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1704       N0 == N1.getOperand(1).getOperand(0))
1705     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1706                        N1.getOperand(1).getOperand(1));
1707   // fold (A+(B-(C+A))) to (B-C)
1708   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1709       N0 == N1.getOperand(1).getOperand(1))
1710     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1711                        N1.getOperand(1).getOperand(0));
1712   // fold (A+((B-A)+or-C)) to (B+or-C)
1713   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1714       N1.getOperand(0).getOpcode() == ISD::SUB &&
1715       N0 == N1.getOperand(0).getOperand(1))
1716     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1717                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1718
1719   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1720   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1721     SDValue N00 = N0.getOperand(0);
1722     SDValue N01 = N0.getOperand(1);
1723     SDValue N10 = N1.getOperand(0);
1724     SDValue N11 = N1.getOperand(1);
1725
1726     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1727       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1728                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1729                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1730   }
1731
1732   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1733     return SDValue(N, 0);
1734
1735   // fold (a+b) -> (a|b) iff a and b share no bits.
1736   if (VT.isInteger() && !VT.isVector()) {
1737     APInt LHSZero, LHSOne;
1738     APInt RHSZero, RHSOne;
1739     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1740
1741     if (LHSZero.getBoolValue()) {
1742       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1743
1744       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1745       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1746       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1747         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1748           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1749       }
1750     }
1751   }
1752
1753   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1754   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1755       isNullConstant(N1.getOperand(0).getOperand(0)))
1756     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1757                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1758                                    N1.getOperand(0).getOperand(1),
1759                                    N1.getOperand(1)));
1760   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1761       isNullConstant(N0.getOperand(0).getOperand(0)))
1762     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1763                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1764                                    N0.getOperand(0).getOperand(1),
1765                                    N0.getOperand(1)));
1766
1767   if (N1.getOpcode() == ISD::AND) {
1768     SDValue AndOp0 = N1.getOperand(0);
1769     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1770     unsigned DestBits = VT.getScalarType().getSizeInBits();
1771
1772     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1773     // and similar xforms where the inner op is either ~0 or 0.
1774     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1775       SDLoc DL(N);
1776       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1777     }
1778   }
1779
1780   // add (sext i1), X -> sub X, (zext i1)
1781   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1782       N0.getOperand(0).getValueType() == MVT::i1 &&
1783       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1784     SDLoc DL(N);
1785     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1786     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1787   }
1788
1789   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1790   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1791     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1792     if (TN->getVT() == MVT::i1) {
1793       SDLoc DL(N);
1794       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1795                                  DAG.getConstant(1, DL, VT));
1796       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1797     }
1798   }
1799
1800   return SDValue();
1801 }
1802
1803 SDValue DAGCombiner::visitADDC(SDNode *N) {
1804   SDValue N0 = N->getOperand(0);
1805   SDValue N1 = N->getOperand(1);
1806   EVT VT = N0.getValueType();
1807
1808   // If the flag result is dead, turn this into an ADD.
1809   if (!N->hasAnyUseOfValue(1))
1810     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1811                      DAG.getNode(ISD::CARRY_FALSE,
1812                                  SDLoc(N), MVT::Glue));
1813
1814   // canonicalize constant to RHS.
1815   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1816   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1817   if (N0C && !N1C)
1818     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1819
1820   // fold (addc x, 0) -> x + no carry out
1821   if (isNullConstant(N1))
1822     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1823                                         SDLoc(N), MVT::Glue));
1824
1825   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1826   APInt LHSZero, LHSOne;
1827   APInt RHSZero, RHSOne;
1828   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1829
1830   if (LHSZero.getBoolValue()) {
1831     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1832
1833     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1834     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1835     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1836       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1837                        DAG.getNode(ISD::CARRY_FALSE,
1838                                    SDLoc(N), MVT::Glue));
1839   }
1840
1841   return SDValue();
1842 }
1843
1844 SDValue DAGCombiner::visitADDE(SDNode *N) {
1845   SDValue N0 = N->getOperand(0);
1846   SDValue N1 = N->getOperand(1);
1847   SDValue CarryIn = N->getOperand(2);
1848
1849   // canonicalize constant to RHS
1850   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1851   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1852   if (N0C && !N1C)
1853     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1854                        N1, N0, CarryIn);
1855
1856   // fold (adde x, y, false) -> (addc x, y)
1857   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1858     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1859
1860   return SDValue();
1861 }
1862
1863 // Since it may not be valid to emit a fold to zero for vector initializers
1864 // check if we can before folding.
1865 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1866                              SelectionDAG &DAG,
1867                              bool LegalOperations, bool LegalTypes) {
1868   if (!VT.isVector())
1869     return DAG.getConstant(0, DL, VT);
1870   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1871     return DAG.getConstant(0, DL, VT);
1872   return SDValue();
1873 }
1874
1875 SDValue DAGCombiner::visitSUB(SDNode *N) {
1876   SDValue N0 = N->getOperand(0);
1877   SDValue N1 = N->getOperand(1);
1878   EVT VT = N0.getValueType();
1879
1880   // fold vector ops
1881   if (VT.isVector()) {
1882     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1883       return FoldedVOp;
1884
1885     // fold (sub x, 0) -> x, vector edition
1886     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1887       return N0;
1888   }
1889
1890   // fold (sub x, x) -> 0
1891   // FIXME: Refactor this and xor and other similar operations together.
1892   if (N0 == N1)
1893     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1894   // fold (sub c1, c2) -> c1-c2
1895   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1896   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1897   if (N0C && N1C)
1898     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1899   // fold (sub x, c) -> (add x, -c)
1900   if (N1C) {
1901     SDLoc DL(N);
1902     return DAG.getNode(ISD::ADD, DL, VT, N0,
1903                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1904   }
1905   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1906   if (isAllOnesConstant(N0))
1907     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1908   // fold A-(A-B) -> B
1909   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1910     return N1.getOperand(1);
1911   // fold (A+B)-A -> B
1912   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1913     return N0.getOperand(1);
1914   // fold (A+B)-B -> A
1915   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1916     return N0.getOperand(0);
1917   // fold C2-(A+C1) -> (C2-C1)-A
1918   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1919     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1920   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1921     SDLoc DL(N);
1922     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1923                                    DL, VT);
1924     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1925                        N1.getOperand(0));
1926   }
1927   // fold ((A+(B+or-C))-B) -> A+or-C
1928   if (N0.getOpcode() == ISD::ADD &&
1929       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1930        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1931       N0.getOperand(1).getOperand(0) == N1)
1932     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1933                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1934   // fold ((A+(C+B))-B) -> A+C
1935   if (N0.getOpcode() == ISD::ADD &&
1936       N0.getOperand(1).getOpcode() == ISD::ADD &&
1937       N0.getOperand(1).getOperand(1) == N1)
1938     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1939                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1940   // fold ((A-(B-C))-C) -> A-B
1941   if (N0.getOpcode() == ISD::SUB &&
1942       N0.getOperand(1).getOpcode() == ISD::SUB &&
1943       N0.getOperand(1).getOperand(1) == N1)
1944     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1945                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1946
1947   // If either operand of a sub is undef, the result is undef
1948   if (N0.getOpcode() == ISD::UNDEF)
1949     return N0;
1950   if (N1.getOpcode() == ISD::UNDEF)
1951     return N1;
1952
1953   // If the relocation model supports it, consider symbol offsets.
1954   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1955     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1956       // fold (sub Sym, c) -> Sym-c
1957       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1958         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1959                                     GA->getOffset() -
1960                                       (uint64_t)N1C->getSExtValue());
1961       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1962       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1963         if (GA->getGlobal() == GB->getGlobal())
1964           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1965                                  SDLoc(N), VT);
1966     }
1967
1968   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1969   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1970     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1971     if (TN->getVT() == MVT::i1) {
1972       SDLoc DL(N);
1973       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1974                                  DAG.getConstant(1, DL, VT));
1975       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1976     }
1977   }
1978
1979   return SDValue();
1980 }
1981
1982 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1983   SDValue N0 = N->getOperand(0);
1984   SDValue N1 = N->getOperand(1);
1985   EVT VT = N0.getValueType();
1986
1987   // If the flag result is dead, turn this into an SUB.
1988   if (!N->hasAnyUseOfValue(1))
1989     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1990                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1991                                  MVT::Glue));
1992
1993   // fold (subc x, x) -> 0 + no borrow
1994   if (N0 == N1) {
1995     SDLoc DL(N);
1996     return CombineTo(N, DAG.getConstant(0, DL, VT),
1997                      DAG.getNode(ISD::CARRY_FALSE, DL,
1998                                  MVT::Glue));
1999   }
2000
2001   // fold (subc x, 0) -> x + no borrow
2002   if (isNullConstant(N1))
2003     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2004                                         MVT::Glue));
2005
2006   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2007   if (isAllOnesConstant(N0))
2008     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2009                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2010                                  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   // fold (sdiv c1, c2) -> c1/c2
2172   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2173   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2174   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2175     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2176   // fold (sdiv X, 1) -> X
2177   if (N1C && N1C->isOne())
2178     return N0;
2179   // fold (sdiv X, -1) -> 0-X
2180   if (N1C && N1C->isAllOnesValue()) {
2181     SDLoc DL(N);
2182     return DAG.getNode(ISD::SUB, DL, VT,
2183                        DAG.getConstant(0, DL, VT), N0);
2184   }
2185   // If we know the sign bits of both operands are zero, strength reduce to a
2186   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2187   if (!VT.isVector()) {
2188     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2189       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2190                          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     SDLoc DL(N);
2207
2208     // Splat the sign bit into the register
2209     SDValue SGN =
2210         DAG.getNode(ISD::SRA, DL, VT, N0,
2211                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2212                                     getShiftAmountTy(N0.getValueType())));
2213     AddToWorklist(SGN.getNode());
2214
2215     // Add (N0 < 0) ? abs2 - 1 : 0;
2216     SDValue SRL =
2217         DAG.getNode(ISD::SRL, DL, VT, SGN,
2218                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2219                                     getShiftAmountTy(SGN.getValueType())));
2220     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2221     AddToWorklist(SRL.getNode());
2222     AddToWorklist(ADD.getNode());    // Divide by pow2
2223     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2224                   DAG.getConstant(lg2, DL,
2225                                   getShiftAmountTy(ADD.getValueType())));
2226
2227     // If we're dividing by a positive value, we're done.  Otherwise, we must
2228     // negate the result.
2229     if (N1C->getAPIntValue().isNonNegative())
2230       return SRA;
2231
2232     AddToWorklist(SRA.getNode());
2233     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2234   }
2235
2236   // If integer divide is expensive and we satisfy the requirements, emit an
2237   // alternate sequence.  Targets may check function attributes for size/speed
2238   // trade-offs.
2239   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2240   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2241     if (SDValue Op = BuildSDIV(N))
2242       return Op;
2243
2244   // undef / X -> 0
2245   if (N0.getOpcode() == ISD::UNDEF)
2246     return DAG.getConstant(0, SDLoc(N), VT);
2247   // X / undef -> undef
2248   if (N1.getOpcode() == ISD::UNDEF)
2249     return N1;
2250
2251   return SDValue();
2252 }
2253
2254 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2255   SDValue N0 = N->getOperand(0);
2256   SDValue N1 = N->getOperand(1);
2257   EVT VT = N->getValueType(0);
2258
2259   // fold vector ops
2260   if (VT.isVector())
2261     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2262       return FoldedVOp;
2263
2264   // fold (udiv c1, c2) -> c1/c2
2265   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2266   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2267   if (N0C && N1C)
2268     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2269                                                     N0C, N1C))
2270       return Folded;
2271   // fold (udiv x, (1 << c)) -> x >>u c
2272   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2273     SDLoc DL(N);
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         SDLoc DL(N);
2284         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2285                                   N1.getOperand(1),
2286                                   DAG.getConstant(SHC->getAPIntValue()
2287                                                                   .logBase2(),
2288                                                   DL, ADDVT));
2289         AddToWorklist(Add.getNode());
2290         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2291       }
2292     }
2293   }
2294
2295   // fold (udiv x, c) -> alternate
2296   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2297   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2298     if (SDValue Op = BuildUDIV(N))
2299       return Op;
2300
2301   // undef / X -> 0
2302   if (N0.getOpcode() == ISD::UNDEF)
2303     return DAG.getConstant(0, SDLoc(N), VT);
2304   // X / undef -> undef
2305   if (N1.getOpcode() == ISD::UNDEF)
2306     return N1;
2307
2308   return SDValue();
2309 }
2310
2311 SDValue DAGCombiner::visitSREM(SDNode *N) {
2312   SDValue N0 = N->getOperand(0);
2313   SDValue N1 = N->getOperand(1);
2314   EVT VT = N->getValueType(0);
2315
2316   // fold (srem c1, c2) -> c1%c2
2317   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2318   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2319   if (N0C && N1C)
2320     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2321                                                     N0C, N1C))
2322       return Folded;
2323   // If we know the sign bits of both operands are zero, strength reduce to a
2324   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2325   if (!VT.isVector()) {
2326     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2327       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2328   }
2329
2330   // If X/C can be simplified by the division-by-constant logic, lower
2331   // X%C to the equivalent of X-X/C*C.
2332   if (N1C && !N1C->isNullValue()) {
2333     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2334     AddToWorklist(Div.getNode());
2335     SDValue OptimizedDiv = combine(Div.getNode());
2336     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2337       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2338                                 OptimizedDiv, N1);
2339       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2340       AddToWorklist(Mul.getNode());
2341       return Sub;
2342     }
2343   }
2344
2345   // undef % X -> 0
2346   if (N0.getOpcode() == ISD::UNDEF)
2347     return DAG.getConstant(0, SDLoc(N), VT);
2348   // X % undef -> undef
2349   if (N1.getOpcode() == ISD::UNDEF)
2350     return N1;
2351
2352   return SDValue();
2353 }
2354
2355 SDValue DAGCombiner::visitUREM(SDNode *N) {
2356   SDValue N0 = N->getOperand(0);
2357   SDValue N1 = N->getOperand(1);
2358   EVT VT = N->getValueType(0);
2359
2360   // fold (urem c1, c2) -> c1%c2
2361   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2362   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2363   if (N0C && N1C)
2364     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2365                                                     N0C, N1C))
2366       return Folded;
2367   // fold (urem x, pow2) -> (and x, pow2-1)
2368   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2369       N1C->getAPIntValue().isPowerOf2()) {
2370     SDLoc DL(N);
2371     return DAG.getNode(ISD::AND, DL, VT, N0,
2372                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2373   }
2374   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2375   if (N1.getOpcode() == ISD::SHL) {
2376     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2377       if (SHC->getAPIntValue().isPowerOf2()) {
2378         SDLoc DL(N);
2379         SDValue Add =
2380           DAG.getNode(ISD::ADD, DL, VT, N1,
2381                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2382                                  VT));
2383         AddToWorklist(Add.getNode());
2384         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2385       }
2386     }
2387   }
2388
2389   // If X/C can be simplified by the division-by-constant logic, lower
2390   // X%C to the equivalent of X-X/C*C.
2391   if (N1C && !N1C->isNullValue()) {
2392     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2393     AddToWorklist(Div.getNode());
2394     SDValue OptimizedDiv = combine(Div.getNode());
2395     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2396       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2397                                 OptimizedDiv, N1);
2398       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2399       AddToWorklist(Mul.getNode());
2400       return Sub;
2401     }
2402   }
2403
2404   // undef % X -> 0
2405   if (N0.getOpcode() == ISD::UNDEF)
2406     return DAG.getConstant(0, SDLoc(N), VT);
2407   // X % undef -> undef
2408   if (N1.getOpcode() == ISD::UNDEF)
2409     return N1;
2410
2411   return SDValue();
2412 }
2413
2414 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2415   SDValue N0 = N->getOperand(0);
2416   SDValue N1 = N->getOperand(1);
2417   EVT VT = N->getValueType(0);
2418   SDLoc DL(N);
2419
2420   // fold (mulhs x, 0) -> 0
2421   if (isNullConstant(N1))
2422     return N1;
2423   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2424   if (isOneConstant(N1)) {
2425     SDLoc DL(N);
2426     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2427                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2428                                        DL,
2429                                        getShiftAmountTy(N0.getValueType())));
2430   }
2431   // fold (mulhs x, undef) -> 0
2432   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2433     return DAG.getConstant(0, SDLoc(N), VT);
2434
2435   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2436   // plus a shift.
2437   if (VT.isSimple() && !VT.isVector()) {
2438     MVT Simple = VT.getSimpleVT();
2439     unsigned SimpleSize = Simple.getSizeInBits();
2440     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2441     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2442       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2443       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2444       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2445       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2446             DAG.getConstant(SimpleSize, DL,
2447                             getShiftAmountTy(N1.getValueType())));
2448       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2449     }
2450   }
2451
2452   return SDValue();
2453 }
2454
2455 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2456   SDValue N0 = N->getOperand(0);
2457   SDValue N1 = N->getOperand(1);
2458   EVT VT = N->getValueType(0);
2459   SDLoc DL(N);
2460
2461   // fold (mulhu x, 0) -> 0
2462   if (isNullConstant(N1))
2463     return N1;
2464   // fold (mulhu x, 1) -> 0
2465   if (isOneConstant(N1))
2466     return DAG.getConstant(0, DL, N0.getValueType());
2467   // fold (mulhu x, undef) -> 0
2468   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2469     return DAG.getConstant(0, DL, VT);
2470
2471   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2472   // plus a shift.
2473   if (VT.isSimple() && !VT.isVector()) {
2474     MVT Simple = VT.getSimpleVT();
2475     unsigned SimpleSize = Simple.getSizeInBits();
2476     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2477     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2478       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2479       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2480       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2481       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2482             DAG.getConstant(SimpleSize, DL,
2483                             getShiftAmountTy(N1.getValueType())));
2484       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2485     }
2486   }
2487
2488   return SDValue();
2489 }
2490
2491 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2492 /// give the opcodes for the two computations that are being performed. Return
2493 /// true if a simplification was made.
2494 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2495                                                 unsigned HiOp) {
2496   // If the high half is not needed, just compute the low half.
2497   bool HiExists = N->hasAnyUseOfValue(1);
2498   if (!HiExists &&
2499       (!LegalOperations ||
2500        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2501     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2502     return CombineTo(N, Res, Res);
2503   }
2504
2505   // If the low half is not needed, just compute the high half.
2506   bool LoExists = N->hasAnyUseOfValue(0);
2507   if (!LoExists &&
2508       (!LegalOperations ||
2509        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2510     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2511     return CombineTo(N, Res, Res);
2512   }
2513
2514   // If both halves are used, return as it is.
2515   if (LoExists && HiExists)
2516     return SDValue();
2517
2518   // If the two computed results can be simplified separately, separate them.
2519   if (LoExists) {
2520     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2521     AddToWorklist(Lo.getNode());
2522     SDValue LoOpt = combine(Lo.getNode());
2523     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2524         (!LegalOperations ||
2525          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2526       return CombineTo(N, LoOpt, LoOpt);
2527   }
2528
2529   if (HiExists) {
2530     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2531     AddToWorklist(Hi.getNode());
2532     SDValue HiOpt = combine(Hi.getNode());
2533     if (HiOpt.getNode() && HiOpt != Hi &&
2534         (!LegalOperations ||
2535          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2536       return CombineTo(N, HiOpt, HiOpt);
2537   }
2538
2539   return SDValue();
2540 }
2541
2542 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2543   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2544     return Res;
2545
2546   EVT VT = N->getValueType(0);
2547   SDLoc DL(N);
2548
2549   // If the type is twice as wide is legal, transform the mulhu to a wider
2550   // multiply plus a shift.
2551   if (VT.isSimple() && !VT.isVector()) {
2552     MVT Simple = VT.getSimpleVT();
2553     unsigned SimpleSize = Simple.getSizeInBits();
2554     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2555     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2556       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2557       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2558       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2559       // Compute the high part as N1.
2560       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2561             DAG.getConstant(SimpleSize, DL,
2562                             getShiftAmountTy(Lo.getValueType())));
2563       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2564       // Compute the low part as N0.
2565       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2566       return CombineTo(N, Lo, Hi);
2567     }
2568   }
2569
2570   return SDValue();
2571 }
2572
2573 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2574   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2575     return Res;
2576
2577   EVT VT = N->getValueType(0);
2578   SDLoc DL(N);
2579
2580   // If the type is twice as wide is legal, transform the mulhu to a wider
2581   // multiply plus a shift.
2582   if (VT.isSimple() && !VT.isVector()) {
2583     MVT Simple = VT.getSimpleVT();
2584     unsigned SimpleSize = Simple.getSizeInBits();
2585     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2586     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2587       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2588       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2589       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2590       // Compute the high part as N1.
2591       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2592             DAG.getConstant(SimpleSize, DL,
2593                             getShiftAmountTy(Lo.getValueType())));
2594       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2595       // Compute the low part as N0.
2596       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2597       return CombineTo(N, Lo, Hi);
2598     }
2599   }
2600
2601   return SDValue();
2602 }
2603
2604 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2605   // (smulo x, 2) -> (saddo x, x)
2606   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2607     if (C2->getAPIntValue() == 2)
2608       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2609                          N->getOperand(0), N->getOperand(0));
2610
2611   return SDValue();
2612 }
2613
2614 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2615   // (umulo x, 2) -> (uaddo x, x)
2616   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2617     if (C2->getAPIntValue() == 2)
2618       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2619                          N->getOperand(0), N->getOperand(0));
2620
2621   return SDValue();
2622 }
2623
2624 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2625   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2626     return Res;
2627
2628   return SDValue();
2629 }
2630
2631 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2632   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2633     return Res;
2634
2635   return SDValue();
2636 }
2637
2638 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2639   SDValue N0 = N->getOperand(0);
2640   SDValue N1 = N->getOperand(1);
2641   EVT VT = N0.getValueType();
2642
2643   // fold vector ops
2644   if (VT.isVector())
2645     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2646       return FoldedVOp;
2647
2648   // fold (add c1, c2) -> c1+c2
2649   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2650   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2651   if (N0C && N1C)
2652     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2653
2654   // canonicalize constant to RHS
2655   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2656      !isConstantIntBuildVectorOrConstantInt(N1))
2657     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2658
2659   return SDValue();
2660 }
2661
2662 /// If this is a binary operator with two operands of the same opcode, try to
2663 /// simplify it.
2664 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2665   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2666   EVT VT = N0.getValueType();
2667   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2668
2669   // Bail early if none of these transforms apply.
2670   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2671
2672   // For each of OP in AND/OR/XOR:
2673   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2674   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2675   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2676   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2677   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2678   //
2679   // do not sink logical op inside of a vector extend, since it may combine
2680   // into a vsetcc.
2681   EVT Op0VT = N0.getOperand(0).getValueType();
2682   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2683        N0.getOpcode() == ISD::SIGN_EXTEND ||
2684        N0.getOpcode() == ISD::BSWAP ||
2685        // Avoid infinite looping with PromoteIntBinOp.
2686        (N0.getOpcode() == ISD::ANY_EXTEND &&
2687         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2688        (N0.getOpcode() == ISD::TRUNCATE &&
2689         (!TLI.isZExtFree(VT, Op0VT) ||
2690          !TLI.isTruncateFree(Op0VT, VT)) &&
2691         TLI.isTypeLegal(Op0VT))) &&
2692       !VT.isVector() &&
2693       Op0VT == N1.getOperand(0).getValueType() &&
2694       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2695     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2696                                  N0.getOperand(0).getValueType(),
2697                                  N0.getOperand(0), N1.getOperand(0));
2698     AddToWorklist(ORNode.getNode());
2699     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2700   }
2701
2702   // For each of OP in SHL/SRL/SRA/AND...
2703   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2704   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2705   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2706   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2707        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2708       N0.getOperand(1) == N1.getOperand(1)) {
2709     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2710                                  N0.getOperand(0).getValueType(),
2711                                  N0.getOperand(0), N1.getOperand(0));
2712     AddToWorklist(ORNode.getNode());
2713     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2714                        ORNode, N0.getOperand(1));
2715   }
2716
2717   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2718   // Only perform this optimization after type legalization and before
2719   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2720   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2721   // we don't want to undo this promotion.
2722   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2723   // on scalars.
2724   if ((N0.getOpcode() == ISD::BITCAST ||
2725        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2726       Level == AfterLegalizeTypes) {
2727     SDValue In0 = N0.getOperand(0);
2728     SDValue In1 = N1.getOperand(0);
2729     EVT In0Ty = In0.getValueType();
2730     EVT In1Ty = In1.getValueType();
2731     SDLoc DL(N);
2732     // If both incoming values are integers, and the original types are the
2733     // same.
2734     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2735       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2736       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2737       AddToWorklist(Op.getNode());
2738       return BC;
2739     }
2740   }
2741
2742   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2743   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2744   // If both shuffles use the same mask, and both shuffle within a single
2745   // vector, then it is worthwhile to move the swizzle after the operation.
2746   // The type-legalizer generates this pattern when loading illegal
2747   // vector types from memory. In many cases this allows additional shuffle
2748   // optimizations.
2749   // There are other cases where moving the shuffle after the xor/and/or
2750   // is profitable even if shuffles don't perform a swizzle.
2751   // If both shuffles use the same mask, and both shuffles have the same first
2752   // or second operand, then it might still be profitable to move the shuffle
2753   // after the xor/and/or operation.
2754   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2755     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2756     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2757
2758     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2759            "Inputs to shuffles are not the same type");
2760
2761     // Check that both shuffles use the same mask. The masks are known to be of
2762     // the same length because the result vector type is the same.
2763     // Check also that shuffles have only one use to avoid introducing extra
2764     // instructions.
2765     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2766         SVN0->getMask().equals(SVN1->getMask())) {
2767       SDValue ShOp = N0->getOperand(1);
2768
2769       // Don't try to fold this node if it requires introducing a
2770       // build vector of all zeros that might be illegal at this stage.
2771       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2772         if (!LegalTypes)
2773           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2774         else
2775           ShOp = SDValue();
2776       }
2777
2778       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2779       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2780       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2781       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2782         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2783                                       N0->getOperand(0), N1->getOperand(0));
2784         AddToWorklist(NewNode.getNode());
2785         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2786                                     &SVN0->getMask()[0]);
2787       }
2788
2789       // Don't try to fold this node if it requires introducing a
2790       // build vector of all zeros that might be illegal at this stage.
2791       ShOp = N0->getOperand(0);
2792       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2793         if (!LegalTypes)
2794           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2795         else
2796           ShOp = SDValue();
2797       }
2798
2799       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2800       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2801       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2802       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2803         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2804                                       N0->getOperand(1), N1->getOperand(1));
2805         AddToWorklist(NewNode.getNode());
2806         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2807                                     &SVN0->getMask()[0]);
2808       }
2809     }
2810   }
2811
2812   return SDValue();
2813 }
2814
2815 /// This contains all DAGCombine rules which reduce two values combined by
2816 /// an And operation to a single value. This makes them reusable in the context
2817 /// of visitSELECT(). Rules involving constants are not included as
2818 /// visitSELECT() already handles those cases.
2819 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2820                                   SDNode *LocReference) {
2821   EVT VT = N1.getValueType();
2822
2823   // fold (and x, undef) -> 0
2824   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2825     return DAG.getConstant(0, SDLoc(LocReference), VT);
2826   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2827   SDValue LL, LR, RL, RR, CC0, CC1;
2828   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2829     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2830     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2831
2832     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2833         LL.getValueType().isInteger()) {
2834       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2835       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2836         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2837                                      LR.getValueType(), LL, RL);
2838         AddToWorklist(ORNode.getNode());
2839         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2840       }
2841       if (isAllOnesConstant(LR)) {
2842         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2843         if (Op1 == ISD::SETEQ) {
2844           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2845                                         LR.getValueType(), LL, RL);
2846           AddToWorklist(ANDNode.getNode());
2847           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2848         }
2849         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2850         if (Op1 == ISD::SETGT) {
2851           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2852                                        LR.getValueType(), LL, RL);
2853           AddToWorklist(ORNode.getNode());
2854           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2855         }
2856       }
2857     }
2858     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2859     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2860         Op0 == Op1 && LL.getValueType().isInteger() &&
2861       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2862                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2863       SDLoc DL(N0);
2864       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2865                                     LL, DAG.getConstant(1, DL,
2866                                                         LL.getValueType()));
2867       AddToWorklist(ADDNode.getNode());
2868       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2869                           DAG.getConstant(2, DL, LL.getValueType()),
2870                           ISD::SETUGE);
2871     }
2872     // canonicalize equivalent to ll == rl
2873     if (LL == RR && LR == RL) {
2874       Op1 = ISD::getSetCCSwappedOperands(Op1);
2875       std::swap(RL, RR);
2876     }
2877     if (LL == RL && LR == RR) {
2878       bool isInteger = LL.getValueType().isInteger();
2879       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2880       if (Result != ISD::SETCC_INVALID &&
2881           (!LegalOperations ||
2882            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2883             TLI.isOperationLegal(ISD::SETCC,
2884                             getSetCCResultType(N0.getSimpleValueType())))))
2885         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2886                             LL, LR, Result);
2887     }
2888   }
2889
2890   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2891       VT.getSizeInBits() <= 64) {
2892     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2893       APInt ADDC = ADDI->getAPIntValue();
2894       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2895         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2896         // immediate for an add, but it is legal if its top c2 bits are set,
2897         // transform the ADD so the immediate doesn't need to be materialized
2898         // in a register.
2899         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2900           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2901                                              SRLI->getZExtValue());
2902           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2903             ADDC |= Mask;
2904             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2905               SDLoc DL(N0);
2906               SDValue NewAdd =
2907                 DAG.getNode(ISD::ADD, DL, VT,
2908                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2909               CombineTo(N0.getNode(), NewAdd);
2910               // Return N so it doesn't get rechecked!
2911               return SDValue(LocReference, 0);
2912             }
2913           }
2914         }
2915       }
2916     }
2917   }
2918
2919   return SDValue();
2920 }
2921
2922 SDValue DAGCombiner::visitAND(SDNode *N) {
2923   SDValue N0 = N->getOperand(0);
2924   SDValue N1 = N->getOperand(1);
2925   EVT VT = N1.getValueType();
2926
2927   // fold vector ops
2928   if (VT.isVector()) {
2929     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2930       return FoldedVOp;
2931
2932     // fold (and x, 0) -> 0, vector edition
2933     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2934       // do not return N0, because undef node may exist in N0
2935       return DAG.getConstant(
2936           APInt::getNullValue(
2937               N0.getValueType().getScalarType().getSizeInBits()),
2938           SDLoc(N), N0.getValueType());
2939     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2940       // do not return N1, because undef node may exist in N1
2941       return DAG.getConstant(
2942           APInt::getNullValue(
2943               N1.getValueType().getScalarType().getSizeInBits()),
2944           SDLoc(N), N1.getValueType());
2945
2946     // fold (and x, -1) -> x, vector edition
2947     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2948       return N1;
2949     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2950       return N0;
2951   }
2952
2953   // fold (and c1, c2) -> c1&c2
2954   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2955   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2956   if (N0C && N1C && !N1C->isOpaque())
2957     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2958   // canonicalize constant to RHS
2959   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2960      !isConstantIntBuildVectorOrConstantInt(N1))
2961     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2962   // fold (and x, -1) -> x
2963   if (isAllOnesConstant(N1))
2964     return N0;
2965   // if (and x, c) is known to be zero, return 0
2966   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2967   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2968                                    APInt::getAllOnesValue(BitWidth)))
2969     return DAG.getConstant(0, SDLoc(N), VT);
2970   // reassociate and
2971   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2972     return RAND;
2973   // fold (and (or x, C), D) -> D if (C & D) == D
2974   if (N1C && N0.getOpcode() == ISD::OR)
2975     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2976       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2977         return N1;
2978   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2979   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2980     SDValue N0Op0 = N0.getOperand(0);
2981     APInt Mask = ~N1C->getAPIntValue();
2982     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2983     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2984       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2985                                  N0.getValueType(), N0Op0);
2986
2987       // Replace uses of the AND with uses of the Zero extend node.
2988       CombineTo(N, Zext);
2989
2990       // We actually want to replace all uses of the any_extend with the
2991       // zero_extend, to avoid duplicating things.  This will later cause this
2992       // AND to be folded.
2993       CombineTo(N0.getNode(), Zext);
2994       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2995     }
2996   }
2997   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2998   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2999   // already be zero by virtue of the width of the base type of the load.
3000   //
3001   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3002   // more cases.
3003   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3004        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3005       N0.getOpcode() == ISD::LOAD) {
3006     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3007                                          N0 : N0.getOperand(0) );
3008
3009     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3010     // This can be a pure constant or a vector splat, in which case we treat the
3011     // vector as a scalar and use the splat value.
3012     APInt Constant = APInt::getNullValue(1);
3013     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3014       Constant = C->getAPIntValue();
3015     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3016       APInt SplatValue, SplatUndef;
3017       unsigned SplatBitSize;
3018       bool HasAnyUndefs;
3019       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3020                                              SplatBitSize, HasAnyUndefs);
3021       if (IsSplat) {
3022         // Undef bits can contribute to a possible optimisation if set, so
3023         // set them.
3024         SplatValue |= SplatUndef;
3025
3026         // The splat value may be something like "0x00FFFFFF", which means 0 for
3027         // the first vector value and FF for the rest, repeating. We need a mask
3028         // that will apply equally to all members of the vector, so AND all the
3029         // lanes of the constant together.
3030         EVT VT = Vector->getValueType(0);
3031         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3032
3033         // If the splat value has been compressed to a bitlength lower
3034         // than the size of the vector lane, we need to re-expand it to
3035         // the lane size.
3036         if (BitWidth > SplatBitSize)
3037           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3038                SplatBitSize < BitWidth;
3039                SplatBitSize = SplatBitSize * 2)
3040             SplatValue |= SplatValue.shl(SplatBitSize);
3041
3042         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3043         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3044         if (SplatBitSize % BitWidth == 0) {
3045           Constant = APInt::getAllOnesValue(BitWidth);
3046           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3047             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3048         }
3049       }
3050     }
3051
3052     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3053     // actually legal and isn't going to get expanded, else this is a false
3054     // optimisation.
3055     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3056                                                     Load->getValueType(0),
3057                                                     Load->getMemoryVT());
3058
3059     // Resize the constant to the same size as the original memory access before
3060     // extension. If it is still the AllOnesValue then this AND is completely
3061     // unneeded.
3062     Constant =
3063       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3064
3065     bool B;
3066     switch (Load->getExtensionType()) {
3067     default: B = false; break;
3068     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3069     case ISD::ZEXTLOAD:
3070     case ISD::NON_EXTLOAD: B = true; break;
3071     }
3072
3073     if (B && Constant.isAllOnesValue()) {
3074       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3075       // preserve semantics once we get rid of the AND.
3076       SDValue NewLoad(Load, 0);
3077       if (Load->getExtensionType() == ISD::EXTLOAD) {
3078         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3079                               Load->getValueType(0), SDLoc(Load),
3080                               Load->getChain(), Load->getBasePtr(),
3081                               Load->getOffset(), Load->getMemoryVT(),
3082                               Load->getMemOperand());
3083         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3084         if (Load->getNumValues() == 3) {
3085           // PRE/POST_INC loads have 3 values.
3086           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3087                            NewLoad.getValue(2) };
3088           CombineTo(Load, To, 3, true);
3089         } else {
3090           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3091         }
3092       }
3093
3094       // Fold the AND away, taking care not to fold to the old load node if we
3095       // replaced it.
3096       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3097
3098       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3099     }
3100   }
3101
3102   // fold (and (load x), 255) -> (zextload x, i8)
3103   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3104   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3105   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3106               (N0.getOpcode() == ISD::ANY_EXTEND &&
3107                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3108     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3109     LoadSDNode *LN0 = HasAnyExt
3110       ? cast<LoadSDNode>(N0.getOperand(0))
3111       : cast<LoadSDNode>(N0);
3112     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3113         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3114       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3115       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3116         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3117         EVT LoadedVT = LN0->getMemoryVT();
3118         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3119
3120         if (ExtVT == LoadedVT &&
3121             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3122                                                     ExtVT))) {
3123
3124           SDValue NewLoad =
3125             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3126                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3127                            LN0->getMemOperand());
3128           AddToWorklist(N);
3129           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3130           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3131         }
3132
3133         // Do not change the width of a volatile load.
3134         // Do not generate loads of non-round integer types since these can
3135         // be expensive (and would be wrong if the type is not byte sized).
3136         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3137             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3138                                                     ExtVT))) {
3139           EVT PtrType = LN0->getOperand(1).getValueType();
3140
3141           unsigned Alignment = LN0->getAlignment();
3142           SDValue NewPtr = LN0->getBasePtr();
3143
3144           // For big endian targets, we need to add an offset to the pointer
3145           // to load the correct bytes.  For little endian systems, we merely
3146           // need to read fewer bytes from the same pointer.
3147           if (DAG.getDataLayout().isBigEndian()) {
3148             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3149             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3150             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3151             SDLoc DL(LN0);
3152             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3153                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3154             Alignment = MinAlign(Alignment, PtrOff);
3155           }
3156
3157           AddToWorklist(NewPtr.getNode());
3158
3159           SDValue Load =
3160             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3161                            LN0->getChain(), NewPtr,
3162                            LN0->getPointerInfo(),
3163                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3164                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3165           AddToWorklist(N);
3166           CombineTo(LN0, Load, Load.getValue(1));
3167           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3168         }
3169       }
3170     }
3171   }
3172
3173   if (SDValue Combined = visitANDLike(N0, N1, N))
3174     return Combined;
3175
3176   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3177   if (N0.getOpcode() == N1.getOpcode())
3178     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3179       return Tmp;
3180
3181   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3182   // fold (and (sra)) -> (and (srl)) when possible.
3183   if (!VT.isVector() &&
3184       SimplifyDemandedBits(SDValue(N, 0)))
3185     return SDValue(N, 0);
3186
3187   // fold (zext_inreg (extload x)) -> (zextload x)
3188   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3189     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3190     EVT MemVT = LN0->getMemoryVT();
3191     // If we zero all the possible extended bits, then we can turn this into
3192     // a zextload if we are running before legalize or the operation is legal.
3193     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3194     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3195                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3196         ((!LegalOperations && !LN0->isVolatile()) ||
3197          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3198       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3199                                        LN0->getChain(), LN0->getBasePtr(),
3200                                        MemVT, LN0->getMemOperand());
3201       AddToWorklist(N);
3202       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3203       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3204     }
3205   }
3206   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3207   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3208       N0.hasOneUse()) {
3209     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3210     EVT MemVT = LN0->getMemoryVT();
3211     // If we zero all the possible extended bits, then we can turn this into
3212     // a zextload if we are running before legalize or the operation is legal.
3213     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3214     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3215                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3216         ((!LegalOperations && !LN0->isVolatile()) ||
3217          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3218       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3219                                        LN0->getChain(), LN0->getBasePtr(),
3220                                        MemVT, LN0->getMemOperand());
3221       AddToWorklist(N);
3222       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3223       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3224     }
3225   }
3226   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3227   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3228     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3229                                        N0.getOperand(1), false);
3230     if (BSwap.getNode())
3231       return BSwap;
3232   }
3233
3234   return SDValue();
3235 }
3236
3237 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3238 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3239                                         bool DemandHighBits) {
3240   if (!LegalOperations)
3241     return SDValue();
3242
3243   EVT VT = N->getValueType(0);
3244   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3245     return SDValue();
3246   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3247     return SDValue();
3248
3249   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3250   bool LookPassAnd0 = false;
3251   bool LookPassAnd1 = false;
3252   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3253       std::swap(N0, N1);
3254   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3255       std::swap(N0, N1);
3256   if (N0.getOpcode() == ISD::AND) {
3257     if (!N0.getNode()->hasOneUse())
3258       return SDValue();
3259     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3260     if (!N01C || N01C->getZExtValue() != 0xFF00)
3261       return SDValue();
3262     N0 = N0.getOperand(0);
3263     LookPassAnd0 = true;
3264   }
3265
3266   if (N1.getOpcode() == ISD::AND) {
3267     if (!N1.getNode()->hasOneUse())
3268       return SDValue();
3269     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3270     if (!N11C || N11C->getZExtValue() != 0xFF)
3271       return SDValue();
3272     N1 = N1.getOperand(0);
3273     LookPassAnd1 = true;
3274   }
3275
3276   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3277     std::swap(N0, N1);
3278   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3279     return SDValue();
3280   if (!N0.getNode()->hasOneUse() ||
3281       !N1.getNode()->hasOneUse())
3282     return SDValue();
3283
3284   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3285   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3286   if (!N01C || !N11C)
3287     return SDValue();
3288   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3289     return SDValue();
3290
3291   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3292   SDValue N00 = N0->getOperand(0);
3293   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3294     if (!N00.getNode()->hasOneUse())
3295       return SDValue();
3296     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3297     if (!N001C || N001C->getZExtValue() != 0xFF)
3298       return SDValue();
3299     N00 = N00.getOperand(0);
3300     LookPassAnd0 = true;
3301   }
3302
3303   SDValue N10 = N1->getOperand(0);
3304   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3305     if (!N10.getNode()->hasOneUse())
3306       return SDValue();
3307     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3308     if (!N101C || N101C->getZExtValue() != 0xFF00)
3309       return SDValue();
3310     N10 = N10.getOperand(0);
3311     LookPassAnd1 = true;
3312   }
3313
3314   if (N00 != N10)
3315     return SDValue();
3316
3317   // Make sure everything beyond the low halfword gets set to zero since the SRL
3318   // 16 will clear the top bits.
3319   unsigned OpSizeInBits = VT.getSizeInBits();
3320   if (DemandHighBits && OpSizeInBits > 16) {
3321     // If the left-shift isn't masked out then the only way this is a bswap is
3322     // if all bits beyond the low 8 are 0. In that case the entire pattern
3323     // reduces to a left shift anyway: leave it for other parts of the combiner.
3324     if (!LookPassAnd0)
3325       return SDValue();
3326
3327     // However, if the right shift isn't masked out then it might be because
3328     // it's not needed. See if we can spot that too.
3329     if (!LookPassAnd1 &&
3330         !DAG.MaskedValueIsZero(
3331             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3332       return SDValue();
3333   }
3334
3335   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3336   if (OpSizeInBits > 16) {
3337     SDLoc DL(N);
3338     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3339                       DAG.getConstant(OpSizeInBits - 16, DL,
3340                                       getShiftAmountTy(VT)));
3341   }
3342   return Res;
3343 }
3344
3345 /// Return true if the specified node is an element that makes up a 32-bit
3346 /// packed halfword byteswap.
3347 /// ((x & 0x000000ff) << 8) |
3348 /// ((x & 0x0000ff00) >> 8) |
3349 /// ((x & 0x00ff0000) << 8) |
3350 /// ((x & 0xff000000) >> 8)
3351 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3352   if (!N.getNode()->hasOneUse())
3353     return false;
3354
3355   unsigned Opc = N.getOpcode();
3356   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3357     return false;
3358
3359   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3360   if (!N1C)
3361     return false;
3362
3363   unsigned Num;
3364   switch (N1C->getZExtValue()) {
3365   default:
3366     return false;
3367   case 0xFF:       Num = 0; break;
3368   case 0xFF00:     Num = 1; break;
3369   case 0xFF0000:   Num = 2; break;
3370   case 0xFF000000: Num = 3; break;
3371   }
3372
3373   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3374   SDValue N0 = N.getOperand(0);
3375   if (Opc == ISD::AND) {
3376     if (Num == 0 || Num == 2) {
3377       // (x >> 8) & 0xff
3378       // (x >> 8) & 0xff0000
3379       if (N0.getOpcode() != ISD::SRL)
3380         return false;
3381       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3382       if (!C || C->getZExtValue() != 8)
3383         return false;
3384     } else {
3385       // (x << 8) & 0xff00
3386       // (x << 8) & 0xff000000
3387       if (N0.getOpcode() != ISD::SHL)
3388         return false;
3389       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3390       if (!C || C->getZExtValue() != 8)
3391         return false;
3392     }
3393   } else if (Opc == ISD::SHL) {
3394     // (x & 0xff) << 8
3395     // (x & 0xff0000) << 8
3396     if (Num != 0 && Num != 2)
3397       return false;
3398     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3399     if (!C || C->getZExtValue() != 8)
3400       return false;
3401   } else { // Opc == ISD::SRL
3402     // (x & 0xff00) >> 8
3403     // (x & 0xff000000) >> 8
3404     if (Num != 1 && Num != 3)
3405       return false;
3406     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3407     if (!C || C->getZExtValue() != 8)
3408       return false;
3409   }
3410
3411   if (Parts[Num])
3412     return false;
3413
3414   Parts[Num] = N0.getOperand(0).getNode();
3415   return true;
3416 }
3417
3418 /// Match a 32-bit packed halfword bswap. That is
3419 /// ((x & 0x000000ff) << 8) |
3420 /// ((x & 0x0000ff00) >> 8) |
3421 /// ((x & 0x00ff0000) << 8) |
3422 /// ((x & 0xff000000) >> 8)
3423 /// => (rotl (bswap x), 16)
3424 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3425   if (!LegalOperations)
3426     return SDValue();
3427
3428   EVT VT = N->getValueType(0);
3429   if (VT != MVT::i32)
3430     return SDValue();
3431   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3432     return SDValue();
3433
3434   // Look for either
3435   // (or (or (and), (and)), (or (and), (and)))
3436   // (or (or (or (and), (and)), (and)), (and))
3437   if (N0.getOpcode() != ISD::OR)
3438     return SDValue();
3439   SDValue N00 = N0.getOperand(0);
3440   SDValue N01 = N0.getOperand(1);
3441   SDNode *Parts[4] = {};
3442
3443   if (N1.getOpcode() == ISD::OR &&
3444       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3445     // (or (or (and), (and)), (or (and), (and)))
3446     SDValue N000 = N00.getOperand(0);
3447     if (!isBSwapHWordElement(N000, Parts))
3448       return SDValue();
3449
3450     SDValue N001 = N00.getOperand(1);
3451     if (!isBSwapHWordElement(N001, Parts))
3452       return SDValue();
3453     SDValue N010 = N01.getOperand(0);
3454     if (!isBSwapHWordElement(N010, Parts))
3455       return SDValue();
3456     SDValue N011 = N01.getOperand(1);
3457     if (!isBSwapHWordElement(N011, Parts))
3458       return SDValue();
3459   } else {
3460     // (or (or (or (and), (and)), (and)), (and))
3461     if (!isBSwapHWordElement(N1, Parts))
3462       return SDValue();
3463     if (!isBSwapHWordElement(N01, Parts))
3464       return SDValue();
3465     if (N00.getOpcode() != ISD::OR)
3466       return SDValue();
3467     SDValue N000 = N00.getOperand(0);
3468     if (!isBSwapHWordElement(N000, Parts))
3469       return SDValue();
3470     SDValue N001 = N00.getOperand(1);
3471     if (!isBSwapHWordElement(N001, Parts))
3472       return SDValue();
3473   }
3474
3475   // Make sure the parts are all coming from the same node.
3476   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3477     return SDValue();
3478
3479   SDLoc DL(N);
3480   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3481                               SDValue(Parts[0], 0));
3482
3483   // Result of the bswap should be rotated by 16. If it's not legal, then
3484   // do  (x << 16) | (x >> 16).
3485   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3486   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3487     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3488   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3489     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3490   return DAG.getNode(ISD::OR, DL, VT,
3491                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3492                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3493 }
3494
3495 /// This contains all DAGCombine rules which reduce two values combined by
3496 /// an Or operation to a single value \see visitANDLike().
3497 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3498   EVT VT = N1.getValueType();
3499   // fold (or x, undef) -> -1
3500   if (!LegalOperations &&
3501       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3502     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3503     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3504                            SDLoc(LocReference), VT);
3505   }
3506   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3507   SDValue LL, LR, RL, RR, CC0, CC1;
3508   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3509     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3510     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3511
3512     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3513       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3514       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3515       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3516         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3517                                      LR.getValueType(), LL, RL);
3518         AddToWorklist(ORNode.getNode());
3519         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3520       }
3521       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3522       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3523       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3524         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3525                                       LR.getValueType(), LL, RL);
3526         AddToWorklist(ANDNode.getNode());
3527         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3528       }
3529     }
3530     // canonicalize equivalent to ll == rl
3531     if (LL == RR && LR == RL) {
3532       Op1 = ISD::getSetCCSwappedOperands(Op1);
3533       std::swap(RL, RR);
3534     }
3535     if (LL == RL && LR == RR) {
3536       bool isInteger = LL.getValueType().isInteger();
3537       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3538       if (Result != ISD::SETCC_INVALID &&
3539           (!LegalOperations ||
3540            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3541             TLI.isOperationLegal(ISD::SETCC,
3542               getSetCCResultType(N0.getValueType())))))
3543         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3544                             LL, LR, Result);
3545     }
3546   }
3547
3548   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3549   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3550       // Don't increase # computations.
3551       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3552     // We can only do this xform if we know that bits from X that are set in C2
3553     // but not in C1 are already zero.  Likewise for Y.
3554     if (const ConstantSDNode *N0O1C =
3555         getAsNonOpaqueConstant(N0.getOperand(1))) {
3556       if (const ConstantSDNode *N1O1C =
3557           getAsNonOpaqueConstant(N1.getOperand(1))) {
3558         // We can only do this xform if we know that bits from X that are set in
3559         // C2 but not in C1 are already zero.  Likewise for Y.
3560         const APInt &LHSMask = N0O1C->getAPIntValue();
3561         const APInt &RHSMask = N1O1C->getAPIntValue();
3562
3563         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3564             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3565           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3566                                   N0.getOperand(0), N1.getOperand(0));
3567           SDLoc DL(LocReference);
3568           return DAG.getNode(ISD::AND, DL, VT, X,
3569                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3570         }
3571       }
3572     }
3573   }
3574
3575   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3576   if (N0.getOpcode() == ISD::AND &&
3577       N1.getOpcode() == ISD::AND &&
3578       N0.getOperand(0) == N1.getOperand(0) &&
3579       // Don't increase # computations.
3580       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3581     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3582                             N0.getOperand(1), N1.getOperand(1));
3583     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3584   }
3585
3586   return SDValue();
3587 }
3588
3589 SDValue DAGCombiner::visitOR(SDNode *N) {
3590   SDValue N0 = N->getOperand(0);
3591   SDValue N1 = N->getOperand(1);
3592   EVT VT = N1.getValueType();
3593
3594   // fold vector ops
3595   if (VT.isVector()) {
3596     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3597       return FoldedVOp;
3598
3599     // fold (or x, 0) -> x, vector edition
3600     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3601       return N1;
3602     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3603       return N0;
3604
3605     // fold (or x, -1) -> -1, vector edition
3606     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3607       // do not return N0, because undef node may exist in N0
3608       return DAG.getConstant(
3609           APInt::getAllOnesValue(
3610               N0.getValueType().getScalarType().getSizeInBits()),
3611           SDLoc(N), N0.getValueType());
3612     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3613       // do not return N1, because undef node may exist in N1
3614       return DAG.getConstant(
3615           APInt::getAllOnesValue(
3616               N1.getValueType().getScalarType().getSizeInBits()),
3617           SDLoc(N), N1.getValueType());
3618
3619     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3620     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3621     // Do this only if the resulting shuffle is legal.
3622     if (isa<ShuffleVectorSDNode>(N0) &&
3623         isa<ShuffleVectorSDNode>(N1) &&
3624         // Avoid folding a node with illegal type.
3625         TLI.isTypeLegal(VT) &&
3626         N0->getOperand(1) == N1->getOperand(1) &&
3627         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3628       bool CanFold = true;
3629       unsigned NumElts = VT.getVectorNumElements();
3630       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3631       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3632       // We construct two shuffle masks:
3633       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3634       // and N1 as the second operand.
3635       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3636       // and N0 as the second operand.
3637       // We do this because OR is commutable and therefore there might be
3638       // two ways to fold this node into a shuffle.
3639       SmallVector<int,4> Mask1;
3640       SmallVector<int,4> Mask2;
3641
3642       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3643         int M0 = SV0->getMaskElt(i);
3644         int M1 = SV1->getMaskElt(i);
3645
3646         // Both shuffle indexes are undef. Propagate Undef.
3647         if (M0 < 0 && M1 < 0) {
3648           Mask1.push_back(M0);
3649           Mask2.push_back(M0);
3650           continue;
3651         }
3652
3653         if (M0 < 0 || M1 < 0 ||
3654             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3655             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3656           CanFold = false;
3657           break;
3658         }
3659
3660         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3661         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3662       }
3663
3664       if (CanFold) {
3665         // Fold this sequence only if the resulting shuffle is 'legal'.
3666         if (TLI.isShuffleMaskLegal(Mask1, VT))
3667           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3668                                       N1->getOperand(0), &Mask1[0]);
3669         if (TLI.isShuffleMaskLegal(Mask2, VT))
3670           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3671                                       N0->getOperand(0), &Mask2[0]);
3672       }
3673     }
3674   }
3675
3676   // fold (or c1, c2) -> c1|c2
3677   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3678   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3679   if (N0C && N1C && !N1C->isOpaque())
3680     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3681   // canonicalize constant to RHS
3682   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3683      !isConstantIntBuildVectorOrConstantInt(N1))
3684     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3685   // fold (or x, 0) -> x
3686   if (isNullConstant(N1))
3687     return N0;
3688   // fold (or x, -1) -> -1
3689   if (isAllOnesConstant(N1))
3690     return N1;
3691   // fold (or x, c) -> c iff (x & ~c) == 0
3692   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3693     return N1;
3694
3695   if (SDValue Combined = visitORLike(N0, N1, N))
3696     return Combined;
3697
3698   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3699   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3700     return BSwap;
3701   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3702     return BSwap;
3703
3704   // reassociate or
3705   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3706     return ROR;
3707   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3708   // iff (c1 & c2) == 0.
3709   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3710              isa<ConstantSDNode>(N0.getOperand(1))) {
3711     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3712     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3713       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3714                                                    N1C, C1))
3715         return DAG.getNode(
3716             ISD::AND, SDLoc(N), VT,
3717             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3718       return SDValue();
3719     }
3720   }
3721   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3722   if (N0.getOpcode() == N1.getOpcode())
3723     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3724       return Tmp;
3725
3726   // See if this is some rotate idiom.
3727   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3728     return SDValue(Rot, 0);
3729
3730   // Simplify the operands using demanded-bits information.
3731   if (!VT.isVector() &&
3732       SimplifyDemandedBits(SDValue(N, 0)))
3733     return SDValue(N, 0);
3734
3735   return SDValue();
3736 }
3737
3738 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3739 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3740   if (Op.getOpcode() == ISD::AND) {
3741     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3742       Mask = Op.getOperand(1);
3743       Op = Op.getOperand(0);
3744     } else {
3745       return false;
3746     }
3747   }
3748
3749   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3750     Shift = Op;
3751     return true;
3752   }
3753
3754   return false;
3755 }
3756
3757 // Return true if we can prove that, whenever Neg and Pos are both in the
3758 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3759 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3760 //
3761 //     (or (shift1 X, Neg), (shift2 X, Pos))
3762 //
3763 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3764 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3765 // to consider shift amounts with defined behavior.
3766 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3767   // If OpSize is a power of 2 then:
3768   //
3769   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3770   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3771   //
3772   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3773   // for the stronger condition:
3774   //
3775   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3776   //
3777   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3778   // we can just replace Neg with Neg' for the rest of the function.
3779   //
3780   // In other cases we check for the even stronger condition:
3781   //
3782   //     Neg == OpSize - Pos                                    [B]
3783   //
3784   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3785   // behavior if Pos == 0 (and consequently Neg == OpSize).
3786   //
3787   // We could actually use [A] whenever OpSize is a power of 2, but the
3788   // only extra cases that it would match are those uninteresting ones
3789   // where Neg and Pos are never in range at the same time.  E.g. for
3790   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3791   // as well as (sub 32, Pos), but:
3792   //
3793   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3794   //
3795   // always invokes undefined behavior for 32-bit X.
3796   //
3797   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3798   unsigned MaskLoBits = 0;
3799   if (Neg.getOpcode() == ISD::AND &&
3800       isPowerOf2_64(OpSize) &&
3801       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3802       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3803     Neg = Neg.getOperand(0);
3804     MaskLoBits = Log2_64(OpSize);
3805   }
3806
3807   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3808   if (Neg.getOpcode() != ISD::SUB)
3809     return 0;
3810   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3811   if (!NegC)
3812     return 0;
3813   SDValue NegOp1 = Neg.getOperand(1);
3814
3815   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3816   // Pos'.  The truncation is redundant for the purpose of the equality.
3817   if (MaskLoBits &&
3818       Pos.getOpcode() == ISD::AND &&
3819       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3820       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3821     Pos = Pos.getOperand(0);
3822
3823   // The condition we need is now:
3824   //
3825   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3826   //
3827   // If NegOp1 == Pos then we need:
3828   //
3829   //              OpSize & Mask == NegC & Mask
3830   //
3831   // (because "x & Mask" is a truncation and distributes through subtraction).
3832   APInt Width;
3833   if (Pos == NegOp1)
3834     Width = NegC->getAPIntValue();
3835   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3836   // Then the condition we want to prove becomes:
3837   //
3838   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3839   //
3840   // which, again because "x & Mask" is a truncation, becomes:
3841   //
3842   //                NegC & Mask == (OpSize - PosC) & Mask
3843   //              OpSize & Mask == (NegC + PosC) & Mask
3844   else if (Pos.getOpcode() == ISD::ADD &&
3845            Pos.getOperand(0) == NegOp1 &&
3846            Pos.getOperand(1).getOpcode() == ISD::Constant)
3847     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3848              NegC->getAPIntValue());
3849   else
3850     return false;
3851
3852   // Now we just need to check that OpSize & Mask == Width & Mask.
3853   if (MaskLoBits)
3854     // Opsize & Mask is 0 since Mask is Opsize - 1.
3855     return Width.getLoBits(MaskLoBits) == 0;
3856   return Width == OpSize;
3857 }
3858
3859 // A subroutine of MatchRotate used once we have found an OR of two opposite
3860 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3861 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3862 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3863 // Neg with outer conversions stripped away.
3864 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3865                                        SDValue Neg, SDValue InnerPos,
3866                                        SDValue InnerNeg, unsigned PosOpcode,
3867                                        unsigned NegOpcode, SDLoc DL) {
3868   // fold (or (shl x, (*ext y)),
3869   //          (srl x, (*ext (sub 32, y)))) ->
3870   //   (rotl x, y) or (rotr x, (sub 32, y))
3871   //
3872   // fold (or (shl x, (*ext (sub 32, y))),
3873   //          (srl x, (*ext y))) ->
3874   //   (rotr x, y) or (rotl x, (sub 32, y))
3875   EVT VT = Shifted.getValueType();
3876   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3877     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3878     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3879                        HasPos ? Pos : Neg).getNode();
3880   }
3881
3882   return nullptr;
3883 }
3884
3885 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3886 // idioms for rotate, and if the target supports rotation instructions, generate
3887 // a rot[lr].
3888 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3889   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3890   EVT VT = LHS.getValueType();
3891   if (!TLI.isTypeLegal(VT)) return nullptr;
3892
3893   // The target must have at least one rotate flavor.
3894   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3895   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3896   if (!HasROTL && !HasROTR) return nullptr;
3897
3898   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3899   SDValue LHSShift;   // The shift.
3900   SDValue LHSMask;    // AND value if any.
3901   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3902     return nullptr; // Not part of a rotate.
3903
3904   SDValue RHSShift;   // The shift.
3905   SDValue RHSMask;    // AND value if any.
3906   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3907     return nullptr; // Not part of a rotate.
3908
3909   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3910     return nullptr;   // Not shifting the same value.
3911
3912   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3913     return nullptr;   // Shifts must disagree.
3914
3915   // Canonicalize shl to left side in a shl/srl pair.
3916   if (RHSShift.getOpcode() == ISD::SHL) {
3917     std::swap(LHS, RHS);
3918     std::swap(LHSShift, RHSShift);
3919     std::swap(LHSMask , RHSMask );
3920   }
3921
3922   unsigned OpSizeInBits = VT.getSizeInBits();
3923   SDValue LHSShiftArg = LHSShift.getOperand(0);
3924   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3925   SDValue RHSShiftArg = RHSShift.getOperand(0);
3926   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3927
3928   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3929   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3930   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3931       RHSShiftAmt.getOpcode() == ISD::Constant) {
3932     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3933     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3934     if ((LShVal + RShVal) != OpSizeInBits)
3935       return nullptr;
3936
3937     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3938                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3939
3940     // If there is an AND of either shifted operand, apply it to the result.
3941     if (LHSMask.getNode() || RHSMask.getNode()) {
3942       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3943
3944       if (LHSMask.getNode()) {
3945         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3946         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3947       }
3948       if (RHSMask.getNode()) {
3949         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3950         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3951       }
3952
3953       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3954     }
3955
3956     return Rot.getNode();
3957   }
3958
3959   // If there is a mask here, and we have a variable shift, we can't be sure
3960   // that we're masking out the right stuff.
3961   if (LHSMask.getNode() || RHSMask.getNode())
3962     return nullptr;
3963
3964   // If the shift amount is sign/zext/any-extended just peel it off.
3965   SDValue LExtOp0 = LHSShiftAmt;
3966   SDValue RExtOp0 = RHSShiftAmt;
3967   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3968        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3969        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3970        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3971       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3972        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3973        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3974        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3975     LExtOp0 = LHSShiftAmt.getOperand(0);
3976     RExtOp0 = RHSShiftAmt.getOperand(0);
3977   }
3978
3979   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3980                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3981   if (TryL)
3982     return TryL;
3983
3984   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3985                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3986   if (TryR)
3987     return TryR;
3988
3989   return nullptr;
3990 }
3991
3992 SDValue DAGCombiner::visitXOR(SDNode *N) {
3993   SDValue N0 = N->getOperand(0);
3994   SDValue N1 = N->getOperand(1);
3995   EVT VT = N0.getValueType();
3996
3997   // fold vector ops
3998   if (VT.isVector()) {
3999     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4000       return FoldedVOp;
4001
4002     // fold (xor x, 0) -> x, vector edition
4003     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4004       return N1;
4005     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4006       return N0;
4007   }
4008
4009   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4010   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4011     return DAG.getConstant(0, SDLoc(N), VT);
4012   // fold (xor x, undef) -> undef
4013   if (N0.getOpcode() == ISD::UNDEF)
4014     return N0;
4015   if (N1.getOpcode() == ISD::UNDEF)
4016     return N1;
4017   // fold (xor c1, c2) -> c1^c2
4018   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4019   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4020   if (N0C && N1C)
4021     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4022   // canonicalize constant to RHS
4023   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4024      !isConstantIntBuildVectorOrConstantInt(N1))
4025     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4026   // fold (xor x, 0) -> x
4027   if (isNullConstant(N1))
4028     return N0;
4029   // reassociate xor
4030   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4031     return RXOR;
4032
4033   // fold !(x cc y) -> (x !cc y)
4034   SDValue LHS, RHS, CC;
4035   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4036     bool isInt = LHS.getValueType().isInteger();
4037     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4038                                                isInt);
4039
4040     if (!LegalOperations ||
4041         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4042       switch (N0.getOpcode()) {
4043       default:
4044         llvm_unreachable("Unhandled SetCC Equivalent!");
4045       case ISD::SETCC:
4046         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4047       case ISD::SELECT_CC:
4048         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4049                                N0.getOperand(3), NotCC);
4050       }
4051     }
4052   }
4053
4054   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4055   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4056       N0.getNode()->hasOneUse() &&
4057       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4058     SDValue V = N0.getOperand(0);
4059     SDLoc DL(N0);
4060     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4061                     DAG.getConstant(1, DL, V.getValueType()));
4062     AddToWorklist(V.getNode());
4063     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4064   }
4065
4066   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4067   if (isOneConstant(N1) && VT == MVT::i1 &&
4068       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4069     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4070     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4071       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4072       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4073       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4074       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4075       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4076     }
4077   }
4078   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4079   if (isAllOnesConstant(N1) &&
4080       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4081     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4082     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4083       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4084       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4085       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4086       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4087       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4088     }
4089   }
4090   // fold (xor (and x, y), y) -> (and (not x), y)
4091   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4092       N0->getOperand(1) == N1) {
4093     SDValue X = N0->getOperand(0);
4094     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4095     AddToWorklist(NotX.getNode());
4096     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4097   }
4098   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4099   if (N1C && N0.getOpcode() == ISD::XOR) {
4100     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4101       SDLoc DL(N);
4102       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4103                          DAG.getConstant(N1C->getAPIntValue() ^
4104                                          N00C->getAPIntValue(), DL, VT));
4105     }
4106     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4107       SDLoc DL(N);
4108       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4109                          DAG.getConstant(N1C->getAPIntValue() ^
4110                                          N01C->getAPIntValue(), DL, VT));
4111     }
4112   }
4113   // fold (xor x, x) -> 0
4114   if (N0 == N1)
4115     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4116
4117   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4118   // Here is a concrete example of this equivalence:
4119   // i16   x ==  14
4120   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4121   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4122   //
4123   // =>
4124   //
4125   // i16     ~1      == 0b1111111111111110
4126   // i16 rol(~1, 14) == 0b1011111111111111
4127   //
4128   // Some additional tips to help conceptualize this transform:
4129   // - Try to see the operation as placing a single zero in a value of all ones.
4130   // - There exists no value for x which would allow the result to contain zero.
4131   // - Values of x larger than the bitwidth are undefined and do not require a
4132   //   consistent result.
4133   // - Pushing the zero left requires shifting one bits in from the right.
4134   // A rotate left of ~1 is a nice way of achieving the desired result.
4135   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4136       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4137     SDLoc DL(N);
4138     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4139                        N0.getOperand(1));
4140   }
4141
4142   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4143   if (N0.getOpcode() == N1.getOpcode())
4144     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4145       return Tmp;
4146
4147   // Simplify the expression using non-local knowledge.
4148   if (!VT.isVector() &&
4149       SimplifyDemandedBits(SDValue(N, 0)))
4150     return SDValue(N, 0);
4151
4152   return SDValue();
4153 }
4154
4155 /// Handle transforms common to the three shifts, when the shift amount is a
4156 /// constant.
4157 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4158   SDNode *LHS = N->getOperand(0).getNode();
4159   if (!LHS->hasOneUse()) return SDValue();
4160
4161   // We want to pull some binops through shifts, so that we have (and (shift))
4162   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4163   // thing happens with address calculations, so it's important to canonicalize
4164   // it.
4165   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4166
4167   switch (LHS->getOpcode()) {
4168   default: return SDValue();
4169   case ISD::OR:
4170   case ISD::XOR:
4171     HighBitSet = false; // We can only transform sra if the high bit is clear.
4172     break;
4173   case ISD::AND:
4174     HighBitSet = true;  // We can only transform sra if the high bit is set.
4175     break;
4176   case ISD::ADD:
4177     if (N->getOpcode() != ISD::SHL)
4178       return SDValue(); // only shl(add) not sr[al](add).
4179     HighBitSet = false; // We can only transform sra if the high bit is clear.
4180     break;
4181   }
4182
4183   // We require the RHS of the binop to be a constant and not opaque as well.
4184   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4185   if (!BinOpCst) return SDValue();
4186
4187   // FIXME: disable this unless the input to the binop is a shift by a constant.
4188   // If it is not a shift, it pessimizes some common cases like:
4189   //
4190   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4191   //    int bar(int *X, int i) { return X[i & 255]; }
4192   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4193   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4194        BinOpLHSVal->getOpcode() != ISD::SRA &&
4195        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4196       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4197     return SDValue();
4198
4199   EVT VT = N->getValueType(0);
4200
4201   // If this is a signed shift right, and the high bit is modified by the
4202   // logical operation, do not perform the transformation. The highBitSet
4203   // boolean indicates the value of the high bit of the constant which would
4204   // cause it to be modified for this operation.
4205   if (N->getOpcode() == ISD::SRA) {
4206     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4207     if (BinOpRHSSignSet != HighBitSet)
4208       return SDValue();
4209   }
4210
4211   if (!TLI.isDesirableToCommuteWithShift(LHS))
4212     return SDValue();
4213
4214   // Fold the constants, shifting the binop RHS by the shift amount.
4215   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4216                                N->getValueType(0),
4217                                LHS->getOperand(1), N->getOperand(1));
4218   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4219
4220   // Create the new shift.
4221   SDValue NewShift = DAG.getNode(N->getOpcode(),
4222                                  SDLoc(LHS->getOperand(0)),
4223                                  VT, LHS->getOperand(0), N->getOperand(1));
4224
4225   // Create the new binop.
4226   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4227 }
4228
4229 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4230   assert(N->getOpcode() == ISD::TRUNCATE);
4231   assert(N->getOperand(0).getOpcode() == ISD::AND);
4232
4233   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4234   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4235     SDValue N01 = N->getOperand(0).getOperand(1);
4236
4237     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4238       if (!N01C->isOpaque()) {
4239         EVT TruncVT = N->getValueType(0);
4240         SDValue N00 = N->getOperand(0).getOperand(0);
4241         APInt TruncC = N01C->getAPIntValue();
4242         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4243         SDLoc DL(N);
4244
4245         return DAG.getNode(ISD::AND, DL, TruncVT,
4246                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4247                            DAG.getConstant(TruncC, DL, TruncVT));
4248       }
4249     }
4250   }
4251
4252   return SDValue();
4253 }
4254
4255 SDValue DAGCombiner::visitRotate(SDNode *N) {
4256   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4257   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4258       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4259     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4260     if (NewOp1.getNode())
4261       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4262                          N->getOperand(0), NewOp1);
4263   }
4264   return SDValue();
4265 }
4266
4267 SDValue DAGCombiner::visitSHL(SDNode *N) {
4268   SDValue N0 = N->getOperand(0);
4269   SDValue N1 = N->getOperand(1);
4270   EVT VT = N0.getValueType();
4271   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4272
4273   // fold vector ops
4274   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4275   if (VT.isVector()) {
4276     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4277       return FoldedVOp;
4278
4279     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4280     // If setcc produces all-one true value then:
4281     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4282     if (N1CV && N1CV->isConstant()) {
4283       if (N0.getOpcode() == ISD::AND) {
4284         SDValue N00 = N0->getOperand(0);
4285         SDValue N01 = N0->getOperand(1);
4286         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4287
4288         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4289             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4290                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4291           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4292                                                      N01CV, N1CV))
4293             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4294         }
4295       } else {
4296         N1C = isConstOrConstSplat(N1);
4297       }
4298     }
4299   }
4300
4301   // fold (shl c1, c2) -> c1<<c2
4302   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4303   if (N0C && N1C && !N1C->isOpaque())
4304     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4305   // fold (shl 0, x) -> 0
4306   if (isNullConstant(N0))
4307     return N0;
4308   // fold (shl x, c >= size(x)) -> undef
4309   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4310     return DAG.getUNDEF(VT);
4311   // fold (shl x, 0) -> x
4312   if (N1C && N1C->isNullValue())
4313     return N0;
4314   // fold (shl undef, x) -> 0
4315   if (N0.getOpcode() == ISD::UNDEF)
4316     return DAG.getConstant(0, SDLoc(N), VT);
4317   // if (shl x, c) is known to be zero, return 0
4318   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4319                             APInt::getAllOnesValue(OpSizeInBits)))
4320     return DAG.getConstant(0, SDLoc(N), VT);
4321   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4322   if (N1.getOpcode() == ISD::TRUNCATE &&
4323       N1.getOperand(0).getOpcode() == ISD::AND) {
4324     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4325     if (NewOp1.getNode())
4326       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4327   }
4328
4329   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4330     return SDValue(N, 0);
4331
4332   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4333   if (N1C && N0.getOpcode() == ISD::SHL) {
4334     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4335       uint64_t c1 = N0C1->getZExtValue();
4336       uint64_t c2 = N1C->getZExtValue();
4337       SDLoc DL(N);
4338       if (c1 + c2 >= OpSizeInBits)
4339         return DAG.getConstant(0, DL, VT);
4340       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4341                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4342     }
4343   }
4344
4345   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4346   // For this to be valid, the second form must not preserve any of the bits
4347   // that are shifted out by the inner shift in the first form.  This means
4348   // the outer shift size must be >= the number of bits added by the ext.
4349   // As a corollary, we don't care what kind of ext it is.
4350   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4351               N0.getOpcode() == ISD::ANY_EXTEND ||
4352               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4353       N0.getOperand(0).getOpcode() == ISD::SHL) {
4354     SDValue N0Op0 = N0.getOperand(0);
4355     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4356       uint64_t c1 = N0Op0C1->getZExtValue();
4357       uint64_t c2 = N1C->getZExtValue();
4358       EVT InnerShiftVT = N0Op0.getValueType();
4359       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4360       if (c2 >= OpSizeInBits - InnerShiftSize) {
4361         SDLoc DL(N0);
4362         if (c1 + c2 >= OpSizeInBits)
4363           return DAG.getConstant(0, DL, VT);
4364         return DAG.getNode(ISD::SHL, DL, VT,
4365                            DAG.getNode(N0.getOpcode(), DL, VT,
4366                                        N0Op0->getOperand(0)),
4367                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4368       }
4369     }
4370   }
4371
4372   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4373   // Only fold this if the inner zext has no other uses to avoid increasing
4374   // the total number of instructions.
4375   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4376       N0.getOperand(0).getOpcode() == ISD::SRL) {
4377     SDValue N0Op0 = N0.getOperand(0);
4378     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4379       uint64_t c1 = N0Op0C1->getZExtValue();
4380       if (c1 < VT.getScalarSizeInBits()) {
4381         uint64_t c2 = N1C->getZExtValue();
4382         if (c1 == c2) {
4383           SDValue NewOp0 = N0.getOperand(0);
4384           EVT CountVT = NewOp0.getOperand(1).getValueType();
4385           SDLoc DL(N);
4386           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4387                                        NewOp0,
4388                                        DAG.getConstant(c2, DL, CountVT));
4389           AddToWorklist(NewSHL.getNode());
4390           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4391         }
4392       }
4393     }
4394   }
4395
4396   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4397   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4398   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4399       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4400     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4401       uint64_t C1 = N0C1->getZExtValue();
4402       uint64_t C2 = N1C->getZExtValue();
4403       SDLoc DL(N);
4404       if (C1 <= C2)
4405         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4406                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4407       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4408                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4409     }
4410   }
4411
4412   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4413   //                               (and (srl x, (sub c1, c2), MASK)
4414   // Only fold this if the inner shift has no other uses -- if it does, folding
4415   // this will increase the total number of instructions.
4416   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4417     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4418       uint64_t c1 = N0C1->getZExtValue();
4419       if (c1 < OpSizeInBits) {
4420         uint64_t c2 = N1C->getZExtValue();
4421         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4422         SDValue Shift;
4423         if (c2 > c1) {
4424           Mask = Mask.shl(c2 - c1);
4425           SDLoc DL(N);
4426           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4427                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4428         } else {
4429           Mask = Mask.lshr(c1 - c2);
4430           SDLoc DL(N);
4431           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4432                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4433         }
4434         SDLoc DL(N0);
4435         return DAG.getNode(ISD::AND, DL, VT, Shift,
4436                            DAG.getConstant(Mask, DL, VT));
4437       }
4438     }
4439   }
4440   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4441   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4442     unsigned BitSize = VT.getScalarSizeInBits();
4443     SDLoc DL(N);
4444     SDValue HiBitsMask =
4445       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4446                                             BitSize - N1C->getZExtValue()),
4447                       DL, VT);
4448     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4449                        HiBitsMask);
4450   }
4451
4452   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4453   // Variant of version done on multiply, except mul by a power of 2 is turned
4454   // into a shift.
4455   APInt Val;
4456   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4457       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4458        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4459     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4460     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4461     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4462   }
4463
4464   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4465   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4466     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4467       if (SDValue Folded =
4468               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4469         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4470     }
4471   }
4472
4473   if (N1C && !N1C->isOpaque())
4474     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4475       return NewSHL;
4476
4477   return SDValue();
4478 }
4479
4480 SDValue DAGCombiner::visitSRA(SDNode *N) {
4481   SDValue N0 = N->getOperand(0);
4482   SDValue N1 = N->getOperand(1);
4483   EVT VT = N0.getValueType();
4484   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4485
4486   // fold vector ops
4487   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4488   if (VT.isVector()) {
4489     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4490       return FoldedVOp;
4491
4492     N1C = isConstOrConstSplat(N1);
4493   }
4494
4495   // fold (sra c1, c2) -> (sra c1, c2)
4496   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4497   if (N0C && N1C && !N1C->isOpaque())
4498     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4499   // fold (sra 0, x) -> 0
4500   if (isNullConstant(N0))
4501     return N0;
4502   // fold (sra -1, x) -> -1
4503   if (isAllOnesConstant(N0))
4504     return N0;
4505   // fold (sra x, (setge c, size(x))) -> undef
4506   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4507     return DAG.getUNDEF(VT);
4508   // fold (sra x, 0) -> x
4509   if (N1C && N1C->isNullValue())
4510     return N0;
4511   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4512   // sext_inreg.
4513   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4514     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4515     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4516     if (VT.isVector())
4517       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4518                                ExtVT, VT.getVectorNumElements());
4519     if ((!LegalOperations ||
4520          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4521       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4522                          N0.getOperand(0), DAG.getValueType(ExtVT));
4523   }
4524
4525   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4526   if (N1C && N0.getOpcode() == ISD::SRA) {
4527     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4528       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4529       if (Sum >= OpSizeInBits)
4530         Sum = OpSizeInBits - 1;
4531       SDLoc DL(N);
4532       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4533                          DAG.getConstant(Sum, DL, N1.getValueType()));
4534     }
4535   }
4536
4537   // fold (sra (shl X, m), (sub result_size, n))
4538   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4539   // result_size - n != m.
4540   // If truncate is free for the target sext(shl) is likely to result in better
4541   // code.
4542   if (N0.getOpcode() == ISD::SHL && N1C) {
4543     // Get the two constanst of the shifts, CN0 = m, CN = n.
4544     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4545     if (N01C) {
4546       LLVMContext &Ctx = *DAG.getContext();
4547       // Determine what the truncate's result bitsize and type would be.
4548       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4549
4550       if (VT.isVector())
4551         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4552
4553       // Determine the residual right-shift amount.
4554       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4555
4556       // If the shift is not a no-op (in which case this should be just a sign
4557       // extend already), the truncated to type is legal, sign_extend is legal
4558       // on that type, and the truncate to that type is both legal and free,
4559       // perform the transform.
4560       if ((ShiftAmt > 0) &&
4561           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4562           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4563           TLI.isTruncateFree(VT, TruncVT)) {
4564
4565         SDLoc DL(N);
4566         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4567             getShiftAmountTy(N0.getOperand(0).getValueType()));
4568         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4569                                     N0.getOperand(0), Amt);
4570         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4571                                     Shift);
4572         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4573                            N->getValueType(0), Trunc);
4574       }
4575     }
4576   }
4577
4578   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4579   if (N1.getOpcode() == ISD::TRUNCATE &&
4580       N1.getOperand(0).getOpcode() == ISD::AND) {
4581     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4582     if (NewOp1.getNode())
4583       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4584   }
4585
4586   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4587   //      if c1 is equal to the number of bits the trunc removes
4588   if (N0.getOpcode() == ISD::TRUNCATE &&
4589       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4590        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4591       N0.getOperand(0).hasOneUse() &&
4592       N0.getOperand(0).getOperand(1).hasOneUse() &&
4593       N1C) {
4594     SDValue N0Op0 = N0.getOperand(0);
4595     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4596       unsigned LargeShiftVal = LargeShift->getZExtValue();
4597       EVT LargeVT = N0Op0.getValueType();
4598
4599       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4600         SDLoc DL(N);
4601         SDValue Amt =
4602           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4603                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4604         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4605                                   N0Op0.getOperand(0), Amt);
4606         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4607       }
4608     }
4609   }
4610
4611   // Simplify, based on bits shifted out of the LHS.
4612   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4613     return SDValue(N, 0);
4614
4615
4616   // If the sign bit is known to be zero, switch this to a SRL.
4617   if (DAG.SignBitIsZero(N0))
4618     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4619
4620   if (N1C && !N1C->isOpaque())
4621     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4622       return NewSRA;
4623
4624   return SDValue();
4625 }
4626
4627 SDValue DAGCombiner::visitSRL(SDNode *N) {
4628   SDValue N0 = N->getOperand(0);
4629   SDValue N1 = N->getOperand(1);
4630   EVT VT = N0.getValueType();
4631   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4632
4633   // fold vector ops
4634   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4635   if (VT.isVector()) {
4636     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4637       return FoldedVOp;
4638
4639     N1C = isConstOrConstSplat(N1);
4640   }
4641
4642   // fold (srl c1, c2) -> c1 >>u c2
4643   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4644   if (N0C && N1C && !N1C->isOpaque())
4645     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4646   // fold (srl 0, x) -> 0
4647   if (isNullConstant(N0))
4648     return N0;
4649   // fold (srl x, c >= size(x)) -> undef
4650   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4651     return DAG.getUNDEF(VT);
4652   // fold (srl x, 0) -> x
4653   if (N1C && N1C->isNullValue())
4654     return N0;
4655   // if (srl x, c) is known to be zero, return 0
4656   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4657                                    APInt::getAllOnesValue(OpSizeInBits)))
4658     return DAG.getConstant(0, SDLoc(N), VT);
4659
4660   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4661   if (N1C && N0.getOpcode() == ISD::SRL) {
4662     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4663       uint64_t c1 = N01C->getZExtValue();
4664       uint64_t c2 = N1C->getZExtValue();
4665       SDLoc DL(N);
4666       if (c1 + c2 >= OpSizeInBits)
4667         return DAG.getConstant(0, DL, VT);
4668       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4669                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4670     }
4671   }
4672
4673   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4674   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4675       N0.getOperand(0).getOpcode() == ISD::SRL &&
4676       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4677     uint64_t c1 =
4678       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4679     uint64_t c2 = N1C->getZExtValue();
4680     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4681     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4682     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4683     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4684     if (c1 + OpSizeInBits == InnerShiftSize) {
4685       SDLoc DL(N0);
4686       if (c1 + c2 >= InnerShiftSize)
4687         return DAG.getConstant(0, DL, VT);
4688       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4689                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4690                                      N0.getOperand(0)->getOperand(0),
4691                                      DAG.getConstant(c1 + c2, DL,
4692                                                      ShiftCountVT)));
4693     }
4694   }
4695
4696   // fold (srl (shl x, c), c) -> (and x, cst2)
4697   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4698     unsigned BitSize = N0.getScalarValueSizeInBits();
4699     if (BitSize <= 64) {
4700       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4701       SDLoc DL(N);
4702       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4703                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4704     }
4705   }
4706
4707   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4708   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4709     // Shifting in all undef bits?
4710     EVT SmallVT = N0.getOperand(0).getValueType();
4711     unsigned BitSize = SmallVT.getScalarSizeInBits();
4712     if (N1C->getZExtValue() >= BitSize)
4713       return DAG.getUNDEF(VT);
4714
4715     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4716       uint64_t ShiftAmt = N1C->getZExtValue();
4717       SDLoc DL0(N0);
4718       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4719                                        N0.getOperand(0),
4720                           DAG.getConstant(ShiftAmt, DL0,
4721                                           getShiftAmountTy(SmallVT)));
4722       AddToWorklist(SmallShift.getNode());
4723       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4724       SDLoc DL(N);
4725       return DAG.getNode(ISD::AND, DL, VT,
4726                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4727                          DAG.getConstant(Mask, DL, VT));
4728     }
4729   }
4730
4731   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4732   // bit, which is unmodified by sra.
4733   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4734     if (N0.getOpcode() == ISD::SRA)
4735       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4736   }
4737
4738   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4739   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4740       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4741     APInt KnownZero, KnownOne;
4742     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4743
4744     // If any of the input bits are KnownOne, then the input couldn't be all
4745     // zeros, thus the result of the srl will always be zero.
4746     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4747
4748     // If all of the bits input the to ctlz node are known to be zero, then
4749     // the result of the ctlz is "32" and the result of the shift is one.
4750     APInt UnknownBits = ~KnownZero;
4751     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4752
4753     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4754     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4755       // Okay, we know that only that the single bit specified by UnknownBits
4756       // could be set on input to the CTLZ node. If this bit is set, the SRL
4757       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4758       // to an SRL/XOR pair, which is likely to simplify more.
4759       unsigned ShAmt = UnknownBits.countTrailingZeros();
4760       SDValue Op = N0.getOperand(0);
4761
4762       if (ShAmt) {
4763         SDLoc DL(N0);
4764         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4765                   DAG.getConstant(ShAmt, DL,
4766                                   getShiftAmountTy(Op.getValueType())));
4767         AddToWorklist(Op.getNode());
4768       }
4769
4770       SDLoc DL(N);
4771       return DAG.getNode(ISD::XOR, DL, VT,
4772                          Op, DAG.getConstant(1, DL, VT));
4773     }
4774   }
4775
4776   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4777   if (N1.getOpcode() == ISD::TRUNCATE &&
4778       N1.getOperand(0).getOpcode() == ISD::AND) {
4779     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4780       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4781   }
4782
4783   // fold operands of srl based on knowledge that the low bits are not
4784   // demanded.
4785   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4786     return SDValue(N, 0);
4787
4788   if (N1C && !N1C->isOpaque())
4789     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4790       return NewSRL;
4791
4792   // Attempt to convert a srl of a load into a narrower zero-extending load.
4793   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4794     return NarrowLoad;
4795
4796   // Here is a common situation. We want to optimize:
4797   //
4798   //   %a = ...
4799   //   %b = and i32 %a, 2
4800   //   %c = srl i32 %b, 1
4801   //   brcond i32 %c ...
4802   //
4803   // into
4804   //
4805   //   %a = ...
4806   //   %b = and %a, 2
4807   //   %c = setcc eq %b, 0
4808   //   brcond %c ...
4809   //
4810   // However when after the source operand of SRL is optimized into AND, the SRL
4811   // itself may not be optimized further. Look for it and add the BRCOND into
4812   // the worklist.
4813   if (N->hasOneUse()) {
4814     SDNode *Use = *N->use_begin();
4815     if (Use->getOpcode() == ISD::BRCOND)
4816       AddToWorklist(Use);
4817     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4818       // Also look pass the truncate.
4819       Use = *Use->use_begin();
4820       if (Use->getOpcode() == ISD::BRCOND)
4821         AddToWorklist(Use);
4822     }
4823   }
4824
4825   return SDValue();
4826 }
4827
4828 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4829   SDValue N0 = N->getOperand(0);
4830   EVT VT = N->getValueType(0);
4831
4832   // fold (bswap c1) -> c2
4833   if (isConstantIntBuildVectorOrConstantInt(N0))
4834     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4835   // fold (bswap (bswap x)) -> x
4836   if (N0.getOpcode() == ISD::BSWAP)
4837     return N0->getOperand(0);
4838   return SDValue();
4839 }
4840
4841 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4842   SDValue N0 = N->getOperand(0);
4843   EVT VT = N->getValueType(0);
4844
4845   // fold (ctlz c1) -> c2
4846   if (isConstantIntBuildVectorOrConstantInt(N0))
4847     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4848   return SDValue();
4849 }
4850
4851 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4852   SDValue N0 = N->getOperand(0);
4853   EVT VT = N->getValueType(0);
4854
4855   // fold (ctlz_zero_undef c1) -> c2
4856   if (isConstantIntBuildVectorOrConstantInt(N0))
4857     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4858   return SDValue();
4859 }
4860
4861 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4862   SDValue N0 = N->getOperand(0);
4863   EVT VT = N->getValueType(0);
4864
4865   // fold (cttz c1) -> c2
4866   if (isConstantIntBuildVectorOrConstantInt(N0))
4867     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4868   return SDValue();
4869 }
4870
4871 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4872   SDValue N0 = N->getOperand(0);
4873   EVT VT = N->getValueType(0);
4874
4875   // fold (cttz_zero_undef c1) -> c2
4876   if (isConstantIntBuildVectorOrConstantInt(N0))
4877     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4878   return SDValue();
4879 }
4880
4881 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4882   SDValue N0 = N->getOperand(0);
4883   EVT VT = N->getValueType(0);
4884
4885   // fold (ctpop c1) -> c2
4886   if (isConstantIntBuildVectorOrConstantInt(N0))
4887     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4888   return SDValue();
4889 }
4890
4891
4892 /// \brief Generate Min/Max node
4893 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4894                                    SDValue True, SDValue False,
4895                                    ISD::CondCode CC, const TargetLowering &TLI,
4896                                    SelectionDAG &DAG) {
4897   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4898     return SDValue();
4899
4900   switch (CC) {
4901   case ISD::SETOLT:
4902   case ISD::SETOLE:
4903   case ISD::SETLT:
4904   case ISD::SETLE:
4905   case ISD::SETULT:
4906   case ISD::SETULE: {
4907     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4908     if (TLI.isOperationLegal(Opcode, VT))
4909       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4910     return SDValue();
4911   }
4912   case ISD::SETOGT:
4913   case ISD::SETOGE:
4914   case ISD::SETGT:
4915   case ISD::SETGE:
4916   case ISD::SETUGT:
4917   case ISD::SETUGE: {
4918     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4919     if (TLI.isOperationLegal(Opcode, VT))
4920       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4921     return SDValue();
4922   }
4923   default:
4924     return SDValue();
4925   }
4926 }
4927
4928 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4929   SDValue N0 = N->getOperand(0);
4930   SDValue N1 = N->getOperand(1);
4931   SDValue N2 = N->getOperand(2);
4932   EVT VT = N->getValueType(0);
4933   EVT VT0 = N0.getValueType();
4934
4935   // fold (select C, X, X) -> X
4936   if (N1 == N2)
4937     return N1;
4938   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4939     // fold (select true, X, Y) -> X
4940     // fold (select false, X, Y) -> Y
4941     return !N0C->isNullValue() ? N1 : N2;
4942   }
4943   // fold (select C, 1, X) -> (or C, X)
4944   if (VT == MVT::i1 && isOneConstant(N1))
4945     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4946   // fold (select C, 0, 1) -> (xor C, 1)
4947   // We can't do this reliably if integer based booleans have different contents
4948   // to floating point based booleans. This is because we can't tell whether we
4949   // have an integer-based boolean or a floating-point-based boolean unless we
4950   // can find the SETCC that produced it and inspect its operands. This is
4951   // fairly easy if C is the SETCC node, but it can potentially be
4952   // undiscoverable (or not reasonably discoverable). For example, it could be
4953   // in another basic block or it could require searching a complicated
4954   // expression.
4955   if (VT.isInteger() &&
4956       (VT0 == MVT::i1 || (VT0.isInteger() &&
4957                           TLI.getBooleanContents(false, false) ==
4958                               TLI.getBooleanContents(false, true) &&
4959                           TLI.getBooleanContents(false, false) ==
4960                               TargetLowering::ZeroOrOneBooleanContent)) &&
4961       isNullConstant(N1) && isOneConstant(N2)) {
4962     SDValue XORNode;
4963     if (VT == VT0) {
4964       SDLoc DL(N);
4965       return DAG.getNode(ISD::XOR, DL, VT0,
4966                          N0, DAG.getConstant(1, DL, VT0));
4967     }
4968     SDLoc DL0(N0);
4969     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4970                           N0, DAG.getConstant(1, DL0, VT0));
4971     AddToWorklist(XORNode.getNode());
4972     if (VT.bitsGT(VT0))
4973       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4974     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4975   }
4976   // fold (select C, 0, X) -> (and (not C), X)
4977   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4978     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4979     AddToWorklist(NOTNode.getNode());
4980     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4981   }
4982   // fold (select C, X, 1) -> (or (not C), X)
4983   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4984     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4985     AddToWorklist(NOTNode.getNode());
4986     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4987   }
4988   // fold (select C, X, 0) -> (and C, X)
4989   if (VT == MVT::i1 && isNullConstant(N2))
4990     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4991   // fold (select X, X, Y) -> (or X, Y)
4992   // fold (select X, 1, Y) -> (or X, Y)
4993   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4994     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4995   // fold (select X, Y, X) -> (and X, Y)
4996   // fold (select X, Y, 0) -> (and X, Y)
4997   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4998     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4999
5000   // If we can fold this based on the true/false value, do so.
5001   if (SimplifySelectOps(N, N1, N2))
5002     return SDValue(N, 0);  // Don't revisit N.
5003
5004   if (VT0 == MVT::i1) {
5005     // The code in this block deals with the following 2 equivalences:
5006     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5007     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5008     // The target can specify its prefered form with the
5009     // shouldNormalizeToSelectSequence() callback. However we always transform
5010     // to the right anyway if we find the inner select exists in the DAG anyway
5011     // and we always transform to the left side if we know that we can further
5012     // optimize the combination of the conditions.
5013     bool normalizeToSequence
5014       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5015     // select (and Cond0, Cond1), X, Y
5016     //   -> select Cond0, (select Cond1, X, Y), Y
5017     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5018       SDValue Cond0 = N0->getOperand(0);
5019       SDValue Cond1 = N0->getOperand(1);
5020       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5021                                         N1.getValueType(), Cond1, N1, N2);
5022       if (normalizeToSequence || !InnerSelect.use_empty())
5023         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5024                            InnerSelect, N2);
5025     }
5026     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5027     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5028       SDValue Cond0 = N0->getOperand(0);
5029       SDValue Cond1 = N0->getOperand(1);
5030       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5031                                         N1.getValueType(), Cond1, N1, N2);
5032       if (normalizeToSequence || !InnerSelect.use_empty())
5033         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5034                            InnerSelect);
5035     }
5036
5037     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5038     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5039       SDValue N1_0 = N1->getOperand(0);
5040       SDValue N1_1 = N1->getOperand(1);
5041       SDValue N1_2 = N1->getOperand(2);
5042       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5043         // Create the actual and node if we can generate good code for it.
5044         if (!normalizeToSequence) {
5045           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5046                                     N0, N1_0);
5047           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5048                              N1_1, N2);
5049         }
5050         // Otherwise see if we can optimize the "and" to a better pattern.
5051         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5052           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5053                              N1_1, N2);
5054       }
5055     }
5056     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5057     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5058       SDValue N2_0 = N2->getOperand(0);
5059       SDValue N2_1 = N2->getOperand(1);
5060       SDValue N2_2 = N2->getOperand(2);
5061       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5062         // Create the actual or node if we can generate good code for it.
5063         if (!normalizeToSequence) {
5064           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5065                                    N0, N2_0);
5066           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5067                              N1, N2_2);
5068         }
5069         // Otherwise see if we can optimize to a better pattern.
5070         if (SDValue Combined = visitORLike(N0, N2_0, N))
5071           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5072                              N1, N2_2);
5073       }
5074     }
5075   }
5076
5077   // fold selects based on a setcc into other things, such as min/max/abs
5078   if (N0.getOpcode() == ISD::SETCC) {
5079     // select x, y (fcmp lt x, y) -> fminnum x, y
5080     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5081     //
5082     // This is OK if we don't care about what happens if either operand is a
5083     // NaN.
5084     //
5085
5086     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5087     // no signed zeros as well as no nans.
5088     const TargetOptions &Options = DAG.getTarget().Options;
5089     if (Options.UnsafeFPMath &&
5090         VT.isFloatingPoint() && N0.hasOneUse() &&
5091         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5092       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5093
5094       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5095                                                 N0.getOperand(1), N1, N2, CC,
5096                                                 TLI, DAG))
5097         return FMinMax;
5098     }
5099
5100     if ((!LegalOperations &&
5101          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5102         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5103       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5104                          N0.getOperand(0), N0.getOperand(1),
5105                          N1, N2, N0.getOperand(2));
5106     return SimplifySelect(SDLoc(N), N0, N1, N2);
5107   }
5108
5109   return SDValue();
5110 }
5111
5112 static
5113 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5114   SDLoc DL(N);
5115   EVT LoVT, HiVT;
5116   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5117
5118   // Split the inputs.
5119   SDValue Lo, Hi, LL, LH, RL, RH;
5120   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5121   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5122
5123   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5124   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5125
5126   return std::make_pair(Lo, Hi);
5127 }
5128
5129 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5130 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5131 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5132   SDLoc dl(N);
5133   SDValue Cond = N->getOperand(0);
5134   SDValue LHS = N->getOperand(1);
5135   SDValue RHS = N->getOperand(2);
5136   EVT VT = N->getValueType(0);
5137   int NumElems = VT.getVectorNumElements();
5138   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5139          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5140          Cond.getOpcode() == ISD::BUILD_VECTOR);
5141
5142   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5143   // binary ones here.
5144   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5145     return SDValue();
5146
5147   // We're sure we have an even number of elements due to the
5148   // concat_vectors we have as arguments to vselect.
5149   // Skip BV elements until we find one that's not an UNDEF
5150   // After we find an UNDEF element, keep looping until we get to half the
5151   // length of the BV and see if all the non-undef nodes are the same.
5152   ConstantSDNode *BottomHalf = nullptr;
5153   for (int i = 0; i < NumElems / 2; ++i) {
5154     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5155       continue;
5156
5157     if (BottomHalf == nullptr)
5158       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5159     else if (Cond->getOperand(i).getNode() != BottomHalf)
5160       return SDValue();
5161   }
5162
5163   // Do the same for the second half of the BuildVector
5164   ConstantSDNode *TopHalf = nullptr;
5165   for (int i = NumElems / 2; i < NumElems; ++i) {
5166     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5167       continue;
5168
5169     if (TopHalf == nullptr)
5170       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5171     else if (Cond->getOperand(i).getNode() != TopHalf)
5172       return SDValue();
5173   }
5174
5175   assert(TopHalf && BottomHalf &&
5176          "One half of the selector was all UNDEFs and the other was all the "
5177          "same value. This should have been addressed before this function.");
5178   return DAG.getNode(
5179       ISD::CONCAT_VECTORS, dl, VT,
5180       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5181       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5182 }
5183
5184 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5185
5186   if (Level >= AfterLegalizeTypes)
5187     return SDValue();
5188
5189   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5190   SDValue Mask = MSC->getMask();
5191   SDValue Data  = MSC->getValue();
5192   SDLoc DL(N);
5193
5194   // If the MSCATTER data type requires splitting and the mask is provided by a
5195   // SETCC, then split both nodes and its operands before legalization. This
5196   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5197   // and enables future optimizations (e.g. min/max pattern matching on X86).
5198   if (Mask.getOpcode() != ISD::SETCC)
5199     return SDValue();
5200
5201   // Check if any splitting is required.
5202   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5203       TargetLowering::TypeSplitVector)
5204     return SDValue();
5205   SDValue MaskLo, MaskHi, Lo, Hi;
5206   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5207
5208   EVT LoVT, HiVT;
5209   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5210
5211   SDValue Chain = MSC->getChain();
5212
5213   EVT MemoryVT = MSC->getMemoryVT();
5214   unsigned Alignment = MSC->getOriginalAlignment();
5215
5216   EVT LoMemVT, HiMemVT;
5217   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5218
5219   SDValue DataLo, DataHi;
5220   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5221
5222   SDValue BasePtr = MSC->getBasePtr();
5223   SDValue IndexLo, IndexHi;
5224   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5225
5226   MachineMemOperand *MMO = DAG.getMachineFunction().
5227     getMachineMemOperand(MSC->getPointerInfo(),
5228                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5229                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5230
5231   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5232   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5233                             DL, OpsLo, MMO);
5234
5235   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5236   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5237                             DL, OpsHi, MMO);
5238
5239   AddToWorklist(Lo.getNode());
5240   AddToWorklist(Hi.getNode());
5241
5242   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5243 }
5244
5245 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5246
5247   if (Level >= AfterLegalizeTypes)
5248     return SDValue();
5249
5250   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5251   SDValue Mask = MST->getMask();
5252   SDValue Data  = MST->getValue();
5253   SDLoc DL(N);
5254
5255   // If the MSTORE data type requires splitting and the mask is provided by a
5256   // SETCC, then split both nodes and its operands before legalization. This
5257   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5258   // and enables future optimizations (e.g. min/max pattern matching on X86).
5259   if (Mask.getOpcode() == ISD::SETCC) {
5260
5261     // Check if any splitting is required.
5262     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5263         TargetLowering::TypeSplitVector)
5264       return SDValue();
5265
5266     SDValue MaskLo, MaskHi, Lo, Hi;
5267     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5268
5269     EVT LoVT, HiVT;
5270     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5271
5272     SDValue Chain = MST->getChain();
5273     SDValue Ptr   = MST->getBasePtr();
5274
5275     EVT MemoryVT = MST->getMemoryVT();
5276     unsigned Alignment = MST->getOriginalAlignment();
5277
5278     // if Alignment is equal to the vector size,
5279     // take the half of it for the second part
5280     unsigned SecondHalfAlignment =
5281       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5282          Alignment/2 : Alignment;
5283
5284     EVT LoMemVT, HiMemVT;
5285     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5286
5287     SDValue DataLo, DataHi;
5288     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5289
5290     MachineMemOperand *MMO = DAG.getMachineFunction().
5291       getMachineMemOperand(MST->getPointerInfo(),
5292                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5293                            Alignment, MST->getAAInfo(), MST->getRanges());
5294
5295     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5296                             MST->isTruncatingStore());
5297
5298     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5299     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5300                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5301
5302     MMO = DAG.getMachineFunction().
5303       getMachineMemOperand(MST->getPointerInfo(),
5304                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5305                            SecondHalfAlignment, MST->getAAInfo(),
5306                            MST->getRanges());
5307
5308     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5309                             MST->isTruncatingStore());
5310
5311     AddToWorklist(Lo.getNode());
5312     AddToWorklist(Hi.getNode());
5313
5314     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5315   }
5316   return SDValue();
5317 }
5318
5319 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5320
5321   if (Level >= AfterLegalizeTypes)
5322     return SDValue();
5323
5324   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5325   SDValue Mask = MGT->getMask();
5326   SDLoc DL(N);
5327
5328   // If the MGATHER result requires splitting and the mask is provided by a
5329   // SETCC, then split both nodes and its operands before legalization. This
5330   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5331   // and enables future optimizations (e.g. min/max pattern matching on X86).
5332
5333   if (Mask.getOpcode() != ISD::SETCC)
5334     return SDValue();
5335
5336   EVT VT = N->getValueType(0);
5337
5338   // Check if any splitting is required.
5339   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5340       TargetLowering::TypeSplitVector)
5341     return SDValue();
5342
5343   SDValue MaskLo, MaskHi, Lo, Hi;
5344   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5345
5346   SDValue Src0 = MGT->getValue();
5347   SDValue Src0Lo, Src0Hi;
5348   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5349
5350   EVT LoVT, HiVT;
5351   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5352
5353   SDValue Chain = MGT->getChain();
5354   EVT MemoryVT = MGT->getMemoryVT();
5355   unsigned Alignment = MGT->getOriginalAlignment();
5356
5357   EVT LoMemVT, HiMemVT;
5358   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5359
5360   SDValue BasePtr = MGT->getBasePtr();
5361   SDValue Index = MGT->getIndex();
5362   SDValue IndexLo, IndexHi;
5363   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5364
5365   MachineMemOperand *MMO = DAG.getMachineFunction().
5366     getMachineMemOperand(MGT->getPointerInfo(),
5367                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5368                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5369
5370   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5371   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5372                             MMO);
5373
5374   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5375   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5376                             MMO);
5377
5378   AddToWorklist(Lo.getNode());
5379   AddToWorklist(Hi.getNode());
5380
5381   // Build a factor node to remember that this load is independent of the
5382   // other one.
5383   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5384                       Hi.getValue(1));
5385
5386   // Legalized the chain result - switch anything that used the old chain to
5387   // use the new one.
5388   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5389
5390   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5391
5392   SDValue RetOps[] = { GatherRes, Chain };
5393   return DAG.getMergeValues(RetOps, DL);
5394 }
5395
5396 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5397
5398   if (Level >= AfterLegalizeTypes)
5399     return SDValue();
5400
5401   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5402   SDValue Mask = MLD->getMask();
5403   SDLoc DL(N);
5404
5405   // If the MLOAD result requires splitting and the mask is provided by a
5406   // SETCC, then split both nodes and its operands before legalization. This
5407   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5408   // and enables future optimizations (e.g. min/max pattern matching on X86).
5409
5410   if (Mask.getOpcode() == ISD::SETCC) {
5411     EVT VT = N->getValueType(0);
5412
5413     // Check if any splitting is required.
5414     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5415         TargetLowering::TypeSplitVector)
5416       return SDValue();
5417
5418     SDValue MaskLo, MaskHi, Lo, Hi;
5419     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5420
5421     SDValue Src0 = MLD->getSrc0();
5422     SDValue Src0Lo, Src0Hi;
5423     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5424
5425     EVT LoVT, HiVT;
5426     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5427
5428     SDValue Chain = MLD->getChain();
5429     SDValue Ptr   = MLD->getBasePtr();
5430     EVT MemoryVT = MLD->getMemoryVT();
5431     unsigned Alignment = MLD->getOriginalAlignment();
5432
5433     // if Alignment is equal to the vector size,
5434     // take the half of it for the second part
5435     unsigned SecondHalfAlignment =
5436       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5437          Alignment/2 : Alignment;
5438
5439     EVT LoMemVT, HiMemVT;
5440     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5441
5442     MachineMemOperand *MMO = DAG.getMachineFunction().
5443     getMachineMemOperand(MLD->getPointerInfo(),
5444                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5445                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5446
5447     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5448                            ISD::NON_EXTLOAD);
5449
5450     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5451     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5452                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5453
5454     MMO = DAG.getMachineFunction().
5455     getMachineMemOperand(MLD->getPointerInfo(),
5456                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5457                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5458
5459     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5460                            ISD::NON_EXTLOAD);
5461
5462     AddToWorklist(Lo.getNode());
5463     AddToWorklist(Hi.getNode());
5464
5465     // Build a factor node to remember that this load is independent of the
5466     // other one.
5467     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5468                         Hi.getValue(1));
5469
5470     // Legalized the chain result - switch anything that used the old chain to
5471     // use the new one.
5472     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5473
5474     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5475
5476     SDValue RetOps[] = { LoadRes, Chain };
5477     return DAG.getMergeValues(RetOps, DL);
5478   }
5479   return SDValue();
5480 }
5481
5482 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5483   SDValue N0 = N->getOperand(0);
5484   SDValue N1 = N->getOperand(1);
5485   SDValue N2 = N->getOperand(2);
5486   SDLoc DL(N);
5487
5488   // Canonicalize integer abs.
5489   // vselect (setg[te] X,  0),  X, -X ->
5490   // vselect (setgt    X, -1),  X, -X ->
5491   // vselect (setl[te] X,  0), -X,  X ->
5492   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5493   if (N0.getOpcode() == ISD::SETCC) {
5494     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5495     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5496     bool isAbs = false;
5497     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5498
5499     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5500          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5501         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5502       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5503     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5504              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5505       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5506
5507     if (isAbs) {
5508       EVT VT = LHS.getValueType();
5509       SDValue Shift = DAG.getNode(
5510           ISD::SRA, DL, VT, LHS,
5511           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5512       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5513       AddToWorklist(Shift.getNode());
5514       AddToWorklist(Add.getNode());
5515       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5516     }
5517   }
5518
5519   if (SimplifySelectOps(N, N1, N2))
5520     return SDValue(N, 0);  // Don't revisit N.
5521
5522   // If the VSELECT result requires splitting and the mask is provided by a
5523   // SETCC, then split both nodes and its operands before legalization. This
5524   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5525   // and enables future optimizations (e.g. min/max pattern matching on X86).
5526   if (N0.getOpcode() == ISD::SETCC) {
5527     EVT VT = N->getValueType(0);
5528
5529     // Check if any splitting is required.
5530     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5531         TargetLowering::TypeSplitVector)
5532       return SDValue();
5533
5534     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5535     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5536     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5537     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5538
5539     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5540     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5541
5542     // Add the new VSELECT nodes to the work list in case they need to be split
5543     // again.
5544     AddToWorklist(Lo.getNode());
5545     AddToWorklist(Hi.getNode());
5546
5547     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5548   }
5549
5550   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5551   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5552     return N1;
5553   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5554   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5555     return N2;
5556
5557   // The ConvertSelectToConcatVector function is assuming both the above
5558   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5559   // and addressed.
5560   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5561       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5562       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5563     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5564       return CV;
5565   }
5566
5567   return SDValue();
5568 }
5569
5570 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5571   SDValue N0 = N->getOperand(0);
5572   SDValue N1 = N->getOperand(1);
5573   SDValue N2 = N->getOperand(2);
5574   SDValue N3 = N->getOperand(3);
5575   SDValue N4 = N->getOperand(4);
5576   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5577
5578   // fold select_cc lhs, rhs, x, x, cc -> x
5579   if (N2 == N3)
5580     return N2;
5581
5582   // Determine if the condition we're dealing with is constant
5583   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5584                               N0, N1, CC, SDLoc(N), false);
5585   if (SCC.getNode()) {
5586     AddToWorklist(SCC.getNode());
5587
5588     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5589       if (!SCCC->isNullValue())
5590         return N2;    // cond always true -> true val
5591       else
5592         return N3;    // cond always false -> false val
5593     } else if (SCC->getOpcode() == ISD::UNDEF) {
5594       // When the condition is UNDEF, just return the first operand. This is
5595       // coherent the DAG creation, no setcc node is created in this case
5596       return N2;
5597     } else if (SCC.getOpcode() == ISD::SETCC) {
5598       // Fold to a simpler select_cc
5599       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5600                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5601                          SCC.getOperand(2));
5602     }
5603   }
5604
5605   // If we can fold this based on the true/false value, do so.
5606   if (SimplifySelectOps(N, N2, N3))
5607     return SDValue(N, 0);  // Don't revisit N.
5608
5609   // fold select_cc into other things, such as min/max/abs
5610   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5611 }
5612
5613 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5614   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5615                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5616                        SDLoc(N));
5617 }
5618
5619 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5620 /// a build_vector of constants.
5621 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5622 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5623 /// Vector extends are not folded if operations are legal; this is to
5624 /// avoid introducing illegal build_vector dag nodes.
5625 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5626                                          SelectionDAG &DAG, bool LegalTypes,
5627                                          bool LegalOperations) {
5628   unsigned Opcode = N->getOpcode();
5629   SDValue N0 = N->getOperand(0);
5630   EVT VT = N->getValueType(0);
5631
5632   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5633          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5634          && "Expected EXTEND dag node in input!");
5635
5636   // fold (sext c1) -> c1
5637   // fold (zext c1) -> c1
5638   // fold (aext c1) -> c1
5639   if (isa<ConstantSDNode>(N0))
5640     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5641
5642   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5643   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5644   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5645   EVT SVT = VT.getScalarType();
5646   if (!(VT.isVector() &&
5647       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5648       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5649     return nullptr;
5650
5651   // We can fold this node into a build_vector.
5652   unsigned VTBits = SVT.getSizeInBits();
5653   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5654   SmallVector<SDValue, 8> Elts;
5655   unsigned NumElts = VT.getVectorNumElements();
5656   SDLoc DL(N);
5657
5658   for (unsigned i=0; i != NumElts; ++i) {
5659     SDValue Op = N0->getOperand(i);
5660     if (Op->getOpcode() == ISD::UNDEF) {
5661       Elts.push_back(DAG.getUNDEF(SVT));
5662       continue;
5663     }
5664
5665     SDLoc DL(Op);
5666     // Get the constant value and if needed trunc it to the size of the type.
5667     // Nodes like build_vector might have constants wider than the scalar type.
5668     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5669     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5670       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5671     else
5672       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5673   }
5674
5675   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5676 }
5677
5678 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5679 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5680 // transformation. Returns true if extension are possible and the above
5681 // mentioned transformation is profitable.
5682 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5683                                     unsigned ExtOpc,
5684                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5685                                     const TargetLowering &TLI) {
5686   bool HasCopyToRegUses = false;
5687   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5688   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5689                             UE = N0.getNode()->use_end();
5690        UI != UE; ++UI) {
5691     SDNode *User = *UI;
5692     if (User == N)
5693       continue;
5694     if (UI.getUse().getResNo() != N0.getResNo())
5695       continue;
5696     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5697     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5698       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5699       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5700         // Sign bits will be lost after a zext.
5701         return false;
5702       bool Add = false;
5703       for (unsigned i = 0; i != 2; ++i) {
5704         SDValue UseOp = User->getOperand(i);
5705         if (UseOp == N0)
5706           continue;
5707         if (!isa<ConstantSDNode>(UseOp))
5708           return false;
5709         Add = true;
5710       }
5711       if (Add)
5712         ExtendNodes.push_back(User);
5713       continue;
5714     }
5715     // If truncates aren't free and there are users we can't
5716     // extend, it isn't worthwhile.
5717     if (!isTruncFree)
5718       return false;
5719     // Remember if this value is live-out.
5720     if (User->getOpcode() == ISD::CopyToReg)
5721       HasCopyToRegUses = true;
5722   }
5723
5724   if (HasCopyToRegUses) {
5725     bool BothLiveOut = false;
5726     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5727          UI != UE; ++UI) {
5728       SDUse &Use = UI.getUse();
5729       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5730         BothLiveOut = true;
5731         break;
5732       }
5733     }
5734     if (BothLiveOut)
5735       // Both unextended and extended values are live out. There had better be
5736       // a good reason for the transformation.
5737       return ExtendNodes.size();
5738   }
5739   return true;
5740 }
5741
5742 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5743                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5744                                   ISD::NodeType ExtType) {
5745   // Extend SetCC uses if necessary.
5746   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5747     SDNode *SetCC = SetCCs[i];
5748     SmallVector<SDValue, 4> Ops;
5749
5750     for (unsigned j = 0; j != 2; ++j) {
5751       SDValue SOp = SetCC->getOperand(j);
5752       if (SOp == Trunc)
5753         Ops.push_back(ExtLoad);
5754       else
5755         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5756     }
5757
5758     Ops.push_back(SetCC->getOperand(2));
5759     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5760   }
5761 }
5762
5763 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5764 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5765   SDValue N0 = N->getOperand(0);
5766   EVT DstVT = N->getValueType(0);
5767   EVT SrcVT = N0.getValueType();
5768
5769   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5770           N->getOpcode() == ISD::ZERO_EXTEND) &&
5771          "Unexpected node type (not an extend)!");
5772
5773   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5774   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5775   //   (v8i32 (sext (v8i16 (load x))))
5776   // into:
5777   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5778   //                          (v4i32 (sextload (x + 16)))))
5779   // Where uses of the original load, i.e.:
5780   //   (v8i16 (load x))
5781   // are replaced with:
5782   //   (v8i16 (truncate
5783   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5784   //                            (v4i32 (sextload (x + 16)))))))
5785   //
5786   // This combine is only applicable to illegal, but splittable, vectors.
5787   // All legal types, and illegal non-vector types, are handled elsewhere.
5788   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5789   //
5790   if (N0->getOpcode() != ISD::LOAD)
5791     return SDValue();
5792
5793   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5794
5795   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5796       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5797       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5798     return SDValue();
5799
5800   SmallVector<SDNode *, 4> SetCCs;
5801   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5802     return SDValue();
5803
5804   ISD::LoadExtType ExtType =
5805       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5806
5807   // Try to split the vector types to get down to legal types.
5808   EVT SplitSrcVT = SrcVT;
5809   EVT SplitDstVT = DstVT;
5810   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5811          SplitSrcVT.getVectorNumElements() > 1) {
5812     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5813     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5814   }
5815
5816   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5817     return SDValue();
5818
5819   SDLoc DL(N);
5820   const unsigned NumSplits =
5821       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5822   const unsigned Stride = SplitSrcVT.getStoreSize();
5823   SmallVector<SDValue, 4> Loads;
5824   SmallVector<SDValue, 4> Chains;
5825
5826   SDValue BasePtr = LN0->getBasePtr();
5827   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5828     const unsigned Offset = Idx * Stride;
5829     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5830
5831     SDValue SplitLoad = DAG.getExtLoad(
5832         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5833         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5834         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5835         Align, LN0->getAAInfo());
5836
5837     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5838                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5839
5840     Loads.push_back(SplitLoad.getValue(0));
5841     Chains.push_back(SplitLoad.getValue(1));
5842   }
5843
5844   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5845   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5846
5847   CombineTo(N, NewValue);
5848
5849   // Replace uses of the original load (before extension)
5850   // with a truncate of the concatenated sextloaded vectors.
5851   SDValue Trunc =
5852       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5853   CombineTo(N0.getNode(), Trunc, NewChain);
5854   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5855                   (ISD::NodeType)N->getOpcode());
5856   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5857 }
5858
5859 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5860   SDValue N0 = N->getOperand(0);
5861   EVT VT = N->getValueType(0);
5862
5863   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5864                                               LegalOperations))
5865     return SDValue(Res, 0);
5866
5867   // fold (sext (sext x)) -> (sext x)
5868   // fold (sext (aext x)) -> (sext x)
5869   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5870     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5871                        N0.getOperand(0));
5872
5873   if (N0.getOpcode() == ISD::TRUNCATE) {
5874     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5875     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5876     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5877       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5878       if (NarrowLoad.getNode() != N0.getNode()) {
5879         CombineTo(N0.getNode(), NarrowLoad);
5880         // CombineTo deleted the truncate, if needed, but not what's under it.
5881         AddToWorklist(oye);
5882       }
5883       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5884     }
5885
5886     // See if the value being truncated is already sign extended.  If so, just
5887     // eliminate the trunc/sext pair.
5888     SDValue Op = N0.getOperand(0);
5889     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5890     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5891     unsigned DestBits = VT.getScalarType().getSizeInBits();
5892     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5893
5894     if (OpBits == DestBits) {
5895       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5896       // bits, it is already ready.
5897       if (NumSignBits > DestBits-MidBits)
5898         return Op;
5899     } else if (OpBits < DestBits) {
5900       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5901       // bits, just sext from i32.
5902       if (NumSignBits > OpBits-MidBits)
5903         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5904     } else {
5905       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5906       // bits, just truncate to i32.
5907       if (NumSignBits > OpBits-MidBits)
5908         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5909     }
5910
5911     // fold (sext (truncate x)) -> (sextinreg x).
5912     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5913                                                  N0.getValueType())) {
5914       if (OpBits < DestBits)
5915         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5916       else if (OpBits > DestBits)
5917         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5918       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5919                          DAG.getValueType(N0.getValueType()));
5920     }
5921   }
5922
5923   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5924   // Only generate vector extloads when 1) they're legal, and 2) they are
5925   // deemed desirable by the target.
5926   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5927       ((!LegalOperations && !VT.isVector() &&
5928         !cast<LoadSDNode>(N0)->isVolatile()) ||
5929        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5930     bool DoXform = true;
5931     SmallVector<SDNode*, 4> SetCCs;
5932     if (!N0.hasOneUse())
5933       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5934     if (VT.isVector())
5935       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5936     if (DoXform) {
5937       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5938       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5939                                        LN0->getChain(),
5940                                        LN0->getBasePtr(), N0.getValueType(),
5941                                        LN0->getMemOperand());
5942       CombineTo(N, ExtLoad);
5943       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5944                                   N0.getValueType(), ExtLoad);
5945       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5946       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5947                       ISD::SIGN_EXTEND);
5948       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5949     }
5950   }
5951
5952   // fold (sext (load x)) to multiple smaller sextloads.
5953   // Only on illegal but splittable vectors.
5954   if (SDValue ExtLoad = CombineExtLoad(N))
5955     return ExtLoad;
5956
5957   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5958   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5959   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5960       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5961     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5962     EVT MemVT = LN0->getMemoryVT();
5963     if ((!LegalOperations && !LN0->isVolatile()) ||
5964         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5965       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5966                                        LN0->getChain(),
5967                                        LN0->getBasePtr(), MemVT,
5968                                        LN0->getMemOperand());
5969       CombineTo(N, ExtLoad);
5970       CombineTo(N0.getNode(),
5971                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5972                             N0.getValueType(), ExtLoad),
5973                 ExtLoad.getValue(1));
5974       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5975     }
5976   }
5977
5978   // fold (sext (and/or/xor (load x), cst)) ->
5979   //      (and/or/xor (sextload x), (sext cst))
5980   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5981        N0.getOpcode() == ISD::XOR) &&
5982       isa<LoadSDNode>(N0.getOperand(0)) &&
5983       N0.getOperand(1).getOpcode() == ISD::Constant &&
5984       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5985       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5986     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5987     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5988       bool DoXform = true;
5989       SmallVector<SDNode*, 4> SetCCs;
5990       if (!N0.hasOneUse())
5991         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5992                                           SetCCs, TLI);
5993       if (DoXform) {
5994         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5995                                          LN0->getChain(), LN0->getBasePtr(),
5996                                          LN0->getMemoryVT(),
5997                                          LN0->getMemOperand());
5998         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5999         Mask = Mask.sext(VT.getSizeInBits());
6000         SDLoc DL(N);
6001         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6002                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6003         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6004                                     SDLoc(N0.getOperand(0)),
6005                                     N0.getOperand(0).getValueType(), ExtLoad);
6006         CombineTo(N, And);
6007         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6008         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6009                         ISD::SIGN_EXTEND);
6010         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6011       }
6012     }
6013   }
6014
6015   if (N0.getOpcode() == ISD::SETCC) {
6016     EVT N0VT = N0.getOperand(0).getValueType();
6017     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6018     // Only do this before legalize for now.
6019     if (VT.isVector() && !LegalOperations &&
6020         TLI.getBooleanContents(N0VT) ==
6021             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6022       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6023       // of the same size as the compared operands. Only optimize sext(setcc())
6024       // if this is the case.
6025       EVT SVT = getSetCCResultType(N0VT);
6026
6027       // We know that the # elements of the results is the same as the
6028       // # elements of the compare (and the # elements of the compare result
6029       // for that matter).  Check to see that they are the same size.  If so,
6030       // we know that the element size of the sext'd result matches the
6031       // element size of the compare operands.
6032       if (VT.getSizeInBits() == SVT.getSizeInBits())
6033         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6034                              N0.getOperand(1),
6035                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6036
6037       // If the desired elements are smaller or larger than the source
6038       // elements we can use a matching integer vector type and then
6039       // truncate/sign extend
6040       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6041       if (SVT == MatchingVectorType) {
6042         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6043                                N0.getOperand(0), N0.getOperand(1),
6044                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6045         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6046       }
6047     }
6048
6049     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6050     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6051     SDLoc DL(N);
6052     SDValue NegOne =
6053       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6054     SDValue SCC =
6055       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6056                        NegOne, DAG.getConstant(0, DL, VT),
6057                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6058     if (SCC.getNode()) return SCC;
6059
6060     if (!VT.isVector()) {
6061       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6062       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6063         SDLoc DL(N);
6064         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6065         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6066                                      N0.getOperand(0), N0.getOperand(1), CC);
6067         return DAG.getSelect(DL, VT, SetCC,
6068                              NegOne, DAG.getConstant(0, DL, VT));
6069       }
6070     }
6071   }
6072
6073   // fold (sext x) -> (zext x) if the sign bit is known zero.
6074   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6075       DAG.SignBitIsZero(N0))
6076     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6077
6078   return SDValue();
6079 }
6080
6081 // isTruncateOf - If N is a truncate of some other value, return true, record
6082 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6083 // This function computes KnownZero to avoid a duplicated call to
6084 // computeKnownBits in the caller.
6085 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6086                          APInt &KnownZero) {
6087   APInt KnownOne;
6088   if (N->getOpcode() == ISD::TRUNCATE) {
6089     Op = N->getOperand(0);
6090     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6091     return true;
6092   }
6093
6094   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6095       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6096     return false;
6097
6098   SDValue Op0 = N->getOperand(0);
6099   SDValue Op1 = N->getOperand(1);
6100   assert(Op0.getValueType() == Op1.getValueType());
6101
6102   if (isNullConstant(Op0))
6103     Op = Op1;
6104   else if (isNullConstant(Op1))
6105     Op = Op0;
6106   else
6107     return false;
6108
6109   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6110
6111   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6112     return false;
6113
6114   return true;
6115 }
6116
6117 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6118   SDValue N0 = N->getOperand(0);
6119   EVT VT = N->getValueType(0);
6120
6121   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6122                                               LegalOperations))
6123     return SDValue(Res, 0);
6124
6125   // fold (zext (zext x)) -> (zext x)
6126   // fold (zext (aext x)) -> (zext x)
6127   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6128     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6129                        N0.getOperand(0));
6130
6131   // fold (zext (truncate x)) -> (zext x) or
6132   //      (zext (truncate x)) -> (truncate x)
6133   // This is valid when the truncated bits of x are already zero.
6134   // FIXME: We should extend this to work for vectors too.
6135   SDValue Op;
6136   APInt KnownZero;
6137   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6138     APInt TruncatedBits =
6139       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6140       APInt(Op.getValueSizeInBits(), 0) :
6141       APInt::getBitsSet(Op.getValueSizeInBits(),
6142                         N0.getValueSizeInBits(),
6143                         std::min(Op.getValueSizeInBits(),
6144                                  VT.getSizeInBits()));
6145     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6146       if (VT.bitsGT(Op.getValueType()))
6147         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6148       if (VT.bitsLT(Op.getValueType()))
6149         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6150
6151       return Op;
6152     }
6153   }
6154
6155   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6156   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6157   if (N0.getOpcode() == ISD::TRUNCATE) {
6158     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6159       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6160       if (NarrowLoad.getNode() != N0.getNode()) {
6161         CombineTo(N0.getNode(), NarrowLoad);
6162         // CombineTo deleted the truncate, if needed, but not what's under it.
6163         AddToWorklist(oye);
6164       }
6165       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6166     }
6167   }
6168
6169   // fold (zext (truncate x)) -> (and x, mask)
6170   if (N0.getOpcode() == ISD::TRUNCATE) {
6171     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6172     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6173     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6174       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6175       if (NarrowLoad.getNode() != N0.getNode()) {
6176         CombineTo(N0.getNode(), NarrowLoad);
6177         // CombineTo deleted the truncate, if needed, but not what's under it.
6178         AddToWorklist(oye);
6179       }
6180       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6181     }
6182
6183     EVT SrcVT = N0.getOperand(0).getValueType();
6184     EVT MinVT = N0.getValueType();
6185
6186     // Try to mask before the extension to avoid having to generate a larger mask,
6187     // possibly over several sub-vectors.
6188     if (SrcVT.bitsLT(VT)) {
6189       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6190                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6191         SDValue Op = N0.getOperand(0);
6192         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6193         AddToWorklist(Op.getNode());
6194         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6195       }
6196     }
6197
6198     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6199       SDValue Op = N0.getOperand(0);
6200       if (SrcVT.bitsLT(VT)) {
6201         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6202         AddToWorklist(Op.getNode());
6203       } else if (SrcVT.bitsGT(VT)) {
6204         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6205         AddToWorklist(Op.getNode());
6206       }
6207       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6208     }
6209   }
6210
6211   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6212   // if either of the casts is not free.
6213   if (N0.getOpcode() == ISD::AND &&
6214       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6215       N0.getOperand(1).getOpcode() == ISD::Constant &&
6216       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6217                            N0.getValueType()) ||
6218        !TLI.isZExtFree(N0.getValueType(), VT))) {
6219     SDValue X = N0.getOperand(0).getOperand(0);
6220     if (X.getValueType().bitsLT(VT)) {
6221       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6222     } else if (X.getValueType().bitsGT(VT)) {
6223       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6224     }
6225     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6226     Mask = Mask.zext(VT.getSizeInBits());
6227     SDLoc DL(N);
6228     return DAG.getNode(ISD::AND, DL, VT,
6229                        X, DAG.getConstant(Mask, DL, VT));
6230   }
6231
6232   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6233   // Only generate vector extloads when 1) they're legal, and 2) they are
6234   // deemed desirable by the target.
6235   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6236       ((!LegalOperations && !VT.isVector() &&
6237         !cast<LoadSDNode>(N0)->isVolatile()) ||
6238        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6239     bool DoXform = true;
6240     SmallVector<SDNode*, 4> SetCCs;
6241     if (!N0.hasOneUse())
6242       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6243     if (VT.isVector())
6244       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6245     if (DoXform) {
6246       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6247       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6248                                        LN0->getChain(),
6249                                        LN0->getBasePtr(), N0.getValueType(),
6250                                        LN0->getMemOperand());
6251       CombineTo(N, ExtLoad);
6252       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6253                                   N0.getValueType(), ExtLoad);
6254       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6255
6256       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6257                       ISD::ZERO_EXTEND);
6258       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6259     }
6260   }
6261
6262   // fold (zext (load x)) to multiple smaller zextloads.
6263   // Only on illegal but splittable vectors.
6264   if (SDValue ExtLoad = CombineExtLoad(N))
6265     return ExtLoad;
6266
6267   // fold (zext (and/or/xor (load x), cst)) ->
6268   //      (and/or/xor (zextload x), (zext cst))
6269   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6270        N0.getOpcode() == ISD::XOR) &&
6271       isa<LoadSDNode>(N0.getOperand(0)) &&
6272       N0.getOperand(1).getOpcode() == ISD::Constant &&
6273       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6274       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6275     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6276     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6277       bool DoXform = true;
6278       SmallVector<SDNode*, 4> SetCCs;
6279       if (!N0.hasOneUse())
6280         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6281                                           SetCCs, TLI);
6282       if (DoXform) {
6283         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6284                                          LN0->getChain(), LN0->getBasePtr(),
6285                                          LN0->getMemoryVT(),
6286                                          LN0->getMemOperand());
6287         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6288         Mask = Mask.zext(VT.getSizeInBits());
6289         SDLoc DL(N);
6290         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6291                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6292         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6293                                     SDLoc(N0.getOperand(0)),
6294                                     N0.getOperand(0).getValueType(), ExtLoad);
6295         CombineTo(N, And);
6296         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6297         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6298                         ISD::ZERO_EXTEND);
6299         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6300       }
6301     }
6302   }
6303
6304   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6305   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6306   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6307       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6308     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6309     EVT MemVT = LN0->getMemoryVT();
6310     if ((!LegalOperations && !LN0->isVolatile()) ||
6311         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6312       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6313                                        LN0->getChain(),
6314                                        LN0->getBasePtr(), MemVT,
6315                                        LN0->getMemOperand());
6316       CombineTo(N, ExtLoad);
6317       CombineTo(N0.getNode(),
6318                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6319                             ExtLoad),
6320                 ExtLoad.getValue(1));
6321       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6322     }
6323   }
6324
6325   if (N0.getOpcode() == ISD::SETCC) {
6326     if (!LegalOperations && VT.isVector() &&
6327         N0.getValueType().getVectorElementType() == MVT::i1) {
6328       EVT N0VT = N0.getOperand(0).getValueType();
6329       if (getSetCCResultType(N0VT) == N0.getValueType())
6330         return SDValue();
6331
6332       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6333       // Only do this before legalize for now.
6334       EVT EltVT = VT.getVectorElementType();
6335       SDLoc DL(N);
6336       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6337                                     DAG.getConstant(1, DL, EltVT));
6338       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6339         // We know that the # elements of the results is the same as the
6340         // # elements of the compare (and the # elements of the compare result
6341         // for that matter).  Check to see that they are the same size.  If so,
6342         // we know that the element size of the sext'd result matches the
6343         // element size of the compare operands.
6344         return DAG.getNode(ISD::AND, DL, VT,
6345                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6346                                          N0.getOperand(1),
6347                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6348                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6349                                        OneOps));
6350
6351       // If the desired elements are smaller or larger than the source
6352       // elements we can use a matching integer vector type and then
6353       // truncate/sign extend
6354       EVT MatchingElementType =
6355         EVT::getIntegerVT(*DAG.getContext(),
6356                           N0VT.getScalarType().getSizeInBits());
6357       EVT MatchingVectorType =
6358         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6359                          N0VT.getVectorNumElements());
6360       SDValue VsetCC =
6361         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6362                       N0.getOperand(1),
6363                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6364       return DAG.getNode(ISD::AND, DL, VT,
6365                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6366                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6367     }
6368
6369     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6370     SDLoc DL(N);
6371     SDValue SCC =
6372       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6373                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6374                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6375     if (SCC.getNode()) return SCC;
6376   }
6377
6378   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6379   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6380       isa<ConstantSDNode>(N0.getOperand(1)) &&
6381       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6382       N0.hasOneUse()) {
6383     SDValue ShAmt = N0.getOperand(1);
6384     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6385     if (N0.getOpcode() == ISD::SHL) {
6386       SDValue InnerZExt = N0.getOperand(0);
6387       // If the original shl may be shifting out bits, do not perform this
6388       // transformation.
6389       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6390         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6391       if (ShAmtVal > KnownZeroBits)
6392         return SDValue();
6393     }
6394
6395     SDLoc DL(N);
6396
6397     // Ensure that the shift amount is wide enough for the shifted value.
6398     if (VT.getSizeInBits() >= 256)
6399       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6400
6401     return DAG.getNode(N0.getOpcode(), DL, VT,
6402                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6403                        ShAmt);
6404   }
6405
6406   return SDValue();
6407 }
6408
6409 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6410   SDValue N0 = N->getOperand(0);
6411   EVT VT = N->getValueType(0);
6412
6413   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6414                                               LegalOperations))
6415     return SDValue(Res, 0);
6416
6417   // fold (aext (aext x)) -> (aext x)
6418   // fold (aext (zext x)) -> (zext x)
6419   // fold (aext (sext x)) -> (sext x)
6420   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6421       N0.getOpcode() == ISD::ZERO_EXTEND ||
6422       N0.getOpcode() == ISD::SIGN_EXTEND)
6423     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6424
6425   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6426   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6427   if (N0.getOpcode() == ISD::TRUNCATE) {
6428     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6429       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6430       if (NarrowLoad.getNode() != N0.getNode()) {
6431         CombineTo(N0.getNode(), NarrowLoad);
6432         // CombineTo deleted the truncate, if needed, but not what's under it.
6433         AddToWorklist(oye);
6434       }
6435       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6436     }
6437   }
6438
6439   // fold (aext (truncate x))
6440   if (N0.getOpcode() == ISD::TRUNCATE) {
6441     SDValue TruncOp = N0.getOperand(0);
6442     if (TruncOp.getValueType() == VT)
6443       return TruncOp; // x iff x size == zext size.
6444     if (TruncOp.getValueType().bitsGT(VT))
6445       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6446     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6447   }
6448
6449   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6450   // if the trunc is not free.
6451   if (N0.getOpcode() == ISD::AND &&
6452       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6453       N0.getOperand(1).getOpcode() == ISD::Constant &&
6454       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6455                           N0.getValueType())) {
6456     SDValue X = N0.getOperand(0).getOperand(0);
6457     if (X.getValueType().bitsLT(VT)) {
6458       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6459     } else if (X.getValueType().bitsGT(VT)) {
6460       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6461     }
6462     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6463     Mask = Mask.zext(VT.getSizeInBits());
6464     SDLoc DL(N);
6465     return DAG.getNode(ISD::AND, DL, VT,
6466                        X, DAG.getConstant(Mask, DL, VT));
6467   }
6468
6469   // fold (aext (load x)) -> (aext (truncate (extload x)))
6470   // None of the supported targets knows how to perform load and any_ext
6471   // on vectors in one instruction.  We only perform this transformation on
6472   // scalars.
6473   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6474       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6475       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6476     bool DoXform = true;
6477     SmallVector<SDNode*, 4> SetCCs;
6478     if (!N0.hasOneUse())
6479       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6480     if (DoXform) {
6481       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6482       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6483                                        LN0->getChain(),
6484                                        LN0->getBasePtr(), N0.getValueType(),
6485                                        LN0->getMemOperand());
6486       CombineTo(N, ExtLoad);
6487       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6488                                   N0.getValueType(), ExtLoad);
6489       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6490       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6491                       ISD::ANY_EXTEND);
6492       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6493     }
6494   }
6495
6496   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6497   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6498   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6499   if (N0.getOpcode() == ISD::LOAD &&
6500       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6501       N0.hasOneUse()) {
6502     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6503     ISD::LoadExtType ExtType = LN0->getExtensionType();
6504     EVT MemVT = LN0->getMemoryVT();
6505     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6506       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6507                                        VT, LN0->getChain(), LN0->getBasePtr(),
6508                                        MemVT, LN0->getMemOperand());
6509       CombineTo(N, ExtLoad);
6510       CombineTo(N0.getNode(),
6511                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6512                             N0.getValueType(), ExtLoad),
6513                 ExtLoad.getValue(1));
6514       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6515     }
6516   }
6517
6518   if (N0.getOpcode() == ISD::SETCC) {
6519     // For vectors:
6520     // aext(setcc) -> vsetcc
6521     // aext(setcc) -> truncate(vsetcc)
6522     // aext(setcc) -> aext(vsetcc)
6523     // Only do this before legalize for now.
6524     if (VT.isVector() && !LegalOperations) {
6525       EVT N0VT = N0.getOperand(0).getValueType();
6526         // We know that the # elements of the results is the same as the
6527         // # elements of the compare (and the # elements of the compare result
6528         // for that matter).  Check to see that they are the same size.  If so,
6529         // we know that the element size of the sext'd result matches the
6530         // element size of the compare operands.
6531       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6532         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6533                              N0.getOperand(1),
6534                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6535       // If the desired elements are smaller or larger than the source
6536       // elements we can use a matching integer vector type and then
6537       // truncate/any extend
6538       else {
6539         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6540         SDValue VsetCC =
6541           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6542                         N0.getOperand(1),
6543                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6544         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6545       }
6546     }
6547
6548     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6549     SDLoc DL(N);
6550     SDValue SCC =
6551       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6552                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6553                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6554     if (SCC.getNode())
6555       return SCC;
6556   }
6557
6558   return SDValue();
6559 }
6560
6561 /// See if the specified operand can be simplified with the knowledge that only
6562 /// the bits specified by Mask are used.  If so, return the simpler operand,
6563 /// otherwise return a null SDValue.
6564 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6565   switch (V.getOpcode()) {
6566   default: break;
6567   case ISD::Constant: {
6568     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6569     assert(CV && "Const value should be ConstSDNode.");
6570     const APInt &CVal = CV->getAPIntValue();
6571     APInt NewVal = CVal & Mask;
6572     if (NewVal != CVal)
6573       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6574     break;
6575   }
6576   case ISD::OR:
6577   case ISD::XOR:
6578     // If the LHS or RHS don't contribute bits to the or, drop them.
6579     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6580       return V.getOperand(1);
6581     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6582       return V.getOperand(0);
6583     break;
6584   case ISD::SRL:
6585     // Only look at single-use SRLs.
6586     if (!V.getNode()->hasOneUse())
6587       break;
6588     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6589       // See if we can recursively simplify the LHS.
6590       unsigned Amt = RHSC->getZExtValue();
6591
6592       // Watch out for shift count overflow though.
6593       if (Amt >= Mask.getBitWidth()) break;
6594       APInt NewMask = Mask << Amt;
6595       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6596         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6597                            SimplifyLHS, V.getOperand(1));
6598     }
6599   }
6600   return SDValue();
6601 }
6602
6603 /// If the result of a wider load is shifted to right of N  bits and then
6604 /// truncated to a narrower type and where N is a multiple of number of bits of
6605 /// the narrower type, transform it to a narrower load from address + N / num of
6606 /// bits of new type. If the result is to be extended, also fold the extension
6607 /// to form a extending load.
6608 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6609   unsigned Opc = N->getOpcode();
6610
6611   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6612   SDValue N0 = N->getOperand(0);
6613   EVT VT = N->getValueType(0);
6614   EVT ExtVT = VT;
6615
6616   // This transformation isn't valid for vector loads.
6617   if (VT.isVector())
6618     return SDValue();
6619
6620   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6621   // extended to VT.
6622   if (Opc == ISD::SIGN_EXTEND_INREG) {
6623     ExtType = ISD::SEXTLOAD;
6624     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6625   } else if (Opc == ISD::SRL) {
6626     // Another special-case: SRL is basically zero-extending a narrower value.
6627     ExtType = ISD::ZEXTLOAD;
6628     N0 = SDValue(N, 0);
6629     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6630     if (!N01) return SDValue();
6631     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6632                               VT.getSizeInBits() - N01->getZExtValue());
6633   }
6634   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6635     return SDValue();
6636
6637   unsigned EVTBits = ExtVT.getSizeInBits();
6638
6639   // Do not generate loads of non-round integer types since these can
6640   // be expensive (and would be wrong if the type is not byte sized).
6641   if (!ExtVT.isRound())
6642     return SDValue();
6643
6644   unsigned ShAmt = 0;
6645   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6646     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6647       ShAmt = N01->getZExtValue();
6648       // Is the shift amount a multiple of size of VT?
6649       if ((ShAmt & (EVTBits-1)) == 0) {
6650         N0 = N0.getOperand(0);
6651         // Is the load width a multiple of size of VT?
6652         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6653           return SDValue();
6654       }
6655
6656       // At this point, we must have a load or else we can't do the transform.
6657       if (!isa<LoadSDNode>(N0)) return SDValue();
6658
6659       // Because a SRL must be assumed to *need* to zero-extend the high bits
6660       // (as opposed to anyext the high bits), we can't combine the zextload
6661       // lowering of SRL and an sextload.
6662       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6663         return SDValue();
6664
6665       // If the shift amount is larger than the input type then we're not
6666       // accessing any of the loaded bytes.  If the load was a zextload/extload
6667       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6668       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6669         return SDValue();
6670     }
6671   }
6672
6673   // If the load is shifted left (and the result isn't shifted back right),
6674   // we can fold the truncate through the shift.
6675   unsigned ShLeftAmt = 0;
6676   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6677       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6678     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6679       ShLeftAmt = N01->getZExtValue();
6680       N0 = N0.getOperand(0);
6681     }
6682   }
6683
6684   // If we haven't found a load, we can't narrow it.  Don't transform one with
6685   // multiple uses, this would require adding a new load.
6686   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6687     return SDValue();
6688
6689   // Don't change the width of a volatile load.
6690   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6691   if (LN0->isVolatile())
6692     return SDValue();
6693
6694   // Verify that we are actually reducing a load width here.
6695   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6696     return SDValue();
6697
6698   // For the transform to be legal, the load must produce only two values
6699   // (the value loaded and the chain).  Don't transform a pre-increment
6700   // load, for example, which produces an extra value.  Otherwise the
6701   // transformation is not equivalent, and the downstream logic to replace
6702   // uses gets things wrong.
6703   if (LN0->getNumValues() > 2)
6704     return SDValue();
6705
6706   // If the load that we're shrinking is an extload and we're not just
6707   // discarding the extension we can't simply shrink the load. Bail.
6708   // TODO: It would be possible to merge the extensions in some cases.
6709   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6710       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6711     return SDValue();
6712
6713   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6714     return SDValue();
6715
6716   EVT PtrType = N0.getOperand(1).getValueType();
6717
6718   if (PtrType == MVT::Untyped || PtrType.isExtended())
6719     // It's not possible to generate a constant of extended or untyped type.
6720     return SDValue();
6721
6722   // For big endian targets, we need to adjust the offset to the pointer to
6723   // load the correct bytes.
6724   if (DAG.getDataLayout().isBigEndian()) {
6725     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6726     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6727     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6728   }
6729
6730   uint64_t PtrOff = ShAmt / 8;
6731   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6732   SDLoc DL(LN0);
6733   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6734                                PtrType, LN0->getBasePtr(),
6735                                DAG.getConstant(PtrOff, DL, PtrType));
6736   AddToWorklist(NewPtr.getNode());
6737
6738   SDValue Load;
6739   if (ExtType == ISD::NON_EXTLOAD)
6740     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6741                         LN0->getPointerInfo().getWithOffset(PtrOff),
6742                         LN0->isVolatile(), LN0->isNonTemporal(),
6743                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6744   else
6745     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6746                           LN0->getPointerInfo().getWithOffset(PtrOff),
6747                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6748                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6749
6750   // Replace the old load's chain with the new load's chain.
6751   WorklistRemover DeadNodes(*this);
6752   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6753
6754   // Shift the result left, if we've swallowed a left shift.
6755   SDValue Result = Load;
6756   if (ShLeftAmt != 0) {
6757     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6758     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6759       ShImmTy = VT;
6760     // If the shift amount is as large as the result size (but, presumably,
6761     // no larger than the source) then the useful bits of the result are
6762     // zero; we can't simply return the shortened shift, because the result
6763     // of that operation is undefined.
6764     SDLoc DL(N0);
6765     if (ShLeftAmt >= VT.getSizeInBits())
6766       Result = DAG.getConstant(0, DL, VT);
6767     else
6768       Result = DAG.getNode(ISD::SHL, DL, VT,
6769                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6770   }
6771
6772   // Return the new loaded value.
6773   return Result;
6774 }
6775
6776 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6777   SDValue N0 = N->getOperand(0);
6778   SDValue N1 = N->getOperand(1);
6779   EVT VT = N->getValueType(0);
6780   EVT EVT = cast<VTSDNode>(N1)->getVT();
6781   unsigned VTBits = VT.getScalarType().getSizeInBits();
6782   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6783
6784   // fold (sext_in_reg c1) -> c1
6785   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6786     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6787
6788   // If the input is already sign extended, just drop the extension.
6789   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6790     return N0;
6791
6792   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6793   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6794       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6795     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6796                        N0.getOperand(0), N1);
6797
6798   // fold (sext_in_reg (sext x)) -> (sext x)
6799   // fold (sext_in_reg (aext x)) -> (sext x)
6800   // if x is small enough.
6801   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6802     SDValue N00 = N0.getOperand(0);
6803     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6804         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6805       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6806   }
6807
6808   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6809   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6810     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6811
6812   // fold operands of sext_in_reg based on knowledge that the top bits are not
6813   // demanded.
6814   if (SimplifyDemandedBits(SDValue(N, 0)))
6815     return SDValue(N, 0);
6816
6817   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6818   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6819   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6820     return NarrowLoad;
6821
6822   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6823   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6824   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6825   if (N0.getOpcode() == ISD::SRL) {
6826     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6827       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6828         // We can turn this into an SRA iff the input to the SRL is already sign
6829         // extended enough.
6830         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6831         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6832           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6833                              N0.getOperand(0), N0.getOperand(1));
6834       }
6835   }
6836
6837   // fold (sext_inreg (extload x)) -> (sextload x)
6838   if (ISD::isEXTLoad(N0.getNode()) &&
6839       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6840       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6841       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6842        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6843     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6844     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6845                                      LN0->getChain(),
6846                                      LN0->getBasePtr(), EVT,
6847                                      LN0->getMemOperand());
6848     CombineTo(N, ExtLoad);
6849     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6850     AddToWorklist(ExtLoad.getNode());
6851     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6852   }
6853   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6854   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6855       N0.hasOneUse() &&
6856       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6857       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6858        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6859     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6860     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6861                                      LN0->getChain(),
6862                                      LN0->getBasePtr(), EVT,
6863                                      LN0->getMemOperand());
6864     CombineTo(N, ExtLoad);
6865     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6866     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6867   }
6868
6869   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6870   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6871     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6872                                        N0.getOperand(1), false);
6873     if (BSwap.getNode())
6874       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6875                          BSwap, N1);
6876   }
6877
6878   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6879   // into a build_vector.
6880   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6881     SmallVector<SDValue, 8> Elts;
6882     unsigned NumElts = N0->getNumOperands();
6883     unsigned ShAmt = VTBits - EVTBits;
6884
6885     for (unsigned i = 0; i != NumElts; ++i) {
6886       SDValue Op = N0->getOperand(i);
6887       if (Op->getOpcode() == ISD::UNDEF) {
6888         Elts.push_back(Op);
6889         continue;
6890       }
6891
6892       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6893       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6894       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6895                                      SDLoc(Op), Op.getValueType()));
6896     }
6897
6898     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6899   }
6900
6901   return SDValue();
6902 }
6903
6904 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6905   SDValue N0 = N->getOperand(0);
6906   EVT VT = N->getValueType(0);
6907
6908   if (N0.getOpcode() == ISD::UNDEF)
6909     return DAG.getUNDEF(VT);
6910
6911   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6912                                               LegalOperations))
6913     return SDValue(Res, 0);
6914
6915   return SDValue();
6916 }
6917
6918 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6919   SDValue N0 = N->getOperand(0);
6920   EVT VT = N->getValueType(0);
6921   bool isLE = DAG.getDataLayout().isLittleEndian();
6922
6923   // noop truncate
6924   if (N0.getValueType() == N->getValueType(0))
6925     return N0;
6926   // fold (truncate c1) -> c1
6927   if (isConstantIntBuildVectorOrConstantInt(N0))
6928     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6929   // fold (truncate (truncate x)) -> (truncate x)
6930   if (N0.getOpcode() == ISD::TRUNCATE)
6931     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6932   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6933   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6934       N0.getOpcode() == ISD::SIGN_EXTEND ||
6935       N0.getOpcode() == ISD::ANY_EXTEND) {
6936     if (N0.getOperand(0).getValueType().bitsLT(VT))
6937       // if the source is smaller than the dest, we still need an extend
6938       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6939                          N0.getOperand(0));
6940     if (N0.getOperand(0).getValueType().bitsGT(VT))
6941       // if the source is larger than the dest, than we just need the truncate
6942       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6943     // if the source and dest are the same type, we can drop both the extend
6944     // and the truncate.
6945     return N0.getOperand(0);
6946   }
6947
6948   // Fold extract-and-trunc into a narrow extract. For example:
6949   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6950   //   i32 y = TRUNCATE(i64 x)
6951   //        -- becomes --
6952   //   v16i8 b = BITCAST (v2i64 val)
6953   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6954   //
6955   // Note: We only run this optimization after type legalization (which often
6956   // creates this pattern) and before operation legalization after which
6957   // we need to be more careful about the vector instructions that we generate.
6958   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6959       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6960
6961     EVT VecTy = N0.getOperand(0).getValueType();
6962     EVT ExTy = N0.getValueType();
6963     EVT TrTy = N->getValueType(0);
6964
6965     unsigned NumElem = VecTy.getVectorNumElements();
6966     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6967
6968     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6969     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6970
6971     SDValue EltNo = N0->getOperand(1);
6972     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6973       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6974       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6975       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6976
6977       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6978                               NVT, N0.getOperand(0));
6979
6980       SDLoc DL(N);
6981       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6982                          DL, TrTy, V,
6983                          DAG.getConstant(Index, DL, IndexTy));
6984     }
6985   }
6986
6987   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6988   if (N0.getOpcode() == ISD::SELECT) {
6989     EVT SrcVT = N0.getValueType();
6990     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6991         TLI.isTruncateFree(SrcVT, VT)) {
6992       SDLoc SL(N0);
6993       SDValue Cond = N0.getOperand(0);
6994       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6995       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6996       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6997     }
6998   }
6999
7000   // Fold a series of buildvector, bitcast, and truncate if possible.
7001   // For example fold
7002   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7003   //   (2xi32 (buildvector x, y)).
7004   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7005       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7006       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7007       N0.getOperand(0).hasOneUse()) {
7008
7009     SDValue BuildVect = N0.getOperand(0);
7010     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7011     EVT TruncVecEltTy = VT.getVectorElementType();
7012
7013     // Check that the element types match.
7014     if (BuildVectEltTy == TruncVecEltTy) {
7015       // Now we only need to compute the offset of the truncated elements.
7016       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7017       unsigned TruncVecNumElts = VT.getVectorNumElements();
7018       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7019
7020       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7021              "Invalid number of elements");
7022
7023       SmallVector<SDValue, 8> Opnds;
7024       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7025         Opnds.push_back(BuildVect.getOperand(i));
7026
7027       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7028     }
7029   }
7030
7031   // See if we can simplify the input to this truncate through knowledge that
7032   // only the low bits are being used.
7033   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7034   // Currently we only perform this optimization on scalars because vectors
7035   // may have different active low bits.
7036   if (!VT.isVector()) {
7037     SDValue Shorter =
7038       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7039                                                VT.getSizeInBits()));
7040     if (Shorter.getNode())
7041       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7042   }
7043   // fold (truncate (load x)) -> (smaller load x)
7044   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7045   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7046     if (SDValue Reduced = ReduceLoadWidth(N))
7047       return Reduced;
7048
7049     // Handle the case where the load remains an extending load even
7050     // after truncation.
7051     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7052       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7053       if (!LN0->isVolatile() &&
7054           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7055         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7056                                          VT, LN0->getChain(), LN0->getBasePtr(),
7057                                          LN0->getMemoryVT(),
7058                                          LN0->getMemOperand());
7059         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7060         return NewLoad;
7061       }
7062     }
7063   }
7064   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7065   // where ... are all 'undef'.
7066   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7067     SmallVector<EVT, 8> VTs;
7068     SDValue V;
7069     unsigned Idx = 0;
7070     unsigned NumDefs = 0;
7071
7072     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7073       SDValue X = N0.getOperand(i);
7074       if (X.getOpcode() != ISD::UNDEF) {
7075         V = X;
7076         Idx = i;
7077         NumDefs++;
7078       }
7079       // Stop if more than one members are non-undef.
7080       if (NumDefs > 1)
7081         break;
7082       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7083                                      VT.getVectorElementType(),
7084                                      X.getValueType().getVectorNumElements()));
7085     }
7086
7087     if (NumDefs == 0)
7088       return DAG.getUNDEF(VT);
7089
7090     if (NumDefs == 1) {
7091       assert(V.getNode() && "The single defined operand is empty!");
7092       SmallVector<SDValue, 8> Opnds;
7093       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7094         if (i != Idx) {
7095           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7096           continue;
7097         }
7098         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7099         AddToWorklist(NV.getNode());
7100         Opnds.push_back(NV);
7101       }
7102       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7103     }
7104   }
7105
7106   // Simplify the operands using demanded-bits information.
7107   if (!VT.isVector() &&
7108       SimplifyDemandedBits(SDValue(N, 0)))
7109     return SDValue(N, 0);
7110
7111   return SDValue();
7112 }
7113
7114 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7115   SDValue Elt = N->getOperand(i);
7116   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7117     return Elt.getNode();
7118   return Elt.getOperand(Elt.getResNo()).getNode();
7119 }
7120
7121 /// build_pair (load, load) -> load
7122 /// if load locations are consecutive.
7123 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7124   assert(N->getOpcode() == ISD::BUILD_PAIR);
7125
7126   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7127   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7128   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7129       LD1->getAddressSpace() != LD2->getAddressSpace())
7130     return SDValue();
7131   EVT LD1VT = LD1->getValueType(0);
7132
7133   if (ISD::isNON_EXTLoad(LD2) &&
7134       LD2->hasOneUse() &&
7135       // If both are volatile this would reduce the number of volatile loads.
7136       // If one is volatile it might be ok, but play conservative and bail out.
7137       !LD1->isVolatile() &&
7138       !LD2->isVolatile() &&
7139       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7140     unsigned Align = LD1->getAlignment();
7141     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7142         VT.getTypeForEVT(*DAG.getContext()));
7143
7144     if (NewAlign <= Align &&
7145         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7146       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7147                          LD1->getBasePtr(), LD1->getPointerInfo(),
7148                          false, false, false, Align);
7149   }
7150
7151   return SDValue();
7152 }
7153
7154 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7155   SDValue N0 = N->getOperand(0);
7156   EVT VT = N->getValueType(0);
7157
7158   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7159   // Only do this before legalize, since afterward the target may be depending
7160   // on the bitconvert.
7161   // First check to see if this is all constant.
7162   if (!LegalTypes &&
7163       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7164       VT.isVector()) {
7165     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7166
7167     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7168     assert(!DestEltVT.isVector() &&
7169            "Element type of vector ValueType must not be vector!");
7170     if (isSimple)
7171       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7172   }
7173
7174   // If the input is a constant, let getNode fold it.
7175   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7176     // If we can't allow illegal operations, we need to check that this is just
7177     // a fp -> int or int -> conversion and that the resulting operation will
7178     // be legal.
7179     if (!LegalOperations ||
7180         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7181          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7182         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7183          TLI.isOperationLegal(ISD::Constant, VT)))
7184       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7185   }
7186
7187   // (conv (conv x, t1), t2) -> (conv x, t2)
7188   if (N0.getOpcode() == ISD::BITCAST)
7189     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7190                        N0.getOperand(0));
7191
7192   // fold (conv (load x)) -> (load (conv*)x)
7193   // If the resultant load doesn't need a higher alignment than the original!
7194   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7195       // Do not change the width of a volatile load.
7196       !cast<LoadSDNode>(N0)->isVolatile() &&
7197       // Do not remove the cast if the types differ in endian layout.
7198       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7199           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7200       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7201       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7202     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7203     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7204         VT.getTypeForEVT(*DAG.getContext()));
7205     unsigned OrigAlign = LN0->getAlignment();
7206
7207     if (Align <= OrigAlign) {
7208       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7209                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7210                                  LN0->isVolatile(), LN0->isNonTemporal(),
7211                                  LN0->isInvariant(), OrigAlign,
7212                                  LN0->getAAInfo());
7213       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7214       return Load;
7215     }
7216   }
7217
7218   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7219   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7220   // This often reduces constant pool loads.
7221   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7222        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7223       N0.getNode()->hasOneUse() && VT.isInteger() &&
7224       !VT.isVector() && !N0.getValueType().isVector()) {
7225     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7226                                   N0.getOperand(0));
7227     AddToWorklist(NewConv.getNode());
7228
7229     SDLoc DL(N);
7230     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7231     if (N0.getOpcode() == ISD::FNEG)
7232       return DAG.getNode(ISD::XOR, DL, VT,
7233                          NewConv, DAG.getConstant(SignBit, DL, VT));
7234     assert(N0.getOpcode() == ISD::FABS);
7235     return DAG.getNode(ISD::AND, DL, VT,
7236                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7237   }
7238
7239   // fold (bitconvert (fcopysign cst, x)) ->
7240   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7241   // Note that we don't handle (copysign x, cst) because this can always be
7242   // folded to an fneg or fabs.
7243   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7244       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7245       VT.isInteger() && !VT.isVector()) {
7246     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7247     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7248     if (isTypeLegal(IntXVT)) {
7249       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7250                               IntXVT, N0.getOperand(1));
7251       AddToWorklist(X.getNode());
7252
7253       // If X has a different width than the result/lhs, sext it or truncate it.
7254       unsigned VTWidth = VT.getSizeInBits();
7255       if (OrigXWidth < VTWidth) {
7256         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7257         AddToWorklist(X.getNode());
7258       } else if (OrigXWidth > VTWidth) {
7259         // To get the sign bit in the right place, we have to shift it right
7260         // before truncating.
7261         SDLoc DL(X);
7262         X = DAG.getNode(ISD::SRL, DL,
7263                         X.getValueType(), X,
7264                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7265                                         X.getValueType()));
7266         AddToWorklist(X.getNode());
7267         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7268         AddToWorklist(X.getNode());
7269       }
7270
7271       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7272       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7273                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7274       AddToWorklist(X.getNode());
7275
7276       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7277                                 VT, N0.getOperand(0));
7278       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7279                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7280       AddToWorklist(Cst.getNode());
7281
7282       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7283     }
7284   }
7285
7286   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7287   if (N0.getOpcode() == ISD::BUILD_PAIR)
7288     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7289       return CombineLD;
7290
7291   // Remove double bitcasts from shuffles - this is often a legacy of
7292   // XformToShuffleWithZero being used to combine bitmaskings (of
7293   // float vectors bitcast to integer vectors) into shuffles.
7294   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7295   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7296       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7297       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7298       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7299     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7300
7301     // If operands are a bitcast, peek through if it casts the original VT.
7302     // If operands are a constant, just bitcast back to original VT.
7303     auto PeekThroughBitcast = [&](SDValue Op) {
7304       if (Op.getOpcode() == ISD::BITCAST &&
7305           Op.getOperand(0).getValueType() == VT)
7306         return SDValue(Op.getOperand(0));
7307       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7308           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7309         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7310       return SDValue();
7311     };
7312
7313     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7314     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7315     if (!(SV0 && SV1))
7316       return SDValue();
7317
7318     int MaskScale =
7319         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7320     SmallVector<int, 8> NewMask;
7321     for (int M : SVN->getMask())
7322       for (int i = 0; i != MaskScale; ++i)
7323         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7324
7325     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7326     if (!LegalMask) {
7327       std::swap(SV0, SV1);
7328       ShuffleVectorSDNode::commuteMask(NewMask);
7329       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7330     }
7331
7332     if (LegalMask)
7333       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7334   }
7335
7336   return SDValue();
7337 }
7338
7339 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7340   EVT VT = N->getValueType(0);
7341   return CombineConsecutiveLoads(N, VT);
7342 }
7343
7344 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7345 /// operands. DstEltVT indicates the destination element value type.
7346 SDValue DAGCombiner::
7347 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7348   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7349
7350   // If this is already the right type, we're done.
7351   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7352
7353   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7354   unsigned DstBitSize = DstEltVT.getSizeInBits();
7355
7356   // If this is a conversion of N elements of one type to N elements of another
7357   // type, convert each element.  This handles FP<->INT cases.
7358   if (SrcBitSize == DstBitSize) {
7359     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7360                               BV->getValueType(0).getVectorNumElements());
7361
7362     // Due to the FP element handling below calling this routine recursively,
7363     // we can end up with a scalar-to-vector node here.
7364     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7365       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7366                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7367                                      DstEltVT, BV->getOperand(0)));
7368
7369     SmallVector<SDValue, 8> Ops;
7370     for (SDValue Op : BV->op_values()) {
7371       // If the vector element type is not legal, the BUILD_VECTOR operands
7372       // are promoted and implicitly truncated.  Make that explicit here.
7373       if (Op.getValueType() != SrcEltVT)
7374         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7375       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7376                                 DstEltVT, Op));
7377       AddToWorklist(Ops.back().getNode());
7378     }
7379     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7380   }
7381
7382   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7383   // handle annoying details of growing/shrinking FP values, we convert them to
7384   // int first.
7385   if (SrcEltVT.isFloatingPoint()) {
7386     // Convert the input float vector to a int vector where the elements are the
7387     // same sizes.
7388     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7389     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7390     SrcEltVT = IntVT;
7391   }
7392
7393   // Now we know the input is an integer vector.  If the output is a FP type,
7394   // convert to integer first, then to FP of the right size.
7395   if (DstEltVT.isFloatingPoint()) {
7396     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7397     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7398
7399     // Next, convert to FP elements of the same size.
7400     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7401   }
7402
7403   SDLoc DL(BV);
7404
7405   // Okay, we know the src/dst types are both integers of differing types.
7406   // Handling growing first.
7407   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7408   if (SrcBitSize < DstBitSize) {
7409     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7410
7411     SmallVector<SDValue, 8> Ops;
7412     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7413          i += NumInputsPerOutput) {
7414       bool isLE = DAG.getDataLayout().isLittleEndian();
7415       APInt NewBits = APInt(DstBitSize, 0);
7416       bool EltIsUndef = true;
7417       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7418         // Shift the previously computed bits over.
7419         NewBits <<= SrcBitSize;
7420         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7421         if (Op.getOpcode() == ISD::UNDEF) continue;
7422         EltIsUndef = false;
7423
7424         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7425                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7426       }
7427
7428       if (EltIsUndef)
7429         Ops.push_back(DAG.getUNDEF(DstEltVT));
7430       else
7431         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7432     }
7433
7434     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7435     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7436   }
7437
7438   // Finally, this must be the case where we are shrinking elements: each input
7439   // turns into multiple outputs.
7440   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7441   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7442                             NumOutputsPerInput*BV->getNumOperands());
7443   SmallVector<SDValue, 8> Ops;
7444
7445   for (const SDValue &Op : BV->op_values()) {
7446     if (Op.getOpcode() == ISD::UNDEF) {
7447       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7448       continue;
7449     }
7450
7451     APInt OpVal = cast<ConstantSDNode>(Op)->
7452                   getAPIntValue().zextOrTrunc(SrcBitSize);
7453
7454     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7455       APInt ThisVal = OpVal.trunc(DstBitSize);
7456       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7457       OpVal = OpVal.lshr(DstBitSize);
7458     }
7459
7460     // For big endian targets, swap the order of the pieces of each element.
7461     if (DAG.getDataLayout().isBigEndian())
7462       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7463   }
7464
7465   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7466 }
7467
7468 /// Try to perform FMA combining on a given FADD node.
7469 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7470   SDValue N0 = N->getOperand(0);
7471   SDValue N1 = N->getOperand(1);
7472   EVT VT = N->getValueType(0);
7473   SDLoc SL(N);
7474
7475   const TargetOptions &Options = DAG.getTarget().Options;
7476   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7477                        Options.UnsafeFPMath);
7478
7479   // Floating-point multiply-add with intermediate rounding.
7480   bool HasFMAD = (LegalOperations &&
7481                   TLI.isOperationLegal(ISD::FMAD, VT));
7482
7483   // Floating-point multiply-add without intermediate rounding.
7484   bool HasFMA = ((!LegalOperations ||
7485                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7486                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7487                  UnsafeFPMath);
7488
7489   // No valid opcode, do not combine.
7490   if (!HasFMAD && !HasFMA)
7491     return SDValue();
7492
7493   // Always prefer FMAD to FMA for precision.
7494   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7495   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7496   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7497
7498   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7499   // prefer to fold the multiply with fewer uses.
7500   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7501       N1.getOpcode() == ISD::FMUL) {
7502     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7503       std::swap(N0, N1);
7504   }
7505
7506   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7507   if (N0.getOpcode() == ISD::FMUL &&
7508       (Aggressive || N0->hasOneUse())) {
7509     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7510                        N0.getOperand(0), N0.getOperand(1), N1);
7511   }
7512
7513   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7514   // Note: Commutes FADD operands.
7515   if (N1.getOpcode() == ISD::FMUL &&
7516       (Aggressive || N1->hasOneUse())) {
7517     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7518                        N1.getOperand(0), N1.getOperand(1), N0);
7519   }
7520
7521   // Look through FP_EXTEND nodes to do more combining.
7522   if (UnsafeFPMath && LookThroughFPExt) {
7523     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7524     if (N0.getOpcode() == ISD::FP_EXTEND) {
7525       SDValue N00 = N0.getOperand(0);
7526       if (N00.getOpcode() == ISD::FMUL)
7527         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7528                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7529                                        N00.getOperand(0)),
7530                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7531                                        N00.getOperand(1)), N1);
7532     }
7533
7534     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7535     // Note: Commutes FADD operands.
7536     if (N1.getOpcode() == ISD::FP_EXTEND) {
7537       SDValue N10 = N1.getOperand(0);
7538       if (N10.getOpcode() == ISD::FMUL)
7539         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7540                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7541                                        N10.getOperand(0)),
7542                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7543                                        N10.getOperand(1)), N0);
7544     }
7545   }
7546
7547   // More folding opportunities when target permits.
7548   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7549     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7550     if (N0.getOpcode() == PreferredFusedOpcode &&
7551         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7552       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7553                          N0.getOperand(0), N0.getOperand(1),
7554                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7555                                      N0.getOperand(2).getOperand(0),
7556                                      N0.getOperand(2).getOperand(1),
7557                                      N1));
7558     }
7559
7560     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7561     if (N1->getOpcode() == PreferredFusedOpcode &&
7562         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7563       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7564                          N1.getOperand(0), N1.getOperand(1),
7565                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7566                                      N1.getOperand(2).getOperand(0),
7567                                      N1.getOperand(2).getOperand(1),
7568                                      N0));
7569     }
7570
7571     if (UnsafeFPMath && LookThroughFPExt) {
7572       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7573       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7574       auto FoldFAddFMAFPExtFMul = [&] (
7575           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7576         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7577                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7578                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7579                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7580                                        Z));
7581       };
7582       if (N0.getOpcode() == PreferredFusedOpcode) {
7583         SDValue N02 = N0.getOperand(2);
7584         if (N02.getOpcode() == ISD::FP_EXTEND) {
7585           SDValue N020 = N02.getOperand(0);
7586           if (N020.getOpcode() == ISD::FMUL)
7587             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7588                                         N020.getOperand(0), N020.getOperand(1),
7589                                         N1);
7590         }
7591       }
7592
7593       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7594       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7595       // FIXME: This turns two single-precision and one double-precision
7596       // operation into two double-precision operations, which might not be
7597       // interesting for all targets, especially GPUs.
7598       auto FoldFAddFPExtFMAFMul = [&] (
7599           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7600         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7601                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7602                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7603                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7604                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7605                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7606                                        Z));
7607       };
7608       if (N0.getOpcode() == ISD::FP_EXTEND) {
7609         SDValue N00 = N0.getOperand(0);
7610         if (N00.getOpcode() == PreferredFusedOpcode) {
7611           SDValue N002 = N00.getOperand(2);
7612           if (N002.getOpcode() == ISD::FMUL)
7613             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7614                                         N002.getOperand(0), N002.getOperand(1),
7615                                         N1);
7616         }
7617       }
7618
7619       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7620       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7621       if (N1.getOpcode() == PreferredFusedOpcode) {
7622         SDValue N12 = N1.getOperand(2);
7623         if (N12.getOpcode() == ISD::FP_EXTEND) {
7624           SDValue N120 = N12.getOperand(0);
7625           if (N120.getOpcode() == ISD::FMUL)
7626             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7627                                         N120.getOperand(0), N120.getOperand(1),
7628                                         N0);
7629         }
7630       }
7631
7632       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7633       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7634       // FIXME: This turns two single-precision and one double-precision
7635       // operation into two double-precision operations, which might not be
7636       // interesting for all targets, especially GPUs.
7637       if (N1.getOpcode() == ISD::FP_EXTEND) {
7638         SDValue N10 = N1.getOperand(0);
7639         if (N10.getOpcode() == PreferredFusedOpcode) {
7640           SDValue N102 = N10.getOperand(2);
7641           if (N102.getOpcode() == ISD::FMUL)
7642             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7643                                         N102.getOperand(0), N102.getOperand(1),
7644                                         N0);
7645         }
7646       }
7647     }
7648   }
7649
7650   return SDValue();
7651 }
7652
7653 /// Try to perform FMA combining on a given FSUB node.
7654 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7655   SDValue N0 = N->getOperand(0);
7656   SDValue N1 = N->getOperand(1);
7657   EVT VT = N->getValueType(0);
7658   SDLoc SL(N);
7659
7660   const TargetOptions &Options = DAG.getTarget().Options;
7661   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7662                        Options.UnsafeFPMath);
7663
7664   // Floating-point multiply-add with intermediate rounding.
7665   bool HasFMAD = (LegalOperations &&
7666                   TLI.isOperationLegal(ISD::FMAD, VT));
7667
7668   // Floating-point multiply-add without intermediate rounding.
7669   bool HasFMA = ((!LegalOperations ||
7670                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7671                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7672                  UnsafeFPMath);
7673
7674   // No valid opcode, do not combine.
7675   if (!HasFMAD && !HasFMA)
7676     return SDValue();
7677
7678   // Always prefer FMAD to FMA for precision.
7679   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7680   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7681   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7682
7683   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7684   if (N0.getOpcode() == ISD::FMUL &&
7685       (Aggressive || N0->hasOneUse())) {
7686     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7687                        N0.getOperand(0), N0.getOperand(1),
7688                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7689   }
7690
7691   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7692   // Note: Commutes FSUB operands.
7693   if (N1.getOpcode() == ISD::FMUL &&
7694       (Aggressive || N1->hasOneUse()))
7695     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7696                        DAG.getNode(ISD::FNEG, SL, VT,
7697                                    N1.getOperand(0)),
7698                        N1.getOperand(1), N0);
7699
7700   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7701   if (N0.getOpcode() == ISD::FNEG &&
7702       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7703       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7704     SDValue N00 = N0.getOperand(0).getOperand(0);
7705     SDValue N01 = N0.getOperand(0).getOperand(1);
7706     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7707                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7708                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7709   }
7710
7711   // Look through FP_EXTEND nodes to do more combining.
7712   if (UnsafeFPMath && LookThroughFPExt) {
7713     // fold (fsub (fpext (fmul x, y)), z)
7714     //   -> (fma (fpext x), (fpext y), (fneg z))
7715     if (N0.getOpcode() == ISD::FP_EXTEND) {
7716       SDValue N00 = N0.getOperand(0);
7717       if (N00.getOpcode() == ISD::FMUL)
7718         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7719                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7720                                        N00.getOperand(0)),
7721                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7722                                        N00.getOperand(1)),
7723                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7724     }
7725
7726     // fold (fsub x, (fpext (fmul y, z)))
7727     //   -> (fma (fneg (fpext y)), (fpext z), x)
7728     // Note: Commutes FSUB operands.
7729     if (N1.getOpcode() == ISD::FP_EXTEND) {
7730       SDValue N10 = N1.getOperand(0);
7731       if (N10.getOpcode() == ISD::FMUL)
7732         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7733                            DAG.getNode(ISD::FNEG, SL, VT,
7734                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7735                                                    N10.getOperand(0))),
7736                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7737                                        N10.getOperand(1)),
7738                            N0);
7739     }
7740
7741     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7742     //   -> (fneg (fma (fpext x), (fpext y), z))
7743     // Note: This could be removed with appropriate canonicalization of the
7744     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7745     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7746     // from implementing the canonicalization in visitFSUB.
7747     if (N0.getOpcode() == ISD::FP_EXTEND) {
7748       SDValue N00 = N0.getOperand(0);
7749       if (N00.getOpcode() == ISD::FNEG) {
7750         SDValue N000 = N00.getOperand(0);
7751         if (N000.getOpcode() == ISD::FMUL) {
7752           return DAG.getNode(ISD::FNEG, SL, VT,
7753                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7754                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7755                                                      N000.getOperand(0)),
7756                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7757                                                      N000.getOperand(1)),
7758                                          N1));
7759         }
7760       }
7761     }
7762
7763     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7764     //   -> (fneg (fma (fpext x)), (fpext y), z)
7765     // Note: This could be removed with appropriate canonicalization of the
7766     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7767     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7768     // from implementing the canonicalization in visitFSUB.
7769     if (N0.getOpcode() == ISD::FNEG) {
7770       SDValue N00 = N0.getOperand(0);
7771       if (N00.getOpcode() == ISD::FP_EXTEND) {
7772         SDValue N000 = N00.getOperand(0);
7773         if (N000.getOpcode() == ISD::FMUL) {
7774           return DAG.getNode(ISD::FNEG, SL, VT,
7775                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7776                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7777                                                      N000.getOperand(0)),
7778                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779                                                      N000.getOperand(1)),
7780                                          N1));
7781         }
7782       }
7783     }
7784
7785   }
7786
7787   // More folding opportunities when target permits.
7788   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7789     // fold (fsub (fma x, y, (fmul u, v)), z)
7790     //   -> (fma x, y (fma u, v, (fneg z)))
7791     if (N0.getOpcode() == PreferredFusedOpcode &&
7792         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7793       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7794                          N0.getOperand(0), N0.getOperand(1),
7795                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7796                                      N0.getOperand(2).getOperand(0),
7797                                      N0.getOperand(2).getOperand(1),
7798                                      DAG.getNode(ISD::FNEG, SL, VT,
7799                                                  N1)));
7800     }
7801
7802     // fold (fsub x, (fma y, z, (fmul u, v)))
7803     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7804     if (N1.getOpcode() == PreferredFusedOpcode &&
7805         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7806       SDValue N20 = N1.getOperand(2).getOperand(0);
7807       SDValue N21 = N1.getOperand(2).getOperand(1);
7808       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7809                          DAG.getNode(ISD::FNEG, SL, VT,
7810                                      N1.getOperand(0)),
7811                          N1.getOperand(1),
7812                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7813                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7814
7815                                      N21, N0));
7816     }
7817
7818     if (UnsafeFPMath && LookThroughFPExt) {
7819       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7820       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7821       if (N0.getOpcode() == PreferredFusedOpcode) {
7822         SDValue N02 = N0.getOperand(2);
7823         if (N02.getOpcode() == ISD::FP_EXTEND) {
7824           SDValue N020 = N02.getOperand(0);
7825           if (N020.getOpcode() == ISD::FMUL)
7826             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7827                                N0.getOperand(0), N0.getOperand(1),
7828                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7829                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7830                                                        N020.getOperand(0)),
7831                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7832                                                        N020.getOperand(1)),
7833                                            DAG.getNode(ISD::FNEG, SL, VT,
7834                                                        N1)));
7835         }
7836       }
7837
7838       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7839       //   -> (fma (fpext x), (fpext y),
7840       //           (fma (fpext u), (fpext v), (fneg z)))
7841       // FIXME: This turns two single-precision and one double-precision
7842       // operation into two double-precision operations, which might not be
7843       // interesting for all targets, especially GPUs.
7844       if (N0.getOpcode() == ISD::FP_EXTEND) {
7845         SDValue N00 = N0.getOperand(0);
7846         if (N00.getOpcode() == PreferredFusedOpcode) {
7847           SDValue N002 = N00.getOperand(2);
7848           if (N002.getOpcode() == ISD::FMUL)
7849             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7850                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7851                                            N00.getOperand(0)),
7852                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7853                                            N00.getOperand(1)),
7854                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7855                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7856                                                        N002.getOperand(0)),
7857                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7858                                                        N002.getOperand(1)),
7859                                            DAG.getNode(ISD::FNEG, SL, VT,
7860                                                        N1)));
7861         }
7862       }
7863
7864       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7865       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7866       if (N1.getOpcode() == PreferredFusedOpcode &&
7867         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7868         SDValue N120 = N1.getOperand(2).getOperand(0);
7869         if (N120.getOpcode() == ISD::FMUL) {
7870           SDValue N1200 = N120.getOperand(0);
7871           SDValue N1201 = N120.getOperand(1);
7872           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7873                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7874                              N1.getOperand(1),
7875                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7876                                          DAG.getNode(ISD::FNEG, SL, VT,
7877                                              DAG.getNode(ISD::FP_EXTEND, SL,
7878                                                          VT, N1200)),
7879                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7880                                                      N1201),
7881                                          N0));
7882         }
7883       }
7884
7885       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7886       //   -> (fma (fneg (fpext y)), (fpext z),
7887       //           (fma (fneg (fpext u)), (fpext v), x))
7888       // FIXME: This turns two single-precision and one double-precision
7889       // operation into two double-precision operations, which might not be
7890       // interesting for all targets, especially GPUs.
7891       if (N1.getOpcode() == ISD::FP_EXTEND &&
7892         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7893         SDValue N100 = N1.getOperand(0).getOperand(0);
7894         SDValue N101 = N1.getOperand(0).getOperand(1);
7895         SDValue N102 = N1.getOperand(0).getOperand(2);
7896         if (N102.getOpcode() == ISD::FMUL) {
7897           SDValue N1020 = N102.getOperand(0);
7898           SDValue N1021 = N102.getOperand(1);
7899           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7900                              DAG.getNode(ISD::FNEG, SL, VT,
7901                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7902                                                      N100)),
7903                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7904                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7905                                          DAG.getNode(ISD::FNEG, SL, VT,
7906                                              DAG.getNode(ISD::FP_EXTEND, SL,
7907                                                          VT, N1020)),
7908                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7909                                                      N1021),
7910                                          N0));
7911         }
7912       }
7913     }
7914   }
7915
7916   return SDValue();
7917 }
7918
7919 SDValue DAGCombiner::visitFADD(SDNode *N) {
7920   SDValue N0 = N->getOperand(0);
7921   SDValue N1 = N->getOperand(1);
7922   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7923   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7924   EVT VT = N->getValueType(0);
7925   SDLoc DL(N);
7926   const TargetOptions &Options = DAG.getTarget().Options;
7927
7928   // fold vector ops
7929   if (VT.isVector())
7930     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7931       return FoldedVOp;
7932
7933   // fold (fadd c1, c2) -> c1 + c2
7934   if (N0CFP && N1CFP)
7935     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7936
7937   // canonicalize constant to RHS
7938   if (N0CFP && !N1CFP)
7939     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7940
7941   // fold (fadd A, (fneg B)) -> (fsub A, B)
7942   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7943       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7944     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7945                        GetNegatedExpression(N1, DAG, LegalOperations));
7946
7947   // fold (fadd (fneg A), B) -> (fsub B, A)
7948   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7949       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7950     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7951                        GetNegatedExpression(N0, DAG, LegalOperations));
7952
7953   // If 'unsafe math' is enabled, fold lots of things.
7954   if (Options.UnsafeFPMath) {
7955     // No FP constant should be created after legalization as Instruction
7956     // Selection pass has a hard time dealing with FP constants.
7957     bool AllowNewConst = (Level < AfterLegalizeDAG);
7958
7959     // fold (fadd A, 0) -> A
7960     if (N1CFP && N1CFP->isZero())
7961       return N0;
7962
7963     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7964     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7965         isa<ConstantFPSDNode>(N0.getOperand(1)))
7966       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7967                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7968
7969     // If allowed, fold (fadd (fneg x), x) -> 0.0
7970     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7971       return DAG.getConstantFP(0.0, DL, VT);
7972
7973     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7974     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7975       return DAG.getConstantFP(0.0, DL, VT);
7976
7977     // We can fold chains of FADD's of the same value into multiplications.
7978     // This transform is not safe in general because we are reducing the number
7979     // of rounding steps.
7980     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7981       if (N0.getOpcode() == ISD::FMUL) {
7982         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7983         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7984
7985         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7986         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7987           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7988                                        DAG.getConstantFP(1.0, DL, VT));
7989           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7990         }
7991
7992         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7993         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7994             N1.getOperand(0) == N1.getOperand(1) &&
7995             N0.getOperand(0) == N1.getOperand(0)) {
7996           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7997                                        DAG.getConstantFP(2.0, DL, VT));
7998           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7999         }
8000       }
8001
8002       if (N1.getOpcode() == ISD::FMUL) {
8003         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8004         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
8005
8006         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8007         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8008           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8009                                        DAG.getConstantFP(1.0, DL, VT));
8010           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
8011         }
8012
8013         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8014         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8015             N0.getOperand(0) == N0.getOperand(1) &&
8016             N1.getOperand(0) == N0.getOperand(0)) {
8017           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8018                                        DAG.getConstantFP(2.0, DL, VT));
8019           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
8020         }
8021       }
8022
8023       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8024         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8025         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8026         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
8027             (N0.getOperand(0) == N1)) {
8028           return DAG.getNode(ISD::FMUL, DL, VT,
8029                              N1, DAG.getConstantFP(3.0, DL, VT));
8030         }
8031       }
8032
8033       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8034         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8035         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8036         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8037             N1.getOperand(0) == N0) {
8038           return DAG.getNode(ISD::FMUL, DL, VT,
8039                              N0, DAG.getConstantFP(3.0, DL, VT));
8040         }
8041       }
8042
8043       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8044       if (AllowNewConst &&
8045           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8046           N0.getOperand(0) == N0.getOperand(1) &&
8047           N1.getOperand(0) == N1.getOperand(1) &&
8048           N0.getOperand(0) == N1.getOperand(0)) {
8049         return DAG.getNode(ISD::FMUL, DL, VT,
8050                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
8051       }
8052     }
8053   } // enable-unsafe-fp-math
8054
8055   // FADD -> FMA combines:
8056   if (SDValue Fused = visitFADDForFMACombine(N)) {
8057     AddToWorklist(Fused.getNode());
8058     return Fused;
8059   }
8060
8061   return SDValue();
8062 }
8063
8064 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8065   SDValue N0 = N->getOperand(0);
8066   SDValue N1 = N->getOperand(1);
8067   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8068   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8069   EVT VT = N->getValueType(0);
8070   SDLoc dl(N);
8071   const TargetOptions &Options = DAG.getTarget().Options;
8072
8073   // fold vector ops
8074   if (VT.isVector())
8075     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8076       return FoldedVOp;
8077
8078   // fold (fsub c1, c2) -> c1-c2
8079   if (N0CFP && N1CFP)
8080     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8081
8082   // fold (fsub A, (fneg B)) -> (fadd A, B)
8083   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8084     return DAG.getNode(ISD::FADD, dl, VT, N0,
8085                        GetNegatedExpression(N1, DAG, LegalOperations));
8086
8087   // If 'unsafe math' is enabled, fold lots of things.
8088   if (Options.UnsafeFPMath) {
8089     // (fsub A, 0) -> A
8090     if (N1CFP && N1CFP->isZero())
8091       return N0;
8092
8093     // (fsub 0, B) -> -B
8094     if (N0CFP && N0CFP->isZero()) {
8095       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8096         return GetNegatedExpression(N1, DAG, LegalOperations);
8097       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8098         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8099     }
8100
8101     // (fsub x, x) -> 0.0
8102     if (N0 == N1)
8103       return DAG.getConstantFP(0.0f, dl, VT);
8104
8105     // (fsub x, (fadd x, y)) -> (fneg y)
8106     // (fsub x, (fadd y, x)) -> (fneg y)
8107     if (N1.getOpcode() == ISD::FADD) {
8108       SDValue N10 = N1->getOperand(0);
8109       SDValue N11 = N1->getOperand(1);
8110
8111       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8112         return GetNegatedExpression(N11, DAG, LegalOperations);
8113
8114       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8115         return GetNegatedExpression(N10, DAG, LegalOperations);
8116     }
8117   }
8118
8119   // FSUB -> FMA combines:
8120   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8121     AddToWorklist(Fused.getNode());
8122     return Fused;
8123   }
8124
8125   return SDValue();
8126 }
8127
8128 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8129   SDValue N0 = N->getOperand(0);
8130   SDValue N1 = N->getOperand(1);
8131   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8132   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8133   EVT VT = N->getValueType(0);
8134   SDLoc DL(N);
8135   const TargetOptions &Options = DAG.getTarget().Options;
8136
8137   // fold vector ops
8138   if (VT.isVector()) {
8139     // This just handles C1 * C2 for vectors. Other vector folds are below.
8140     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8141       return FoldedVOp;
8142   }
8143
8144   // fold (fmul c1, c2) -> c1*c2
8145   if (N0CFP && N1CFP)
8146     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8147
8148   // canonicalize constant to RHS
8149   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8150      !isConstantFPBuildVectorOrConstantFP(N1))
8151     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8152
8153   // fold (fmul A, 1.0) -> A
8154   if (N1CFP && N1CFP->isExactlyValue(1.0))
8155     return N0;
8156
8157   if (Options.UnsafeFPMath) {
8158     // fold (fmul A, 0) -> 0
8159     if (N1CFP && N1CFP->isZero())
8160       return N1;
8161
8162     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8163     if (N0.getOpcode() == ISD::FMUL) {
8164       // Fold scalars or any vector constants (not just splats).
8165       // This fold is done in general by InstCombine, but extra fmul insts
8166       // may have been generated during lowering.
8167       SDValue N00 = N0.getOperand(0);
8168       SDValue N01 = N0.getOperand(1);
8169       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8170       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8171       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8172
8173       // Check 1: Make sure that the first operand of the inner multiply is NOT
8174       // a constant. Otherwise, we may induce infinite looping.
8175       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8176         // Check 2: Make sure that the second operand of the inner multiply and
8177         // the second operand of the outer multiply are constants.
8178         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8179             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8180           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8181           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8182         }
8183       }
8184     }
8185
8186     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8187     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8188     // during an early run of DAGCombiner can prevent folding with fmuls
8189     // inserted during lowering.
8190     if (N0.getOpcode() == ISD::FADD &&
8191         (N0.getOperand(0) == N0.getOperand(1)) &&
8192         N0.hasOneUse()) {
8193       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8194       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8195       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8196     }
8197   }
8198
8199   // fold (fmul X, 2.0) -> (fadd X, X)
8200   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8201     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8202
8203   // fold (fmul X, -1.0) -> (fneg X)
8204   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8205     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8206       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8207
8208   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8209   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8210     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8211       // Both can be negated for free, check to see if at least one is cheaper
8212       // negated.
8213       if (LHSNeg == 2 || RHSNeg == 2)
8214         return DAG.getNode(ISD::FMUL, DL, VT,
8215                            GetNegatedExpression(N0, DAG, LegalOperations),
8216                            GetNegatedExpression(N1, DAG, LegalOperations));
8217     }
8218   }
8219
8220   return SDValue();
8221 }
8222
8223 SDValue DAGCombiner::visitFMA(SDNode *N) {
8224   SDValue N0 = N->getOperand(0);
8225   SDValue N1 = N->getOperand(1);
8226   SDValue N2 = N->getOperand(2);
8227   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8228   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8229   EVT VT = N->getValueType(0);
8230   SDLoc dl(N);
8231   const TargetOptions &Options = DAG.getTarget().Options;
8232
8233   // Constant fold FMA.
8234   if (isa<ConstantFPSDNode>(N0) &&
8235       isa<ConstantFPSDNode>(N1) &&
8236       isa<ConstantFPSDNode>(N2)) {
8237     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8238   }
8239
8240   if (Options.UnsafeFPMath) {
8241     if (N0CFP && N0CFP->isZero())
8242       return N2;
8243     if (N1CFP && N1CFP->isZero())
8244       return N2;
8245   }
8246   if (N0CFP && N0CFP->isExactlyValue(1.0))
8247     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8248   if (N1CFP && N1CFP->isExactlyValue(1.0))
8249     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8250
8251   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8252   if (N0CFP && !N1CFP)
8253     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8254
8255   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8256   if (Options.UnsafeFPMath && N1CFP &&
8257       N2.getOpcode() == ISD::FMUL &&
8258       N0 == N2.getOperand(0) &&
8259       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8260     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8261                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8262   }
8263
8264
8265   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8266   if (Options.UnsafeFPMath &&
8267       N0.getOpcode() == ISD::FMUL && N1CFP &&
8268       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8269     return DAG.getNode(ISD::FMA, dl, VT,
8270                        N0.getOperand(0),
8271                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8272                        N2);
8273   }
8274
8275   // (fma x, 1, y) -> (fadd x, y)
8276   // (fma x, -1, y) -> (fadd (fneg x), y)
8277   if (N1CFP) {
8278     if (N1CFP->isExactlyValue(1.0))
8279       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8280
8281     if (N1CFP->isExactlyValue(-1.0) &&
8282         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8283       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8284       AddToWorklist(RHSNeg.getNode());
8285       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8286     }
8287   }
8288
8289   // (fma x, c, x) -> (fmul x, (c+1))
8290   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8291     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8292                        DAG.getNode(ISD::FADD, dl, VT,
8293                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8294
8295   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8296   if (Options.UnsafeFPMath && N1CFP &&
8297       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8298     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8299                        DAG.getNode(ISD::FADD, dl, VT,
8300                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8301
8302
8303   return SDValue();
8304 }
8305
8306 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8307 // reciprocal.
8308 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8309 // Notice that this is not always beneficial. One reason is different target
8310 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8311 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8312 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8313 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8314   if (!DAG.getTarget().Options.UnsafeFPMath)
8315     return SDValue();
8316
8317   // Skip if current node is a reciprocal.
8318   SDValue N0 = N->getOperand(0);
8319   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8320   if (N0CFP && N0CFP->isExactlyValue(1.0))
8321     return SDValue();
8322
8323   // Exit early if the target does not want this transform or if there can't
8324   // possibly be enough uses of the divisor to make the transform worthwhile.
8325   SDValue N1 = N->getOperand(1);
8326   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8327   if (!MinUses || N1->use_size() < MinUses)
8328     return SDValue();
8329
8330   // Find all FDIV users of the same divisor.
8331   // Use a set because duplicates may be present in the user list.
8332   SetVector<SDNode *> Users;
8333   for (auto *U : N1->uses())
8334     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8335       Users.insert(U);
8336
8337   // Now that we have the actual number of divisor uses, make sure it meets
8338   // the minimum threshold specified by the target.
8339   if (Users.size() < MinUses)
8340     return SDValue();
8341
8342   EVT VT = N->getValueType(0);
8343   SDLoc DL(N);
8344   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8345   // FIXME: This optimization requires some level of fast-math, so the
8346   // created reciprocal node should at least have the 'allowReciprocal'
8347   // fast-math-flag set.
8348   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8349
8350   // Dividend / Divisor -> Dividend * Reciprocal
8351   for (auto *U : Users) {
8352     SDValue Dividend = U->getOperand(0);
8353     if (Dividend != FPOne) {
8354       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8355                                     Reciprocal);
8356       CombineTo(U, NewNode);
8357     } else if (U != Reciprocal.getNode()) {
8358       // In the absence of fast-math-flags, this user node is always the
8359       // same node as Reciprocal, but with FMF they may be different nodes.
8360       CombineTo(U, Reciprocal);
8361     }
8362   }
8363   return SDValue(N, 0);  // N was replaced.
8364 }
8365
8366 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8367   SDValue N0 = N->getOperand(0);
8368   SDValue N1 = N->getOperand(1);
8369   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8370   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8371   EVT VT = N->getValueType(0);
8372   SDLoc DL(N);
8373   const TargetOptions &Options = DAG.getTarget().Options;
8374
8375   // fold vector ops
8376   if (VT.isVector())
8377     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8378       return FoldedVOp;
8379
8380   // fold (fdiv c1, c2) -> c1/c2
8381   if (N0CFP && N1CFP)
8382     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8383
8384   if (Options.UnsafeFPMath) {
8385     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8386     if (N1CFP) {
8387       // Compute the reciprocal 1.0 / c2.
8388       APFloat N1APF = N1CFP->getValueAPF();
8389       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8390       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8391       // Only do the transform if the reciprocal is a legal fp immediate that
8392       // isn't too nasty (eg NaN, denormal, ...).
8393       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8394           (!LegalOperations ||
8395            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8396            // backend)... we should handle this gracefully after Legalize.
8397            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8398            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8399            TLI.isFPImmLegal(Recip, VT)))
8400         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8401                            DAG.getConstantFP(Recip, DL, VT));
8402     }
8403
8404     // If this FDIV is part of a reciprocal square root, it may be folded
8405     // into a target-specific square root estimate instruction.
8406     if (N1.getOpcode() == ISD::FSQRT) {
8407       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8408         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8409       }
8410     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8411                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8412       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8413         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8414         AddToWorklist(RV.getNode());
8415         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8416       }
8417     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8418                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8419       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8420         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8421         AddToWorklist(RV.getNode());
8422         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8423       }
8424     } else if (N1.getOpcode() == ISD::FMUL) {
8425       // Look through an FMUL. Even though this won't remove the FDIV directly,
8426       // it's still worthwhile to get rid of the FSQRT if possible.
8427       SDValue SqrtOp;
8428       SDValue OtherOp;
8429       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8430         SqrtOp = N1.getOperand(0);
8431         OtherOp = N1.getOperand(1);
8432       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8433         SqrtOp = N1.getOperand(1);
8434         OtherOp = N1.getOperand(0);
8435       }
8436       if (SqrtOp.getNode()) {
8437         // We found a FSQRT, so try to make this fold:
8438         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8439         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8440           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8441           AddToWorklist(RV.getNode());
8442           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8443         }
8444       }
8445     }
8446
8447     // Fold into a reciprocal estimate and multiply instead of a real divide.
8448     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8449       AddToWorklist(RV.getNode());
8450       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8451     }
8452   }
8453
8454   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8455   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8456     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8457       // Both can be negated for free, check to see if at least one is cheaper
8458       // negated.
8459       if (LHSNeg == 2 || RHSNeg == 2)
8460         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8461                            GetNegatedExpression(N0, DAG, LegalOperations),
8462                            GetNegatedExpression(N1, DAG, LegalOperations));
8463     }
8464   }
8465
8466   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8467     return CombineRepeatedDivisors;
8468
8469   return SDValue();
8470 }
8471
8472 SDValue DAGCombiner::visitFREM(SDNode *N) {
8473   SDValue N0 = N->getOperand(0);
8474   SDValue N1 = N->getOperand(1);
8475   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8476   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8477   EVT VT = N->getValueType(0);
8478
8479   // fold (frem c1, c2) -> fmod(c1,c2)
8480   if (N0CFP && N1CFP)
8481     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8482
8483   return SDValue();
8484 }
8485
8486 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8487   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8488     return SDValue();
8489
8490   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8491   SDValue RV = BuildRsqrtEstimate(N->getOperand(0));
8492   if (!RV)
8493     return SDValue();
8494
8495   EVT VT = RV.getValueType();
8496   SDLoc DL(N);
8497   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8498   AddToWorklist(RV.getNode());
8499
8500   // Unfortunately, RV is now NaN if the input was exactly 0.
8501   // Select out this case and force the answer to 0.
8502   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8503   EVT CCVT = getSetCCResultType(VT);
8504   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8505   AddToWorklist(ZeroCmp.getNode());
8506   AddToWorklist(RV.getNode());
8507
8508   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8509                      ZeroCmp, Zero, RV);
8510 }
8511
8512 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8513   SDValue N0 = N->getOperand(0);
8514   SDValue N1 = N->getOperand(1);
8515   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8516   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8517   EVT VT = N->getValueType(0);
8518
8519   if (N0CFP && N1CFP)  // Constant fold
8520     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8521
8522   if (N1CFP) {
8523     const APFloat& V = N1CFP->getValueAPF();
8524     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8525     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8526     if (!V.isNegative()) {
8527       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8528         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8529     } else {
8530       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8531         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8532                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8533     }
8534   }
8535
8536   // copysign(fabs(x), y) -> copysign(x, y)
8537   // copysign(fneg(x), y) -> copysign(x, y)
8538   // copysign(copysign(x,z), y) -> copysign(x, y)
8539   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8540       N0.getOpcode() == ISD::FCOPYSIGN)
8541     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8542                        N0.getOperand(0), N1);
8543
8544   // copysign(x, abs(y)) -> abs(x)
8545   if (N1.getOpcode() == ISD::FABS)
8546     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8547
8548   // copysign(x, copysign(y,z)) -> copysign(x, z)
8549   if (N1.getOpcode() == ISD::FCOPYSIGN)
8550     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8551                        N0, N1.getOperand(1));
8552
8553   // copysign(x, fp_extend(y)) -> copysign(x, y)
8554   // copysign(x, fp_round(y)) -> copysign(x, y)
8555   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8556     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8557                        N0, N1.getOperand(0));
8558
8559   return SDValue();
8560 }
8561
8562 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8563   SDValue N0 = N->getOperand(0);
8564   EVT VT = N->getValueType(0);
8565   EVT OpVT = N0.getValueType();
8566
8567   // fold (sint_to_fp c1) -> c1fp
8568   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8569       // ...but only if the target supports immediate floating-point values
8570       (!LegalOperations ||
8571        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8572     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8573
8574   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8575   // but UINT_TO_FP is legal on this target, try to convert.
8576   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8577       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8578     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8579     if (DAG.SignBitIsZero(N0))
8580       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8581   }
8582
8583   // The next optimizations are desirable only if SELECT_CC can be lowered.
8584   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8585     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8586     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8587         !VT.isVector() &&
8588         (!LegalOperations ||
8589          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8590       SDLoc DL(N);
8591       SDValue Ops[] =
8592         { N0.getOperand(0), N0.getOperand(1),
8593           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8594           N0.getOperand(2) };
8595       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8596     }
8597
8598     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8599     //      (select_cc x, y, 1.0, 0.0,, cc)
8600     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8601         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8602         (!LegalOperations ||
8603          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8604       SDLoc DL(N);
8605       SDValue Ops[] =
8606         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8607           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8608           N0.getOperand(0).getOperand(2) };
8609       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8610     }
8611   }
8612
8613   return SDValue();
8614 }
8615
8616 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8617   SDValue N0 = N->getOperand(0);
8618   EVT VT = N->getValueType(0);
8619   EVT OpVT = N0.getValueType();
8620
8621   // fold (uint_to_fp c1) -> c1fp
8622   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8623       // ...but only if the target supports immediate floating-point values
8624       (!LegalOperations ||
8625        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8626     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8627
8628   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8629   // but SINT_TO_FP is legal on this target, try to convert.
8630   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8631       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8632     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8633     if (DAG.SignBitIsZero(N0))
8634       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8635   }
8636
8637   // The next optimizations are desirable only if SELECT_CC can be lowered.
8638   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8639     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8640
8641     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8642         (!LegalOperations ||
8643          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8644       SDLoc DL(N);
8645       SDValue Ops[] =
8646         { N0.getOperand(0), N0.getOperand(1),
8647           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8648           N0.getOperand(2) };
8649       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8650     }
8651   }
8652
8653   return SDValue();
8654 }
8655
8656 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8657 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8658   SDValue N0 = N->getOperand(0);
8659   EVT VT = N->getValueType(0);
8660
8661   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8662     return SDValue();
8663
8664   SDValue Src = N0.getOperand(0);
8665   EVT SrcVT = Src.getValueType();
8666   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8667   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8668
8669   // We can safely assume the conversion won't overflow the output range,
8670   // because (for example) (uint8_t)18293.f is undefined behavior.
8671
8672   // Since we can assume the conversion won't overflow, our decision as to
8673   // whether the input will fit in the float should depend on the minimum
8674   // of the input range and output range.
8675
8676   // This means this is also safe for a signed input and unsigned output, since
8677   // a negative input would lead to undefined behavior.
8678   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8679   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8680   unsigned ActualSize = std::min(InputSize, OutputSize);
8681   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8682
8683   // We can only fold away the float conversion if the input range can be
8684   // represented exactly in the float range.
8685   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8686     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8687       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8688                                                        : ISD::ZERO_EXTEND;
8689       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8690     }
8691     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8692       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8693     if (SrcVT == VT)
8694       return Src;
8695     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8696   }
8697   return SDValue();
8698 }
8699
8700 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8701   SDValue N0 = N->getOperand(0);
8702   EVT VT = N->getValueType(0);
8703
8704   // fold (fp_to_sint c1fp) -> c1
8705   if (isConstantFPBuildVectorOrConstantFP(N0))
8706     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8707
8708   return FoldIntToFPToInt(N, DAG);
8709 }
8710
8711 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8712   SDValue N0 = N->getOperand(0);
8713   EVT VT = N->getValueType(0);
8714
8715   // fold (fp_to_uint c1fp) -> c1
8716   if (isConstantFPBuildVectorOrConstantFP(N0))
8717     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8718
8719   return FoldIntToFPToInt(N, DAG);
8720 }
8721
8722 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8723   SDValue N0 = N->getOperand(0);
8724   SDValue N1 = N->getOperand(1);
8725   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8726   EVT VT = N->getValueType(0);
8727
8728   // fold (fp_round c1fp) -> c1fp
8729   if (N0CFP)
8730     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8731
8732   // fold (fp_round (fp_extend x)) -> x
8733   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8734     return N0.getOperand(0);
8735
8736   // fold (fp_round (fp_round x)) -> (fp_round x)
8737   if (N0.getOpcode() == ISD::FP_ROUND) {
8738     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8739     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8740     // If the first fp_round isn't a value preserving truncation, it might
8741     // introduce a tie in the second fp_round, that wouldn't occur in the
8742     // single-step fp_round we want to fold to.
8743     // In other words, double rounding isn't the same as rounding.
8744     // Also, this is a value preserving truncation iff both fp_round's are.
8745     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8746       SDLoc DL(N);
8747       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8748                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8749     }
8750   }
8751
8752   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8753   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8754     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8755                               N0.getOperand(0), N1);
8756     AddToWorklist(Tmp.getNode());
8757     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8758                        Tmp, N0.getOperand(1));
8759   }
8760
8761   return SDValue();
8762 }
8763
8764 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8765   SDValue N0 = N->getOperand(0);
8766   EVT VT = N->getValueType(0);
8767   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8768   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8769
8770   // fold (fp_round_inreg c1fp) -> c1fp
8771   if (N0CFP && isTypeLegal(EVT)) {
8772     SDLoc DL(N);
8773     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8774     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8775   }
8776
8777   return SDValue();
8778 }
8779
8780 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8781   SDValue N0 = N->getOperand(0);
8782   EVT VT = N->getValueType(0);
8783
8784   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8785   if (N->hasOneUse() &&
8786       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8787     return SDValue();
8788
8789   // fold (fp_extend c1fp) -> c1fp
8790   if (isConstantFPBuildVectorOrConstantFP(N0))
8791     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8792
8793   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8794   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8795       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8796     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8797
8798   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8799   // value of X.
8800   if (N0.getOpcode() == ISD::FP_ROUND
8801       && N0.getNode()->getConstantOperandVal(1) == 1) {
8802     SDValue In = N0.getOperand(0);
8803     if (In.getValueType() == VT) return In;
8804     if (VT.bitsLT(In.getValueType()))
8805       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8806                          In, N0.getOperand(1));
8807     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8808   }
8809
8810   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8811   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8812        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8813     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8814     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8815                                      LN0->getChain(),
8816                                      LN0->getBasePtr(), N0.getValueType(),
8817                                      LN0->getMemOperand());
8818     CombineTo(N, ExtLoad);
8819     CombineTo(N0.getNode(),
8820               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8821                           N0.getValueType(), ExtLoad,
8822                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8823               ExtLoad.getValue(1));
8824     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8825   }
8826
8827   return SDValue();
8828 }
8829
8830 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8831   SDValue N0 = N->getOperand(0);
8832   EVT VT = N->getValueType(0);
8833
8834   // fold (fceil c1) -> fceil(c1)
8835   if (isConstantFPBuildVectorOrConstantFP(N0))
8836     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8837
8838   return SDValue();
8839 }
8840
8841 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8842   SDValue N0 = N->getOperand(0);
8843   EVT VT = N->getValueType(0);
8844
8845   // fold (ftrunc c1) -> ftrunc(c1)
8846   if (isConstantFPBuildVectorOrConstantFP(N0))
8847     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8848
8849   return SDValue();
8850 }
8851
8852 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8853   SDValue N0 = N->getOperand(0);
8854   EVT VT = N->getValueType(0);
8855
8856   // fold (ffloor c1) -> ffloor(c1)
8857   if (isConstantFPBuildVectorOrConstantFP(N0))
8858     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8859
8860   return SDValue();
8861 }
8862
8863 // FIXME: FNEG and FABS have a lot in common; refactor.
8864 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8865   SDValue N0 = N->getOperand(0);
8866   EVT VT = N->getValueType(0);
8867
8868   // Constant fold FNEG.
8869   if (isConstantFPBuildVectorOrConstantFP(N0))
8870     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8871
8872   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8873                          &DAG.getTarget().Options))
8874     return GetNegatedExpression(N0, DAG, LegalOperations);
8875
8876   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8877   // constant pool values.
8878   if (!TLI.isFNegFree(VT) &&
8879       N0.getOpcode() == ISD::BITCAST &&
8880       N0.getNode()->hasOneUse()) {
8881     SDValue Int = N0.getOperand(0);
8882     EVT IntVT = Int.getValueType();
8883     if (IntVT.isInteger() && !IntVT.isVector()) {
8884       APInt SignMask;
8885       if (N0.getValueType().isVector()) {
8886         // For a vector, get a mask such as 0x80... per scalar element
8887         // and splat it.
8888         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8889         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8890       } else {
8891         // For a scalar, just generate 0x80...
8892         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8893       }
8894       SDLoc DL0(N0);
8895       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8896                         DAG.getConstant(SignMask, DL0, IntVT));
8897       AddToWorklist(Int.getNode());
8898       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8899     }
8900   }
8901
8902   // (fneg (fmul c, x)) -> (fmul -c, x)
8903   if (N0.getOpcode() == ISD::FMUL &&
8904       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8905     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8906     if (CFP1) {
8907       APFloat CVal = CFP1->getValueAPF();
8908       CVal.changeSign();
8909       if (Level >= AfterLegalizeDAG &&
8910           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8911            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8912         return DAG.getNode(
8913             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8914             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8915     }
8916   }
8917
8918   return SDValue();
8919 }
8920
8921 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8922   SDValue N0 = N->getOperand(0);
8923   SDValue N1 = N->getOperand(1);
8924   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8925   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8926
8927   if (N0CFP && N1CFP) {
8928     const APFloat &C0 = N0CFP->getValueAPF();
8929     const APFloat &C1 = N1CFP->getValueAPF();
8930     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8931   }
8932
8933   if (N0CFP) {
8934     EVT VT = N->getValueType(0);
8935     // Canonicalize to constant on RHS.
8936     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8937   }
8938
8939   return SDValue();
8940 }
8941
8942 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8943   SDValue N0 = N->getOperand(0);
8944   SDValue N1 = N->getOperand(1);
8945   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8946   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8947
8948   if (N0CFP && N1CFP) {
8949     const APFloat &C0 = N0CFP->getValueAPF();
8950     const APFloat &C1 = N1CFP->getValueAPF();
8951     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8952   }
8953
8954   if (N0CFP) {
8955     EVT VT = N->getValueType(0);
8956     // Canonicalize to constant on RHS.
8957     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8958   }
8959
8960   return SDValue();
8961 }
8962
8963 SDValue DAGCombiner::visitFABS(SDNode *N) {
8964   SDValue N0 = N->getOperand(0);
8965   EVT VT = N->getValueType(0);
8966
8967   // fold (fabs c1) -> fabs(c1)
8968   if (isConstantFPBuildVectorOrConstantFP(N0))
8969     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8970
8971   // fold (fabs (fabs x)) -> (fabs x)
8972   if (N0.getOpcode() == ISD::FABS)
8973     return N->getOperand(0);
8974
8975   // fold (fabs (fneg x)) -> (fabs x)
8976   // fold (fabs (fcopysign x, y)) -> (fabs x)
8977   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8978     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8979
8980   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8981   // constant pool values.
8982   if (!TLI.isFAbsFree(VT) &&
8983       N0.getOpcode() == ISD::BITCAST &&
8984       N0.getNode()->hasOneUse()) {
8985     SDValue Int = N0.getOperand(0);
8986     EVT IntVT = Int.getValueType();
8987     if (IntVT.isInteger() && !IntVT.isVector()) {
8988       APInt SignMask;
8989       if (N0.getValueType().isVector()) {
8990         // For a vector, get a mask such as 0x7f... per scalar element
8991         // and splat it.
8992         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8993         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8994       } else {
8995         // For a scalar, just generate 0x7f...
8996         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8997       }
8998       SDLoc DL(N0);
8999       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9000                         DAG.getConstant(SignMask, DL, IntVT));
9001       AddToWorklist(Int.getNode());
9002       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9003     }
9004   }
9005
9006   return SDValue();
9007 }
9008
9009 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9010   SDValue Chain = N->getOperand(0);
9011   SDValue N1 = N->getOperand(1);
9012   SDValue N2 = N->getOperand(2);
9013
9014   // If N is a constant we could fold this into a fallthrough or unconditional
9015   // branch. However that doesn't happen very often in normal code, because
9016   // Instcombine/SimplifyCFG should have handled the available opportunities.
9017   // If we did this folding here, it would be necessary to update the
9018   // MachineBasicBlock CFG, which is awkward.
9019
9020   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9021   // on the target.
9022   if (N1.getOpcode() == ISD::SETCC &&
9023       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9024                                    N1.getOperand(0).getValueType())) {
9025     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9026                        Chain, N1.getOperand(2),
9027                        N1.getOperand(0), N1.getOperand(1), N2);
9028   }
9029
9030   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9031       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9032        (N1.getOperand(0).hasOneUse() &&
9033         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9034     SDNode *Trunc = nullptr;
9035     if (N1.getOpcode() == ISD::TRUNCATE) {
9036       // Look pass the truncate.
9037       Trunc = N1.getNode();
9038       N1 = N1.getOperand(0);
9039     }
9040
9041     // Match this pattern so that we can generate simpler code:
9042     //
9043     //   %a = ...
9044     //   %b = and i32 %a, 2
9045     //   %c = srl i32 %b, 1
9046     //   brcond i32 %c ...
9047     //
9048     // into
9049     //
9050     //   %a = ...
9051     //   %b = and i32 %a, 2
9052     //   %c = setcc eq %b, 0
9053     //   brcond %c ...
9054     //
9055     // This applies only when the AND constant value has one bit set and the
9056     // SRL constant is equal to the log2 of the AND constant. The back-end is
9057     // smart enough to convert the result into a TEST/JMP sequence.
9058     SDValue Op0 = N1.getOperand(0);
9059     SDValue Op1 = N1.getOperand(1);
9060
9061     if (Op0.getOpcode() == ISD::AND &&
9062         Op1.getOpcode() == ISD::Constant) {
9063       SDValue AndOp1 = Op0.getOperand(1);
9064
9065       if (AndOp1.getOpcode() == ISD::Constant) {
9066         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9067
9068         if (AndConst.isPowerOf2() &&
9069             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9070           SDLoc DL(N);
9071           SDValue SetCC =
9072             DAG.getSetCC(DL,
9073                          getSetCCResultType(Op0.getValueType()),
9074                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9075                          ISD::SETNE);
9076
9077           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9078                                           MVT::Other, Chain, SetCC, N2);
9079           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9080           // will convert it back to (X & C1) >> C2.
9081           CombineTo(N, NewBRCond, false);
9082           // Truncate is dead.
9083           if (Trunc)
9084             deleteAndRecombine(Trunc);
9085           // Replace the uses of SRL with SETCC
9086           WorklistRemover DeadNodes(*this);
9087           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9088           deleteAndRecombine(N1.getNode());
9089           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9090         }
9091       }
9092     }
9093
9094     if (Trunc)
9095       // Restore N1 if the above transformation doesn't match.
9096       N1 = N->getOperand(1);
9097   }
9098
9099   // Transform br(xor(x, y)) -> br(x != y)
9100   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9101   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9102     SDNode *TheXor = N1.getNode();
9103     SDValue Op0 = TheXor->getOperand(0);
9104     SDValue Op1 = TheXor->getOperand(1);
9105     if (Op0.getOpcode() == Op1.getOpcode()) {
9106       // Avoid missing important xor optimizations.
9107       if (SDValue Tmp = visitXOR(TheXor)) {
9108         if (Tmp.getNode() != TheXor) {
9109           DEBUG(dbgs() << "\nReplacing.8 ";
9110                 TheXor->dump(&DAG);
9111                 dbgs() << "\nWith: ";
9112                 Tmp.getNode()->dump(&DAG);
9113                 dbgs() << '\n');
9114           WorklistRemover DeadNodes(*this);
9115           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9116           deleteAndRecombine(TheXor);
9117           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9118                              MVT::Other, Chain, Tmp, N2);
9119         }
9120
9121         // visitXOR has changed XOR's operands or replaced the XOR completely,
9122         // bail out.
9123         return SDValue(N, 0);
9124       }
9125     }
9126
9127     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9128       bool Equal = false;
9129       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9130           Op0.getOpcode() == ISD::XOR) {
9131         TheXor = Op0.getNode();
9132         Equal = true;
9133       }
9134
9135       EVT SetCCVT = N1.getValueType();
9136       if (LegalTypes)
9137         SetCCVT = getSetCCResultType(SetCCVT);
9138       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9139                                    SetCCVT,
9140                                    Op0, Op1,
9141                                    Equal ? ISD::SETEQ : ISD::SETNE);
9142       // Replace the uses of XOR with SETCC
9143       WorklistRemover DeadNodes(*this);
9144       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9145       deleteAndRecombine(N1.getNode());
9146       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9147                          MVT::Other, Chain, SetCC, N2);
9148     }
9149   }
9150
9151   return SDValue();
9152 }
9153
9154 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9155 //
9156 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9157   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9158   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9159
9160   // If N is a constant we could fold this into a fallthrough or unconditional
9161   // branch. However that doesn't happen very often in normal code, because
9162   // Instcombine/SimplifyCFG should have handled the available opportunities.
9163   // If we did this folding here, it would be necessary to update the
9164   // MachineBasicBlock CFG, which is awkward.
9165
9166   // Use SimplifySetCC to simplify SETCC's.
9167   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9168                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9169                                false);
9170   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9171
9172   // fold to a simpler setcc
9173   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9174     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9175                        N->getOperand(0), Simp.getOperand(2),
9176                        Simp.getOperand(0), Simp.getOperand(1),
9177                        N->getOperand(4));
9178
9179   return SDValue();
9180 }
9181
9182 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9183 /// and that N may be folded in the load / store addressing mode.
9184 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9185                                     SelectionDAG &DAG,
9186                                     const TargetLowering &TLI) {
9187   EVT VT;
9188   unsigned AS;
9189
9190   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9191     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9192       return false;
9193     VT = LD->getMemoryVT();
9194     AS = LD->getAddressSpace();
9195   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9196     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9197       return false;
9198     VT = ST->getMemoryVT();
9199     AS = ST->getAddressSpace();
9200   } else
9201     return false;
9202
9203   TargetLowering::AddrMode AM;
9204   if (N->getOpcode() == ISD::ADD) {
9205     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9206     if (Offset)
9207       // [reg +/- imm]
9208       AM.BaseOffs = Offset->getSExtValue();
9209     else
9210       // [reg +/- reg]
9211       AM.Scale = 1;
9212   } else if (N->getOpcode() == ISD::SUB) {
9213     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9214     if (Offset)
9215       // [reg +/- imm]
9216       AM.BaseOffs = -Offset->getSExtValue();
9217     else
9218       // [reg +/- reg]
9219       AM.Scale = 1;
9220   } else
9221     return false;
9222
9223   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9224                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9225 }
9226
9227 /// Try turning a load/store into a pre-indexed load/store when the base
9228 /// pointer is an add or subtract and it has other uses besides the load/store.
9229 /// After the transformation, the new indexed load/store has effectively folded
9230 /// the add/subtract in and all of its other uses are redirected to the
9231 /// new load/store.
9232 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9233   if (Level < AfterLegalizeDAG)
9234     return false;
9235
9236   bool isLoad = true;
9237   SDValue Ptr;
9238   EVT VT;
9239   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9240     if (LD->isIndexed())
9241       return false;
9242     VT = LD->getMemoryVT();
9243     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9244         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9245       return false;
9246     Ptr = LD->getBasePtr();
9247   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9248     if (ST->isIndexed())
9249       return false;
9250     VT = ST->getMemoryVT();
9251     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9252         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9253       return false;
9254     Ptr = ST->getBasePtr();
9255     isLoad = false;
9256   } else {
9257     return false;
9258   }
9259
9260   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9261   // out.  There is no reason to make this a preinc/predec.
9262   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9263       Ptr.getNode()->hasOneUse())
9264     return false;
9265
9266   // Ask the target to do addressing mode selection.
9267   SDValue BasePtr;
9268   SDValue Offset;
9269   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9270   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9271     return false;
9272
9273   // Backends without true r+i pre-indexed forms may need to pass a
9274   // constant base with a variable offset so that constant coercion
9275   // will work with the patterns in canonical form.
9276   bool Swapped = false;
9277   if (isa<ConstantSDNode>(BasePtr)) {
9278     std::swap(BasePtr, Offset);
9279     Swapped = true;
9280   }
9281
9282   // Don't create a indexed load / store with zero offset.
9283   if (isNullConstant(Offset))
9284     return false;
9285
9286   // Try turning it into a pre-indexed load / store except when:
9287   // 1) The new base ptr is a frame index.
9288   // 2) If N is a store and the new base ptr is either the same as or is a
9289   //    predecessor of the value being stored.
9290   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9291   //    that would create a cycle.
9292   // 4) All uses are load / store ops that use it as old base ptr.
9293
9294   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9295   // (plus the implicit offset) to a register to preinc anyway.
9296   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9297     return false;
9298
9299   // Check #2.
9300   if (!isLoad) {
9301     SDValue Val = cast<StoreSDNode>(N)->getValue();
9302     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9303       return false;
9304   }
9305
9306   // If the offset is a constant, there may be other adds of constants that
9307   // can be folded with this one. We should do this to avoid having to keep
9308   // a copy of the original base pointer.
9309   SmallVector<SDNode *, 16> OtherUses;
9310   if (isa<ConstantSDNode>(Offset))
9311     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9312                               UE = BasePtr.getNode()->use_end();
9313          UI != UE; ++UI) {
9314       SDUse &Use = UI.getUse();
9315       // Skip the use that is Ptr and uses of other results from BasePtr's
9316       // node (important for nodes that return multiple results).
9317       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9318         continue;
9319
9320       if (Use.getUser()->isPredecessorOf(N))
9321         continue;
9322
9323       if (Use.getUser()->getOpcode() != ISD::ADD &&
9324           Use.getUser()->getOpcode() != ISD::SUB) {
9325         OtherUses.clear();
9326         break;
9327       }
9328
9329       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9330       if (!isa<ConstantSDNode>(Op1)) {
9331         OtherUses.clear();
9332         break;
9333       }
9334
9335       // FIXME: In some cases, we can be smarter about this.
9336       if (Op1.getValueType() != Offset.getValueType()) {
9337         OtherUses.clear();
9338         break;
9339       }
9340
9341       OtherUses.push_back(Use.getUser());
9342     }
9343
9344   if (Swapped)
9345     std::swap(BasePtr, Offset);
9346
9347   // Now check for #3 and #4.
9348   bool RealUse = false;
9349
9350   // Caches for hasPredecessorHelper
9351   SmallPtrSet<const SDNode *, 32> Visited;
9352   SmallVector<const SDNode *, 16> Worklist;
9353
9354   for (SDNode *Use : Ptr.getNode()->uses()) {
9355     if (Use == N)
9356       continue;
9357     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9358       return false;
9359
9360     // If Ptr may be folded in addressing mode of other use, then it's
9361     // not profitable to do this transformation.
9362     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9363       RealUse = true;
9364   }
9365
9366   if (!RealUse)
9367     return false;
9368
9369   SDValue Result;
9370   if (isLoad)
9371     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9372                                 BasePtr, Offset, AM);
9373   else
9374     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9375                                  BasePtr, Offset, AM);
9376   ++PreIndexedNodes;
9377   ++NodesCombined;
9378   DEBUG(dbgs() << "\nReplacing.4 ";
9379         N->dump(&DAG);
9380         dbgs() << "\nWith: ";
9381         Result.getNode()->dump(&DAG);
9382         dbgs() << '\n');
9383   WorklistRemover DeadNodes(*this);
9384   if (isLoad) {
9385     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9386     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9387   } else {
9388     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9389   }
9390
9391   // Finally, since the node is now dead, remove it from the graph.
9392   deleteAndRecombine(N);
9393
9394   if (Swapped)
9395     std::swap(BasePtr, Offset);
9396
9397   // Replace other uses of BasePtr that can be updated to use Ptr
9398   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9399     unsigned OffsetIdx = 1;
9400     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9401       OffsetIdx = 0;
9402     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9403            BasePtr.getNode() && "Expected BasePtr operand");
9404
9405     // We need to replace ptr0 in the following expression:
9406     //   x0 * offset0 + y0 * ptr0 = t0
9407     // knowing that
9408     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9409     //
9410     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9411     // indexed load/store and the expresion that needs to be re-written.
9412     //
9413     // Therefore, we have:
9414     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9415
9416     ConstantSDNode *CN =
9417       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9418     int X0, X1, Y0, Y1;
9419     APInt Offset0 = CN->getAPIntValue();
9420     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9421
9422     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9423     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9424     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9425     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9426
9427     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9428
9429     APInt CNV = Offset0;
9430     if (X0 < 0) CNV = -CNV;
9431     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9432     else CNV = CNV - Offset1;
9433
9434     SDLoc DL(OtherUses[i]);
9435
9436     // We can now generate the new expression.
9437     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9438     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9439
9440     SDValue NewUse = DAG.getNode(Opcode,
9441                                  DL,
9442                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9443     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9444     deleteAndRecombine(OtherUses[i]);
9445   }
9446
9447   // Replace the uses of Ptr with uses of the updated base value.
9448   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9449   deleteAndRecombine(Ptr.getNode());
9450
9451   return true;
9452 }
9453
9454 /// Try to combine a load/store with a add/sub of the base pointer node into a
9455 /// post-indexed load/store. The transformation folded the add/subtract into the
9456 /// new indexed load/store effectively and all of its uses are redirected to the
9457 /// new load/store.
9458 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9459   if (Level < AfterLegalizeDAG)
9460     return false;
9461
9462   bool isLoad = true;
9463   SDValue Ptr;
9464   EVT VT;
9465   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9466     if (LD->isIndexed())
9467       return false;
9468     VT = LD->getMemoryVT();
9469     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9470         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9471       return false;
9472     Ptr = LD->getBasePtr();
9473   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9474     if (ST->isIndexed())
9475       return false;
9476     VT = ST->getMemoryVT();
9477     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9478         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9479       return false;
9480     Ptr = ST->getBasePtr();
9481     isLoad = false;
9482   } else {
9483     return false;
9484   }
9485
9486   if (Ptr.getNode()->hasOneUse())
9487     return false;
9488
9489   for (SDNode *Op : Ptr.getNode()->uses()) {
9490     if (Op == N ||
9491         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9492       continue;
9493
9494     SDValue BasePtr;
9495     SDValue Offset;
9496     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9497     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9498       // Don't create a indexed load / store with zero offset.
9499       if (isNullConstant(Offset))
9500         continue;
9501
9502       // Try turning it into a post-indexed load / store except when
9503       // 1) All uses are load / store ops that use it as base ptr (and
9504       //    it may be folded as addressing mmode).
9505       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9506       //    nor a successor of N. Otherwise, if Op is folded that would
9507       //    create a cycle.
9508
9509       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9510         continue;
9511
9512       // Check for #1.
9513       bool TryNext = false;
9514       for (SDNode *Use : BasePtr.getNode()->uses()) {
9515         if (Use == Ptr.getNode())
9516           continue;
9517
9518         // If all the uses are load / store addresses, then don't do the
9519         // transformation.
9520         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9521           bool RealUse = false;
9522           for (SDNode *UseUse : Use->uses()) {
9523             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9524               RealUse = true;
9525           }
9526
9527           if (!RealUse) {
9528             TryNext = true;
9529             break;
9530           }
9531         }
9532       }
9533
9534       if (TryNext)
9535         continue;
9536
9537       // Check for #2
9538       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9539         SDValue Result = isLoad
9540           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9541                                BasePtr, Offset, AM)
9542           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9543                                 BasePtr, Offset, AM);
9544         ++PostIndexedNodes;
9545         ++NodesCombined;
9546         DEBUG(dbgs() << "\nReplacing.5 ";
9547               N->dump(&DAG);
9548               dbgs() << "\nWith: ";
9549               Result.getNode()->dump(&DAG);
9550               dbgs() << '\n');
9551         WorklistRemover DeadNodes(*this);
9552         if (isLoad) {
9553           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9554           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9555         } else {
9556           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9557         }
9558
9559         // Finally, since the node is now dead, remove it from the graph.
9560         deleteAndRecombine(N);
9561
9562         // Replace the uses of Use with uses of the updated base value.
9563         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9564                                       Result.getValue(isLoad ? 1 : 0));
9565         deleteAndRecombine(Op);
9566         return true;
9567       }
9568     }
9569   }
9570
9571   return false;
9572 }
9573
9574 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9575 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9576   ISD::MemIndexedMode AM = LD->getAddressingMode();
9577   assert(AM != ISD::UNINDEXED);
9578   SDValue BP = LD->getOperand(1);
9579   SDValue Inc = LD->getOperand(2);
9580
9581   // Some backends use TargetConstants for load offsets, but don't expect
9582   // TargetConstants in general ADD nodes. We can convert these constants into
9583   // regular Constants (if the constant is not opaque).
9584   assert((Inc.getOpcode() != ISD::TargetConstant ||
9585           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9586          "Cannot split out indexing using opaque target constants");
9587   if (Inc.getOpcode() == ISD::TargetConstant) {
9588     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9589     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9590                           ConstInc->getValueType(0));
9591   }
9592
9593   unsigned Opc =
9594       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9595   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9596 }
9597
9598 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9599   LoadSDNode *LD  = cast<LoadSDNode>(N);
9600   SDValue Chain = LD->getChain();
9601   SDValue Ptr   = LD->getBasePtr();
9602
9603   // If load is not volatile and there are no uses of the loaded value (and
9604   // the updated indexed value in case of indexed loads), change uses of the
9605   // chain value into uses of the chain input (i.e. delete the dead load).
9606   if (!LD->isVolatile()) {
9607     if (N->getValueType(1) == MVT::Other) {
9608       // Unindexed loads.
9609       if (!N->hasAnyUseOfValue(0)) {
9610         // It's not safe to use the two value CombineTo variant here. e.g.
9611         // v1, chain2 = load chain1, loc
9612         // v2, chain3 = load chain2, loc
9613         // v3         = add v2, c
9614         // Now we replace use of chain2 with chain1.  This makes the second load
9615         // isomorphic to the one we are deleting, and thus makes this load live.
9616         DEBUG(dbgs() << "\nReplacing.6 ";
9617               N->dump(&DAG);
9618               dbgs() << "\nWith chain: ";
9619               Chain.getNode()->dump(&DAG);
9620               dbgs() << "\n");
9621         WorklistRemover DeadNodes(*this);
9622         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9623
9624         if (N->use_empty())
9625           deleteAndRecombine(N);
9626
9627         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9628       }
9629     } else {
9630       // Indexed loads.
9631       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9632
9633       // If this load has an opaque TargetConstant offset, then we cannot split
9634       // the indexing into an add/sub directly (that TargetConstant may not be
9635       // valid for a different type of node, and we cannot convert an opaque
9636       // target constant into a regular constant).
9637       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9638                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9639
9640       if (!N->hasAnyUseOfValue(0) &&
9641           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9642         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9643         SDValue Index;
9644         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9645           Index = SplitIndexingFromLoad(LD);
9646           // Try to fold the base pointer arithmetic into subsequent loads and
9647           // stores.
9648           AddUsersToWorklist(N);
9649         } else
9650           Index = DAG.getUNDEF(N->getValueType(1));
9651         DEBUG(dbgs() << "\nReplacing.7 ";
9652               N->dump(&DAG);
9653               dbgs() << "\nWith: ";
9654               Undef.getNode()->dump(&DAG);
9655               dbgs() << " and 2 other values\n");
9656         WorklistRemover DeadNodes(*this);
9657         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9658         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9659         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9660         deleteAndRecombine(N);
9661         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9662       }
9663     }
9664   }
9665
9666   // If this load is directly stored, replace the load value with the stored
9667   // value.
9668   // TODO: Handle store large -> read small portion.
9669   // TODO: Handle TRUNCSTORE/LOADEXT
9670   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9671     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9672       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9673       if (PrevST->getBasePtr() == Ptr &&
9674           PrevST->getValue().getValueType() == N->getValueType(0))
9675       return CombineTo(N, Chain.getOperand(1), Chain);
9676     }
9677   }
9678
9679   // Try to infer better alignment information than the load already has.
9680   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9681     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9682       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9683         SDValue NewLoad =
9684                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9685                               LD->getValueType(0),
9686                               Chain, Ptr, LD->getPointerInfo(),
9687                               LD->getMemoryVT(),
9688                               LD->isVolatile(), LD->isNonTemporal(),
9689                               LD->isInvariant(), Align, LD->getAAInfo());
9690         if (NewLoad.getNode() != N)
9691           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9692       }
9693     }
9694   }
9695
9696   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9697                                                   : DAG.getSubtarget().useAA();
9698 #ifndef NDEBUG
9699   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9700       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9701     UseAA = false;
9702 #endif
9703   if (UseAA && LD->isUnindexed()) {
9704     // Walk up chain skipping non-aliasing memory nodes.
9705     SDValue BetterChain = FindBetterChain(N, Chain);
9706
9707     // If there is a better chain.
9708     if (Chain != BetterChain) {
9709       SDValue ReplLoad;
9710
9711       // Replace the chain to void dependency.
9712       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9713         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9714                                BetterChain, Ptr, LD->getMemOperand());
9715       } else {
9716         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9717                                   LD->getValueType(0),
9718                                   BetterChain, Ptr, LD->getMemoryVT(),
9719                                   LD->getMemOperand());
9720       }
9721
9722       // Create token factor to keep old chain connected.
9723       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9724                                   MVT::Other, Chain, ReplLoad.getValue(1));
9725
9726       // Make sure the new and old chains are cleaned up.
9727       AddToWorklist(Token.getNode());
9728
9729       // Replace uses with load result and token factor. Don't add users
9730       // to work list.
9731       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9732     }
9733   }
9734
9735   // Try transforming N to an indexed load.
9736   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9737     return SDValue(N, 0);
9738
9739   // Try to slice up N to more direct loads if the slices are mapped to
9740   // different register banks or pairing can take place.
9741   if (SliceUpLoad(N))
9742     return SDValue(N, 0);
9743
9744   return SDValue();
9745 }
9746
9747 namespace {
9748 /// \brief Helper structure used to slice a load in smaller loads.
9749 /// Basically a slice is obtained from the following sequence:
9750 /// Origin = load Ty1, Base
9751 /// Shift = srl Ty1 Origin, CstTy Amount
9752 /// Inst = trunc Shift to Ty2
9753 ///
9754 /// Then, it will be rewriten into:
9755 /// Slice = load SliceTy, Base + SliceOffset
9756 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9757 ///
9758 /// SliceTy is deduced from the number of bits that are actually used to
9759 /// build Inst.
9760 struct LoadedSlice {
9761   /// \brief Helper structure used to compute the cost of a slice.
9762   struct Cost {
9763     /// Are we optimizing for code size.
9764     bool ForCodeSize;
9765     /// Various cost.
9766     unsigned Loads;
9767     unsigned Truncates;
9768     unsigned CrossRegisterBanksCopies;
9769     unsigned ZExts;
9770     unsigned Shift;
9771
9772     Cost(bool ForCodeSize = false)
9773         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9774           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9775
9776     /// \brief Get the cost of one isolated slice.
9777     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9778         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9779           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9780       EVT TruncType = LS.Inst->getValueType(0);
9781       EVT LoadedType = LS.getLoadedType();
9782       if (TruncType != LoadedType &&
9783           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9784         ZExts = 1;
9785     }
9786
9787     /// \brief Account for slicing gain in the current cost.
9788     /// Slicing provide a few gains like removing a shift or a
9789     /// truncate. This method allows to grow the cost of the original
9790     /// load with the gain from this slice.
9791     void addSliceGain(const LoadedSlice &LS) {
9792       // Each slice saves a truncate.
9793       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9794       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9795                               LS.Inst->getValueType(0)))
9796         ++Truncates;
9797       // If there is a shift amount, this slice gets rid of it.
9798       if (LS.Shift)
9799         ++Shift;
9800       // If this slice can merge a cross register bank copy, account for it.
9801       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9802         ++CrossRegisterBanksCopies;
9803     }
9804
9805     Cost &operator+=(const Cost &RHS) {
9806       Loads += RHS.Loads;
9807       Truncates += RHS.Truncates;
9808       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9809       ZExts += RHS.ZExts;
9810       Shift += RHS.Shift;
9811       return *this;
9812     }
9813
9814     bool operator==(const Cost &RHS) const {
9815       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9816              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9817              ZExts == RHS.ZExts && Shift == RHS.Shift;
9818     }
9819
9820     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9821
9822     bool operator<(const Cost &RHS) const {
9823       // Assume cross register banks copies are as expensive as loads.
9824       // FIXME: Do we want some more target hooks?
9825       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9826       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9827       // Unless we are optimizing for code size, consider the
9828       // expensive operation first.
9829       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9830         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9831       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9832              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9833     }
9834
9835     bool operator>(const Cost &RHS) const { return RHS < *this; }
9836
9837     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9838
9839     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9840   };
9841   // The last instruction that represent the slice. This should be a
9842   // truncate instruction.
9843   SDNode *Inst;
9844   // The original load instruction.
9845   LoadSDNode *Origin;
9846   // The right shift amount in bits from the original load.
9847   unsigned Shift;
9848   // The DAG from which Origin came from.
9849   // This is used to get some contextual information about legal types, etc.
9850   SelectionDAG *DAG;
9851
9852   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9853               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9854       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9855
9856   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9857   /// \return Result is \p BitWidth and has used bits set to 1 and
9858   ///         not used bits set to 0.
9859   APInt getUsedBits() const {
9860     // Reproduce the trunc(lshr) sequence:
9861     // - Start from the truncated value.
9862     // - Zero extend to the desired bit width.
9863     // - Shift left.
9864     assert(Origin && "No original load to compare against.");
9865     unsigned BitWidth = Origin->getValueSizeInBits(0);
9866     assert(Inst && "This slice is not bound to an instruction");
9867     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9868            "Extracted slice is bigger than the whole type!");
9869     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9870     UsedBits.setAllBits();
9871     UsedBits = UsedBits.zext(BitWidth);
9872     UsedBits <<= Shift;
9873     return UsedBits;
9874   }
9875
9876   /// \brief Get the size of the slice to be loaded in bytes.
9877   unsigned getLoadedSize() const {
9878     unsigned SliceSize = getUsedBits().countPopulation();
9879     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9880     return SliceSize / 8;
9881   }
9882
9883   /// \brief Get the type that will be loaded for this slice.
9884   /// Note: This may not be the final type for the slice.
9885   EVT getLoadedType() const {
9886     assert(DAG && "Missing context");
9887     LLVMContext &Ctxt = *DAG->getContext();
9888     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9889   }
9890
9891   /// \brief Get the alignment of the load used for this slice.
9892   unsigned getAlignment() const {
9893     unsigned Alignment = Origin->getAlignment();
9894     unsigned Offset = getOffsetFromBase();
9895     if (Offset != 0)
9896       Alignment = MinAlign(Alignment, Alignment + Offset);
9897     return Alignment;
9898   }
9899
9900   /// \brief Check if this slice can be rewritten with legal operations.
9901   bool isLegal() const {
9902     // An invalid slice is not legal.
9903     if (!Origin || !Inst || !DAG)
9904       return false;
9905
9906     // Offsets are for indexed load only, we do not handle that.
9907     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9908       return false;
9909
9910     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9911
9912     // Check that the type is legal.
9913     EVT SliceType = getLoadedType();
9914     if (!TLI.isTypeLegal(SliceType))
9915       return false;
9916
9917     // Check that the load is legal for this type.
9918     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9919       return false;
9920
9921     // Check that the offset can be computed.
9922     // 1. Check its type.
9923     EVT PtrType = Origin->getBasePtr().getValueType();
9924     if (PtrType == MVT::Untyped || PtrType.isExtended())
9925       return false;
9926
9927     // 2. Check that it fits in the immediate.
9928     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9929       return false;
9930
9931     // 3. Check that the computation is legal.
9932     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9933       return false;
9934
9935     // Check that the zext is legal if it needs one.
9936     EVT TruncateType = Inst->getValueType(0);
9937     if (TruncateType != SliceType &&
9938         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9939       return false;
9940
9941     return true;
9942   }
9943
9944   /// \brief Get the offset in bytes of this slice in the original chunk of
9945   /// bits.
9946   /// \pre DAG != nullptr.
9947   uint64_t getOffsetFromBase() const {
9948     assert(DAG && "Missing context.");
9949     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9950     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9951     uint64_t Offset = Shift / 8;
9952     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9953     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9954            "The size of the original loaded type is not a multiple of a"
9955            " byte.");
9956     // If Offset is bigger than TySizeInBytes, it means we are loading all
9957     // zeros. This should have been optimized before in the process.
9958     assert(TySizeInBytes > Offset &&
9959            "Invalid shift amount for given loaded size");
9960     if (IsBigEndian)
9961       Offset = TySizeInBytes - Offset - getLoadedSize();
9962     return Offset;
9963   }
9964
9965   /// \brief Generate the sequence of instructions to load the slice
9966   /// represented by this object and redirect the uses of this slice to
9967   /// this new sequence of instructions.
9968   /// \pre this->Inst && this->Origin are valid Instructions and this
9969   /// object passed the legal check: LoadedSlice::isLegal returned true.
9970   /// \return The last instruction of the sequence used to load the slice.
9971   SDValue loadSlice() const {
9972     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9973     const SDValue &OldBaseAddr = Origin->getBasePtr();
9974     SDValue BaseAddr = OldBaseAddr;
9975     // Get the offset in that chunk of bytes w.r.t. the endianess.
9976     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9977     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9978     if (Offset) {
9979       // BaseAddr = BaseAddr + Offset.
9980       EVT ArithType = BaseAddr.getValueType();
9981       SDLoc DL(Origin);
9982       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9983                               DAG->getConstant(Offset, DL, ArithType));
9984     }
9985
9986     // Create the type of the loaded slice according to its size.
9987     EVT SliceType = getLoadedType();
9988
9989     // Create the load for the slice.
9990     SDValue LastInst = DAG->getLoad(
9991         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9992         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9993         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9994     // If the final type is not the same as the loaded type, this means that
9995     // we have to pad with zero. Create a zero extend for that.
9996     EVT FinalType = Inst->getValueType(0);
9997     if (SliceType != FinalType)
9998       LastInst =
9999           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10000     return LastInst;
10001   }
10002
10003   /// \brief Check if this slice can be merged with an expensive cross register
10004   /// bank copy. E.g.,
10005   /// i = load i32
10006   /// f = bitcast i32 i to float
10007   bool canMergeExpensiveCrossRegisterBankCopy() const {
10008     if (!Inst || !Inst->hasOneUse())
10009       return false;
10010     SDNode *Use = *Inst->use_begin();
10011     if (Use->getOpcode() != ISD::BITCAST)
10012       return false;
10013     assert(DAG && "Missing context");
10014     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10015     EVT ResVT = Use->getValueType(0);
10016     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10017     const TargetRegisterClass *ArgRC =
10018         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10019     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10020       return false;
10021
10022     // At this point, we know that we perform a cross-register-bank copy.
10023     // Check if it is expensive.
10024     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10025     // Assume bitcasts are cheap, unless both register classes do not
10026     // explicitly share a common sub class.
10027     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10028       return false;
10029
10030     // Check if it will be merged with the load.
10031     // 1. Check the alignment constraint.
10032     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10033         ResVT.getTypeForEVT(*DAG->getContext()));
10034
10035     if (RequiredAlignment > getAlignment())
10036       return false;
10037
10038     // 2. Check that the load is a legal operation for that type.
10039     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10040       return false;
10041
10042     // 3. Check that we do not have a zext in the way.
10043     if (Inst->getValueType(0) != getLoadedType())
10044       return false;
10045
10046     return true;
10047   }
10048 };
10049 }
10050
10051 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10052 /// \p UsedBits looks like 0..0 1..1 0..0.
10053 static bool areUsedBitsDense(const APInt &UsedBits) {
10054   // If all the bits are one, this is dense!
10055   if (UsedBits.isAllOnesValue())
10056     return true;
10057
10058   // Get rid of the unused bits on the right.
10059   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10060   // Get rid of the unused bits on the left.
10061   if (NarrowedUsedBits.countLeadingZeros())
10062     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10063   // Check that the chunk of bits is completely used.
10064   return NarrowedUsedBits.isAllOnesValue();
10065 }
10066
10067 /// \brief Check whether or not \p First and \p Second are next to each other
10068 /// in memory. This means that there is no hole between the bits loaded
10069 /// by \p First and the bits loaded by \p Second.
10070 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10071                                      const LoadedSlice &Second) {
10072   assert(First.Origin == Second.Origin && First.Origin &&
10073          "Unable to match different memory origins.");
10074   APInt UsedBits = First.getUsedBits();
10075   assert((UsedBits & Second.getUsedBits()) == 0 &&
10076          "Slices are not supposed to overlap.");
10077   UsedBits |= Second.getUsedBits();
10078   return areUsedBitsDense(UsedBits);
10079 }
10080
10081 /// \brief Adjust the \p GlobalLSCost according to the target
10082 /// paring capabilities and the layout of the slices.
10083 /// \pre \p GlobalLSCost should account for at least as many loads as
10084 /// there is in the slices in \p LoadedSlices.
10085 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10086                                  LoadedSlice::Cost &GlobalLSCost) {
10087   unsigned NumberOfSlices = LoadedSlices.size();
10088   // If there is less than 2 elements, no pairing is possible.
10089   if (NumberOfSlices < 2)
10090     return;
10091
10092   // Sort the slices so that elements that are likely to be next to each
10093   // other in memory are next to each other in the list.
10094   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10095             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10096     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10097     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10098   });
10099   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10100   // First (resp. Second) is the first (resp. Second) potentially candidate
10101   // to be placed in a paired load.
10102   const LoadedSlice *First = nullptr;
10103   const LoadedSlice *Second = nullptr;
10104   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10105                 // Set the beginning of the pair.
10106                                                            First = Second) {
10107
10108     Second = &LoadedSlices[CurrSlice];
10109
10110     // If First is NULL, it means we start a new pair.
10111     // Get to the next slice.
10112     if (!First)
10113       continue;
10114
10115     EVT LoadedType = First->getLoadedType();
10116
10117     // If the types of the slices are different, we cannot pair them.
10118     if (LoadedType != Second->getLoadedType())
10119       continue;
10120
10121     // Check if the target supplies paired loads for this type.
10122     unsigned RequiredAlignment = 0;
10123     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10124       // move to the next pair, this type is hopeless.
10125       Second = nullptr;
10126       continue;
10127     }
10128     // Check if we meet the alignment requirement.
10129     if (RequiredAlignment > First->getAlignment())
10130       continue;
10131
10132     // Check that both loads are next to each other in memory.
10133     if (!areSlicesNextToEachOther(*First, *Second))
10134       continue;
10135
10136     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10137     --GlobalLSCost.Loads;
10138     // Move to the next pair.
10139     Second = nullptr;
10140   }
10141 }
10142
10143 /// \brief Check the profitability of all involved LoadedSlice.
10144 /// Currently, it is considered profitable if there is exactly two
10145 /// involved slices (1) which are (2) next to each other in memory, and
10146 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10147 ///
10148 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10149 /// the elements themselves.
10150 ///
10151 /// FIXME: When the cost model will be mature enough, we can relax
10152 /// constraints (1) and (2).
10153 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10154                                 const APInt &UsedBits, bool ForCodeSize) {
10155   unsigned NumberOfSlices = LoadedSlices.size();
10156   if (StressLoadSlicing)
10157     return NumberOfSlices > 1;
10158
10159   // Check (1).
10160   if (NumberOfSlices != 2)
10161     return false;
10162
10163   // Check (2).
10164   if (!areUsedBitsDense(UsedBits))
10165     return false;
10166
10167   // Check (3).
10168   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10169   // The original code has one big load.
10170   OrigCost.Loads = 1;
10171   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10172     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10173     // Accumulate the cost of all the slices.
10174     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10175     GlobalSlicingCost += SliceCost;
10176
10177     // Account as cost in the original configuration the gain obtained
10178     // with the current slices.
10179     OrigCost.addSliceGain(LS);
10180   }
10181
10182   // If the target supports paired load, adjust the cost accordingly.
10183   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10184   return OrigCost > GlobalSlicingCost;
10185 }
10186
10187 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10188 /// operations, split it in the various pieces being extracted.
10189 ///
10190 /// This sort of thing is introduced by SROA.
10191 /// This slicing takes care not to insert overlapping loads.
10192 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10193 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10194   if (Level < AfterLegalizeDAG)
10195     return false;
10196
10197   LoadSDNode *LD = cast<LoadSDNode>(N);
10198   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10199       !LD->getValueType(0).isInteger())
10200     return false;
10201
10202   // Keep track of already used bits to detect overlapping values.
10203   // In that case, we will just abort the transformation.
10204   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10205
10206   SmallVector<LoadedSlice, 4> LoadedSlices;
10207
10208   // Check if this load is used as several smaller chunks of bits.
10209   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10210   // of computation for each trunc.
10211   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10212        UI != UIEnd; ++UI) {
10213     // Skip the uses of the chain.
10214     if (UI.getUse().getResNo() != 0)
10215       continue;
10216
10217     SDNode *User = *UI;
10218     unsigned Shift = 0;
10219
10220     // Check if this is a trunc(lshr).
10221     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10222         isa<ConstantSDNode>(User->getOperand(1))) {
10223       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10224       User = *User->use_begin();
10225     }
10226
10227     // At this point, User is a Truncate, iff we encountered, trunc or
10228     // trunc(lshr).
10229     if (User->getOpcode() != ISD::TRUNCATE)
10230       return false;
10231
10232     // The width of the type must be a power of 2 and greater than 8-bits.
10233     // Otherwise the load cannot be represented in LLVM IR.
10234     // Moreover, if we shifted with a non-8-bits multiple, the slice
10235     // will be across several bytes. We do not support that.
10236     unsigned Width = User->getValueSizeInBits(0);
10237     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10238       return 0;
10239
10240     // Build the slice for this chain of computations.
10241     LoadedSlice LS(User, LD, Shift, &DAG);
10242     APInt CurrentUsedBits = LS.getUsedBits();
10243
10244     // Check if this slice overlaps with another.
10245     if ((CurrentUsedBits & UsedBits) != 0)
10246       return false;
10247     // Update the bits used globally.
10248     UsedBits |= CurrentUsedBits;
10249
10250     // Check if the new slice would be legal.
10251     if (!LS.isLegal())
10252       return false;
10253
10254     // Record the slice.
10255     LoadedSlices.push_back(LS);
10256   }
10257
10258   // Abort slicing if it does not seem to be profitable.
10259   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10260     return false;
10261
10262   ++SlicedLoads;
10263
10264   // Rewrite each chain to use an independent load.
10265   // By construction, each chain can be represented by a unique load.
10266
10267   // Prepare the argument for the new token factor for all the slices.
10268   SmallVector<SDValue, 8> ArgChains;
10269   for (SmallVectorImpl<LoadedSlice>::const_iterator
10270            LSIt = LoadedSlices.begin(),
10271            LSItEnd = LoadedSlices.end();
10272        LSIt != LSItEnd; ++LSIt) {
10273     SDValue SliceInst = LSIt->loadSlice();
10274     CombineTo(LSIt->Inst, SliceInst, true);
10275     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10276       SliceInst = SliceInst.getOperand(0);
10277     assert(SliceInst->getOpcode() == ISD::LOAD &&
10278            "It takes more than a zext to get to the loaded slice!!");
10279     ArgChains.push_back(SliceInst.getValue(1));
10280   }
10281
10282   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10283                               ArgChains);
10284   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10285   return true;
10286 }
10287
10288 /// Check to see if V is (and load (ptr), imm), where the load is having
10289 /// specific bytes cleared out.  If so, return the byte size being masked out
10290 /// and the shift amount.
10291 static std::pair<unsigned, unsigned>
10292 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10293   std::pair<unsigned, unsigned> Result(0, 0);
10294
10295   // Check for the structure we're looking for.
10296   if (V->getOpcode() != ISD::AND ||
10297       !isa<ConstantSDNode>(V->getOperand(1)) ||
10298       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10299     return Result;
10300
10301   // Check the chain and pointer.
10302   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10303   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10304
10305   // The store should be chained directly to the load or be an operand of a
10306   // tokenfactor.
10307   if (LD == Chain.getNode())
10308     ; // ok.
10309   else if (Chain->getOpcode() != ISD::TokenFactor)
10310     return Result; // Fail.
10311   else {
10312     bool isOk = false;
10313     for (const SDValue &ChainOp : Chain->op_values())
10314       if (ChainOp.getNode() == LD) {
10315         isOk = true;
10316         break;
10317       }
10318     if (!isOk) return Result;
10319   }
10320
10321   // This only handles simple types.
10322   if (V.getValueType() != MVT::i16 &&
10323       V.getValueType() != MVT::i32 &&
10324       V.getValueType() != MVT::i64)
10325     return Result;
10326
10327   // Check the constant mask.  Invert it so that the bits being masked out are
10328   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10329   // follow the sign bit for uniformity.
10330   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10331   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10332   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10333   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10334   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10335   if (NotMaskLZ == 64) return Result;  // All zero mask.
10336
10337   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10338   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10339     return Result;
10340
10341   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10342   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10343     NotMaskLZ -= 64-V.getValueSizeInBits();
10344
10345   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10346   switch (MaskedBytes) {
10347   case 1:
10348   case 2:
10349   case 4: break;
10350   default: return Result; // All one mask, or 5-byte mask.
10351   }
10352
10353   // Verify that the first bit starts at a multiple of mask so that the access
10354   // is aligned the same as the access width.
10355   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10356
10357   Result.first = MaskedBytes;
10358   Result.second = NotMaskTZ/8;
10359   return Result;
10360 }
10361
10362
10363 /// Check to see if IVal is something that provides a value as specified by
10364 /// MaskInfo. If so, replace the specified store with a narrower store of
10365 /// truncated IVal.
10366 static SDNode *
10367 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10368                                 SDValue IVal, StoreSDNode *St,
10369                                 DAGCombiner *DC) {
10370   unsigned NumBytes = MaskInfo.first;
10371   unsigned ByteShift = MaskInfo.second;
10372   SelectionDAG &DAG = DC->getDAG();
10373
10374   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10375   // that uses this.  If not, this is not a replacement.
10376   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10377                                   ByteShift*8, (ByteShift+NumBytes)*8);
10378   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10379
10380   // Check that it is legal on the target to do this.  It is legal if the new
10381   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10382   // legalization.
10383   MVT VT = MVT::getIntegerVT(NumBytes*8);
10384   if (!DC->isTypeLegal(VT))
10385     return nullptr;
10386
10387   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10388   // shifted by ByteShift and truncated down to NumBytes.
10389   if (ByteShift) {
10390     SDLoc DL(IVal);
10391     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10392                        DAG.getConstant(ByteShift*8, DL,
10393                                     DC->getShiftAmountTy(IVal.getValueType())));
10394   }
10395
10396   // Figure out the offset for the store and the alignment of the access.
10397   unsigned StOffset;
10398   unsigned NewAlign = St->getAlignment();
10399
10400   if (DAG.getDataLayout().isLittleEndian())
10401     StOffset = ByteShift;
10402   else
10403     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10404
10405   SDValue Ptr = St->getBasePtr();
10406   if (StOffset) {
10407     SDLoc DL(IVal);
10408     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10409                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10410     NewAlign = MinAlign(NewAlign, StOffset);
10411   }
10412
10413   // Truncate down to the new size.
10414   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10415
10416   ++OpsNarrowed;
10417   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10418                       St->getPointerInfo().getWithOffset(StOffset),
10419                       false, false, NewAlign).getNode();
10420 }
10421
10422
10423 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10424 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10425 /// narrowing the load and store if it would end up being a win for performance
10426 /// or code size.
10427 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10428   StoreSDNode *ST  = cast<StoreSDNode>(N);
10429   if (ST->isVolatile())
10430     return SDValue();
10431
10432   SDValue Chain = ST->getChain();
10433   SDValue Value = ST->getValue();
10434   SDValue Ptr   = ST->getBasePtr();
10435   EVT VT = Value.getValueType();
10436
10437   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10438     return SDValue();
10439
10440   unsigned Opc = Value.getOpcode();
10441
10442   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10443   // is a byte mask indicating a consecutive number of bytes, check to see if
10444   // Y is known to provide just those bytes.  If so, we try to replace the
10445   // load + replace + store sequence with a single (narrower) store, which makes
10446   // the load dead.
10447   if (Opc == ISD::OR) {
10448     std::pair<unsigned, unsigned> MaskedLoad;
10449     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10450     if (MaskedLoad.first)
10451       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10452                                                   Value.getOperand(1), ST,this))
10453         return SDValue(NewST, 0);
10454
10455     // Or is commutative, so try swapping X and Y.
10456     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10457     if (MaskedLoad.first)
10458       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10459                                                   Value.getOperand(0), ST,this))
10460         return SDValue(NewST, 0);
10461   }
10462
10463   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10464       Value.getOperand(1).getOpcode() != ISD::Constant)
10465     return SDValue();
10466
10467   SDValue N0 = Value.getOperand(0);
10468   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10469       Chain == SDValue(N0.getNode(), 1)) {
10470     LoadSDNode *LD = cast<LoadSDNode>(N0);
10471     if (LD->getBasePtr() != Ptr ||
10472         LD->getPointerInfo().getAddrSpace() !=
10473         ST->getPointerInfo().getAddrSpace())
10474       return SDValue();
10475
10476     // Find the type to narrow it the load / op / store to.
10477     SDValue N1 = Value.getOperand(1);
10478     unsigned BitWidth = N1.getValueSizeInBits();
10479     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10480     if (Opc == ISD::AND)
10481       Imm ^= APInt::getAllOnesValue(BitWidth);
10482     if (Imm == 0 || Imm.isAllOnesValue())
10483       return SDValue();
10484     unsigned ShAmt = Imm.countTrailingZeros();
10485     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10486     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10487     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10488     // The narrowing should be profitable, the load/store operation should be
10489     // legal (or custom) and the store size should be equal to the NewVT width.
10490     while (NewBW < BitWidth &&
10491            (NewVT.getStoreSizeInBits() != NewBW ||
10492             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10493             !TLI.isNarrowingProfitable(VT, NewVT))) {
10494       NewBW = NextPowerOf2(NewBW);
10495       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10496     }
10497     if (NewBW >= BitWidth)
10498       return SDValue();
10499
10500     // If the lsb changed does not start at the type bitwidth boundary,
10501     // start at the previous one.
10502     if (ShAmt % NewBW)
10503       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10504     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10505                                    std::min(BitWidth, ShAmt + NewBW));
10506     if ((Imm & Mask) == Imm) {
10507       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10508       if (Opc == ISD::AND)
10509         NewImm ^= APInt::getAllOnesValue(NewBW);
10510       uint64_t PtrOff = ShAmt / 8;
10511       // For big endian targets, we need to adjust the offset to the pointer to
10512       // load the correct bytes.
10513       if (DAG.getDataLayout().isBigEndian())
10514         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10515
10516       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10517       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10518       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10519         return SDValue();
10520
10521       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10522                                    Ptr.getValueType(), Ptr,
10523                                    DAG.getConstant(PtrOff, SDLoc(LD),
10524                                                    Ptr.getValueType()));
10525       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10526                                   LD->getChain(), NewPtr,
10527                                   LD->getPointerInfo().getWithOffset(PtrOff),
10528                                   LD->isVolatile(), LD->isNonTemporal(),
10529                                   LD->isInvariant(), NewAlign,
10530                                   LD->getAAInfo());
10531       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10532                                    DAG.getConstant(NewImm, SDLoc(Value),
10533                                                    NewVT));
10534       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10535                                    NewVal, NewPtr,
10536                                    ST->getPointerInfo().getWithOffset(PtrOff),
10537                                    false, false, NewAlign);
10538
10539       AddToWorklist(NewPtr.getNode());
10540       AddToWorklist(NewLD.getNode());
10541       AddToWorklist(NewVal.getNode());
10542       WorklistRemover DeadNodes(*this);
10543       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10544       ++OpsNarrowed;
10545       return NewST;
10546     }
10547   }
10548
10549   return SDValue();
10550 }
10551
10552 /// For a given floating point load / store pair, if the load value isn't used
10553 /// by any other operations, then consider transforming the pair to integer
10554 /// load / store operations if the target deems the transformation profitable.
10555 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10556   StoreSDNode *ST  = cast<StoreSDNode>(N);
10557   SDValue Chain = ST->getChain();
10558   SDValue Value = ST->getValue();
10559   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10560       Value.hasOneUse() &&
10561       Chain == SDValue(Value.getNode(), 1)) {
10562     LoadSDNode *LD = cast<LoadSDNode>(Value);
10563     EVT VT = LD->getMemoryVT();
10564     if (!VT.isFloatingPoint() ||
10565         VT != ST->getMemoryVT() ||
10566         LD->isNonTemporal() ||
10567         ST->isNonTemporal() ||
10568         LD->getPointerInfo().getAddrSpace() != 0 ||
10569         ST->getPointerInfo().getAddrSpace() != 0)
10570       return SDValue();
10571
10572     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10573     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10574         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10575         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10576         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10577       return SDValue();
10578
10579     unsigned LDAlign = LD->getAlignment();
10580     unsigned STAlign = ST->getAlignment();
10581     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10582     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10583     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10584       return SDValue();
10585
10586     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10587                                 LD->getChain(), LD->getBasePtr(),
10588                                 LD->getPointerInfo(),
10589                                 false, false, false, LDAlign);
10590
10591     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10592                                  NewLD, ST->getBasePtr(),
10593                                  ST->getPointerInfo(),
10594                                  false, false, STAlign);
10595
10596     AddToWorklist(NewLD.getNode());
10597     AddToWorklist(NewST.getNode());
10598     WorklistRemover DeadNodes(*this);
10599     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10600     ++LdStFP2Int;
10601     return NewST;
10602   }
10603
10604   return SDValue();
10605 }
10606
10607 namespace {
10608 /// Helper struct to parse and store a memory address as base + index + offset.
10609 /// We ignore sign extensions when it is safe to do so.
10610 /// The following two expressions are not equivalent. To differentiate we need
10611 /// to store whether there was a sign extension involved in the index
10612 /// computation.
10613 ///  (load (i64 add (i64 copyfromreg %c)
10614 ///                 (i64 signextend (add (i8 load %index)
10615 ///                                      (i8 1))))
10616 /// vs
10617 ///
10618 /// (load (i64 add (i64 copyfromreg %c)
10619 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10620 ///                                         (i32 1)))))
10621 struct BaseIndexOffset {
10622   SDValue Base;
10623   SDValue Index;
10624   int64_t Offset;
10625   bool IsIndexSignExt;
10626
10627   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10628
10629   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10630                   bool IsIndexSignExt) :
10631     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10632
10633   bool equalBaseIndex(const BaseIndexOffset &Other) {
10634     return Other.Base == Base && Other.Index == Index &&
10635       Other.IsIndexSignExt == IsIndexSignExt;
10636   }
10637
10638   /// Parses tree in Ptr for base, index, offset addresses.
10639   static BaseIndexOffset match(SDValue Ptr) {
10640     bool IsIndexSignExt = false;
10641
10642     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10643     // instruction, then it could be just the BASE or everything else we don't
10644     // know how to handle. Just use Ptr as BASE and give up.
10645     if (Ptr->getOpcode() != ISD::ADD)
10646       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10647
10648     // We know that we have at least an ADD instruction. Try to pattern match
10649     // the simple case of BASE + OFFSET.
10650     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10651       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10652       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10653                               IsIndexSignExt);
10654     }
10655
10656     // Inside a loop the current BASE pointer is calculated using an ADD and a
10657     // MUL instruction. In this case Ptr is the actual BASE pointer.
10658     // (i64 add (i64 %array_ptr)
10659     //          (i64 mul (i64 %induction_var)
10660     //                   (i64 %element_size)))
10661     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10662       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10663
10664     // Look at Base + Index + Offset cases.
10665     SDValue Base = Ptr->getOperand(0);
10666     SDValue IndexOffset = Ptr->getOperand(1);
10667
10668     // Skip signextends.
10669     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10670       IndexOffset = IndexOffset->getOperand(0);
10671       IsIndexSignExt = true;
10672     }
10673
10674     // Either the case of Base + Index (no offset) or something else.
10675     if (IndexOffset->getOpcode() != ISD::ADD)
10676       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10677
10678     // Now we have the case of Base + Index + offset.
10679     SDValue Index = IndexOffset->getOperand(0);
10680     SDValue Offset = IndexOffset->getOperand(1);
10681
10682     if (!isa<ConstantSDNode>(Offset))
10683       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10684
10685     // Ignore signextends.
10686     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10687       Index = Index->getOperand(0);
10688       IsIndexSignExt = true;
10689     } else IsIndexSignExt = false;
10690
10691     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10692     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10693   }
10694 };
10695 } // namespace
10696
10697 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10698                                                   SDLoc SL,
10699                                                   ArrayRef<MemOpLink> Stores,
10700                                                   EVT Ty) const {
10701   SmallVector<SDValue, 8> BuildVector;
10702
10703   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10704     BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10705
10706   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10707 }
10708
10709 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10710                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10711                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10712   // Make sure we have something to merge.
10713   if (NumStores < 2)
10714     return false;
10715
10716   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10717   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10718   unsigned LatestNodeUsed = 0;
10719
10720   for (unsigned i=0; i < NumStores; ++i) {
10721     // Find a chain for the new wide-store operand. Notice that some
10722     // of the store nodes that we found may not be selected for inclusion
10723     // in the wide store. The chain we use needs to be the chain of the
10724     // latest store node which is *used* and replaced by the wide store.
10725     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10726       LatestNodeUsed = i;
10727   }
10728
10729   // The latest Node in the DAG.
10730   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10731   SDLoc DL(StoreNodes[0].MemNode);
10732
10733   SDValue StoredVal;
10734   if (UseVector) {
10735     bool IsVec = MemVT.isVector();
10736     unsigned Elts = NumStores;
10737     if (IsVec) {
10738       // When merging vector stores, get the total number of elements.
10739       Elts *= MemVT.getVectorNumElements();
10740     }
10741     // Get the type for the merged vector store.
10742     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10743     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10744
10745     if (IsConstantSrc) {
10746       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10747     } else {
10748       SmallVector<SDValue, 8> Ops;
10749       for (unsigned i = 0; i < NumStores; ++i) {
10750         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10751         SDValue Val = St->getValue();
10752         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10753         if (Val.getValueType() != MemVT)
10754           return false;
10755         Ops.push_back(Val);
10756       }
10757
10758       // Build the extracted vector elements back into a vector.
10759       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10760                               DL, Ty, Ops);    }
10761   } else {
10762     // We should always use a vector store when merging extracted vector
10763     // elements, so this path implies a store of constants.
10764     assert(IsConstantSrc && "Merged vector elements should use vector store");
10765
10766     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10767     APInt StoreInt(SizeInBits, 0);
10768
10769     // Construct a single integer constant which is made of the smaller
10770     // constant inputs.
10771     bool IsLE = DAG.getDataLayout().isLittleEndian();
10772     for (unsigned i = 0; i < NumStores; ++i) {
10773       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10774       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10775       SDValue Val = St->getValue();
10776       StoreInt <<= ElementSizeBytes * 8;
10777       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10778         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10779       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10780         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10781       } else {
10782         llvm_unreachable("Invalid constant element type");
10783       }
10784     }
10785
10786     // Create the new Load and Store operations.
10787     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10788     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10789   }
10790
10791   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10792                                   FirstInChain->getBasePtr(),
10793                                   FirstInChain->getPointerInfo(),
10794                                   false, false,
10795                                   FirstInChain->getAlignment());
10796
10797   // Replace the last store with the new store
10798   CombineTo(LatestOp, NewStore);
10799   // Erase all other stores.
10800   for (unsigned i = 0; i < NumStores; ++i) {
10801     if (StoreNodes[i].MemNode == LatestOp)
10802       continue;
10803     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10804     // ReplaceAllUsesWith will replace all uses that existed when it was
10805     // called, but graph optimizations may cause new ones to appear. For
10806     // example, the case in pr14333 looks like
10807     //
10808     //  St's chain -> St -> another store -> X
10809     //
10810     // And the only difference from St to the other store is the chain.
10811     // When we change it's chain to be St's chain they become identical,
10812     // get CSEed and the net result is that X is now a use of St.
10813     // Since we know that St is redundant, just iterate.
10814     while (!St->use_empty())
10815       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10816     deleteAndRecombine(St);
10817   }
10818
10819   return true;
10820 }
10821
10822 void DAGCombiner::getStoreMergeAndAliasCandidates(
10823     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10824     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10825   // This holds the base pointer, index, and the offset in bytes from the base
10826   // pointer.
10827   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10828
10829   // We must have a base and an offset.
10830   if (!BasePtr.Base.getNode())
10831     return;
10832
10833   // Do not handle stores to undef base pointers.
10834   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10835     return;
10836
10837   // Walk up the chain and look for nodes with offsets from the same
10838   // base pointer. Stop when reaching an instruction with a different kind
10839   // or instruction which has a different base pointer.
10840   EVT MemVT = St->getMemoryVT();
10841   unsigned Seq = 0;
10842   StoreSDNode *Index = St;
10843
10844
10845   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10846                                                   : DAG.getSubtarget().useAA();
10847
10848   if (UseAA) {
10849     // Look at other users of the same chain. Stores on the same chain do not
10850     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10851     // to be on the same chain, so don't bother looking at adjacent chains.
10852
10853     SDValue Chain = St->getChain();
10854     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10855       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10856
10857         if (OtherST->isVolatile() || OtherST->isIndexed())
10858           continue;
10859
10860         if (OtherST->getMemoryVT() != MemVT)
10861           continue;
10862
10863         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10864
10865         if (Ptr.equalBaseIndex(BasePtr))
10866           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
10867       }
10868     }
10869
10870     return;
10871   }
10872
10873   while (Index) {
10874     // If the chain has more than one use, then we can't reorder the mem ops.
10875     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10876       break;
10877
10878     // Find the base pointer and offset for this memory node.
10879     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10880
10881     // Check that the base pointer is the same as the original one.
10882     if (!Ptr.equalBaseIndex(BasePtr))
10883       break;
10884
10885     // The memory operands must not be volatile.
10886     if (Index->isVolatile() || Index->isIndexed())
10887       break;
10888
10889     // No truncation.
10890     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10891       if (St->isTruncatingStore())
10892         break;
10893
10894     // The stored memory type must be the same.
10895     if (Index->getMemoryVT() != MemVT)
10896       break;
10897
10898     // We found a potential memory operand to merge.
10899     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10900
10901     // Find the next memory operand in the chain. If the next operand in the
10902     // chain is a store then move up and continue the scan with the next
10903     // memory operand. If the next operand is a load save it and use alias
10904     // information to check if it interferes with anything.
10905     SDNode *NextInChain = Index->getChain().getNode();
10906     while (1) {
10907       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10908         // We found a store node. Use it for the next iteration.
10909         Index = STn;
10910         break;
10911       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10912         if (Ldn->isVolatile()) {
10913           Index = nullptr;
10914           break;
10915         }
10916
10917         // Save the load node for later. Continue the scan.
10918         AliasLoadNodes.push_back(Ldn);
10919         NextInChain = Ldn->getChain().getNode();
10920         continue;
10921       } else {
10922         Index = nullptr;
10923         break;
10924       }
10925     }
10926   }
10927 }
10928
10929 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10930   if (OptLevel == CodeGenOpt::None)
10931     return false;
10932
10933   EVT MemVT = St->getMemoryVT();
10934   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10935   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10936       Attribute::NoImplicitFloat);
10937
10938   // This function cannot currently deal with non-byte-sized memory sizes.
10939   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10940     return false;
10941
10942   // Don't merge vectors into wider inputs.
10943   if (MemVT.isVector() || !MemVT.isSimple())
10944     return false;
10945
10946   // Perform an early exit check. Do not bother looking at stored values that
10947   // are not constants, loads, or extracted vector elements.
10948   SDValue StoredVal = St->getValue();
10949   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10950   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10951                        isa<ConstantFPSDNode>(StoredVal);
10952   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10953
10954   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10955     return false;
10956
10957   // Only look at ends of store sequences.
10958   SDValue Chain = SDValue(St, 0);
10959   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10960     return false;
10961
10962   // Save the LoadSDNodes that we find in the chain.
10963   // We need to make sure that these nodes do not interfere with
10964   // any of the store nodes.
10965   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10966
10967   // Save the StoreSDNodes that we find in the chain.
10968   SmallVector<MemOpLink, 8> StoreNodes;
10969
10970   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10971
10972   // Check if there is anything to merge.
10973   if (StoreNodes.size() < 2)
10974     return false;
10975
10976   // Sort the memory operands according to their distance from the base pointer.
10977   std::sort(StoreNodes.begin(), StoreNodes.end(),
10978             [](MemOpLink LHS, MemOpLink RHS) {
10979     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10980            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10981             LHS.SequenceNum > RHS.SequenceNum);
10982   });
10983
10984   // Scan the memory operations on the chain and find the first non-consecutive
10985   // store memory address.
10986   unsigned LastConsecutiveStore = 0;
10987   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10988   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10989
10990     // Check that the addresses are consecutive starting from the second
10991     // element in the list of stores.
10992     if (i > 0) {
10993       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10994       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10995         break;
10996     }
10997
10998     bool Alias = false;
10999     // Check if this store interferes with any of the loads that we found.
11000     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11001       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11002         Alias = true;
11003         break;
11004       }
11005     // We found a load that alias with this store. Stop the sequence.
11006     if (Alias)
11007       break;
11008
11009     // Mark this node as useful.
11010     LastConsecutiveStore = i;
11011   }
11012
11013   // The node with the lowest store address.
11014   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11015   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11016   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11017   LLVMContext &Context = *DAG.getContext();
11018   const DataLayout &DL = DAG.getDataLayout();
11019
11020   // Store the constants into memory as one consecutive store.
11021   if (IsConstantSrc) {
11022     unsigned LastLegalType = 0;
11023     unsigned LastLegalVectorType = 0;
11024     bool NonZero = false;
11025     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11026       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11027       SDValue StoredVal = St->getValue();
11028
11029       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11030         NonZero |= !C->isNullValue();
11031       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11032         NonZero |= !C->getConstantFPValue()->isNullValue();
11033       } else {
11034         // Non-constant.
11035         break;
11036       }
11037
11038       // Find a legal type for the constant store.
11039       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11040       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11041       if (TLI.isTypeLegal(StoreTy) &&
11042           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11043                                  FirstStoreAlign)) {
11044         LastLegalType = i+1;
11045       // Or check whether a truncstore is legal.
11046       } else if (TLI.getTypeAction(Context, StoreTy) ==
11047                  TargetLowering::TypePromoteInteger) {
11048         EVT LegalizedStoredValueTy =
11049           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11050         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11051             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11052                                    FirstStoreAS, FirstStoreAlign)) {
11053           LastLegalType = i + 1;
11054         }
11055       }
11056
11057       // We only use vectors if the constant is known to be zero or the target
11058       // allows it and the function is not marked with the noimplicitfloat
11059       // attribute.
11060       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11061                                                         FirstStoreAS)) &&
11062           !NoVectors) {
11063         // Find a legal type for the vector store.
11064         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11065         if (TLI.isTypeLegal(Ty) &&
11066             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11067                                    FirstStoreAlign))
11068           LastLegalVectorType = i + 1;
11069       }
11070     }
11071
11072     // Check if we found a legal integer type to store.
11073     if (LastLegalType == 0 && LastLegalVectorType == 0)
11074       return false;
11075
11076     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11077     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11078
11079     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11080                                            true, UseVector);
11081   }
11082
11083   // When extracting multiple vector elements, try to store them
11084   // in one vector store rather than a sequence of scalar stores.
11085   if (IsExtractVecEltSrc) {
11086     unsigned NumElem = 0;
11087     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11088       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11089       SDValue StoredVal = St->getValue();
11090       // This restriction could be loosened.
11091       // Bail out if any stored values are not elements extracted from a vector.
11092       // It should be possible to handle mixed sources, but load sources need
11093       // more careful handling (see the block of code below that handles
11094       // consecutive loads).
11095       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11096         return false;
11097
11098       // Find a legal type for the vector store.
11099       EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11100       if (TLI.isTypeLegal(Ty) &&
11101           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11102                                  FirstStoreAlign))
11103         NumElem = i + 1;
11104     }
11105
11106     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11107                                            false, true);
11108   }
11109
11110   // Below we handle the case of multiple consecutive stores that
11111   // come from multiple consecutive loads. We merge them into a single
11112   // wide load and a single wide store.
11113
11114   // Look for load nodes which are used by the stored values.
11115   SmallVector<MemOpLink, 8> LoadNodes;
11116
11117   // Find acceptable loads. Loads need to have the same chain (token factor),
11118   // must not be zext, volatile, indexed, and they must be consecutive.
11119   BaseIndexOffset LdBasePtr;
11120   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11121     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11122     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11123     if (!Ld) break;
11124
11125     // Loads must only have one use.
11126     if (!Ld->hasNUsesOfValue(1, 0))
11127       break;
11128
11129     // The memory operands must not be volatile.
11130     if (Ld->isVolatile() || Ld->isIndexed())
11131       break;
11132
11133     // We do not accept ext loads.
11134     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11135       break;
11136
11137     // The stored memory type must be the same.
11138     if (Ld->getMemoryVT() != MemVT)
11139       break;
11140
11141     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11142     // If this is not the first ptr that we check.
11143     if (LdBasePtr.Base.getNode()) {
11144       // The base ptr must be the same.
11145       if (!LdPtr.equalBaseIndex(LdBasePtr))
11146         break;
11147     } else {
11148       // Check that all other base pointers are the same as this one.
11149       LdBasePtr = LdPtr;
11150     }
11151
11152     // We found a potential memory operand to merge.
11153     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11154   }
11155
11156   if (LoadNodes.size() < 2)
11157     return false;
11158
11159   // If we have load/store pair instructions and we only have two values,
11160   // don't bother.
11161   unsigned RequiredAlignment;
11162   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11163       St->getAlignment() >= RequiredAlignment)
11164     return false;
11165
11166   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11167   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11168   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11169
11170   // Scan the memory operations on the chain and find the first non-consecutive
11171   // load memory address. These variables hold the index in the store node
11172   // array.
11173   unsigned LastConsecutiveLoad = 0;
11174   // This variable refers to the size and not index in the array.
11175   unsigned LastLegalVectorType = 0;
11176   unsigned LastLegalIntegerType = 0;
11177   StartAddress = LoadNodes[0].OffsetFromBase;
11178   SDValue FirstChain = FirstLoad->getChain();
11179   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11180     // All loads much share the same chain.
11181     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11182       break;
11183
11184     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11185     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11186       break;
11187     LastConsecutiveLoad = i;
11188
11189     // Find a legal type for the vector store.
11190     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11191     if (TLI.isTypeLegal(StoreTy) &&
11192         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11193                                FirstStoreAlign) &&
11194         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11195                                FirstLoadAlign)) {
11196       LastLegalVectorType = i + 1;
11197     }
11198
11199     // Find a legal type for the integer store.
11200     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11201     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11202     if (TLI.isTypeLegal(StoreTy) &&
11203         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11204                                FirstStoreAlign) &&
11205         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11206                                FirstLoadAlign))
11207       LastLegalIntegerType = i + 1;
11208     // Or check whether a truncstore and extload is legal.
11209     else if (TLI.getTypeAction(Context, StoreTy) ==
11210              TargetLowering::TypePromoteInteger) {
11211       EVT LegalizedStoredValueTy =
11212         TLI.getTypeToTransformTo(Context, StoreTy);
11213       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11214           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11215           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11216           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11217           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11218                                  FirstStoreAS, FirstStoreAlign) &&
11219           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11220                                  FirstLoadAS, FirstLoadAlign))
11221         LastLegalIntegerType = i+1;
11222     }
11223   }
11224
11225   // Only use vector types if the vector type is larger than the integer type.
11226   // If they are the same, use integers.
11227   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11228   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11229
11230   // We add +1 here because the LastXXX variables refer to location while
11231   // the NumElem refers to array/index size.
11232   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11233   NumElem = std::min(LastLegalType, NumElem);
11234
11235   if (NumElem < 2)
11236     return false;
11237
11238   // The latest Node in the DAG.
11239   unsigned LatestNodeUsed = 0;
11240   for (unsigned i=1; i<NumElem; ++i) {
11241     // Find a chain for the new wide-store operand. Notice that some
11242     // of the store nodes that we found may not be selected for inclusion
11243     // in the wide store. The chain we use needs to be the chain of the
11244     // latest store node which is *used* and replaced by the wide store.
11245     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11246       LatestNodeUsed = i;
11247   }
11248
11249   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11250
11251   // Find if it is better to use vectors or integers to load and store
11252   // to memory.
11253   EVT JointMemOpVT;
11254   if (UseVectorTy) {
11255     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11256   } else {
11257     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11258     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11259   }
11260
11261   SDLoc LoadDL(LoadNodes[0].MemNode);
11262   SDLoc StoreDL(StoreNodes[0].MemNode);
11263
11264   SDValue NewLoad = DAG.getLoad(
11265       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11266       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11267
11268   SDValue NewStore = DAG.getStore(
11269       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11270       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11271
11272   // Replace one of the loads with the new load.
11273   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11274   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11275                                 SDValue(NewLoad.getNode(), 1));
11276
11277   // Remove the rest of the load chains.
11278   for (unsigned i = 1; i < NumElem ; ++i) {
11279     // Replace all chain users of the old load nodes with the chain of the new
11280     // load node.
11281     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11282     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11283   }
11284
11285   // Replace the last store with the new store.
11286   CombineTo(LatestOp, NewStore);
11287   // Erase all other stores.
11288   for (unsigned i = 0; i < NumElem ; ++i) {
11289     // Remove all Store nodes.
11290     if (StoreNodes[i].MemNode == LatestOp)
11291       continue;
11292     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11293     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11294     deleteAndRecombine(St);
11295   }
11296
11297   return true;
11298 }
11299
11300 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11301   SDLoc SL(ST);
11302   SDValue ReplStore;
11303
11304   // Replace the chain to avoid dependency.
11305   if (ST->isTruncatingStore()) {
11306     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11307                                   ST->getBasePtr(), ST->getMemoryVT(),
11308                                   ST->getMemOperand());
11309   } else {
11310     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11311                              ST->getMemOperand());
11312   }
11313
11314   // Create token to keep both nodes around.
11315   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11316                               MVT::Other, ST->getChain(), ReplStore);
11317
11318   // Make sure the new and old chains are cleaned up.
11319   AddToWorklist(Token.getNode());
11320
11321   // Don't add users to work list.
11322   return CombineTo(ST, Token, false);
11323 }
11324
11325 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11326   StoreSDNode *ST  = cast<StoreSDNode>(N);
11327   SDValue Chain = ST->getChain();
11328   SDValue Value = ST->getValue();
11329   SDValue Ptr   = ST->getBasePtr();
11330
11331   // If this is a store of a bit convert, store the input value if the
11332   // resultant store does not need a higher alignment than the original.
11333   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11334       ST->isUnindexed()) {
11335     unsigned OrigAlign = ST->getAlignment();
11336     EVT SVT = Value.getOperand(0).getValueType();
11337     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11338         SVT.getTypeForEVT(*DAG.getContext()));
11339     if (Align <= OrigAlign &&
11340         ((!LegalOperations && !ST->isVolatile()) ||
11341          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11342       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11343                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11344                           ST->isNonTemporal(), OrigAlign,
11345                           ST->getAAInfo());
11346   }
11347
11348   // Turn 'store undef, Ptr' -> nothing.
11349   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11350     return Chain;
11351
11352   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11353   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11354     // NOTE: If the original store is volatile, this transform must not increase
11355     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11356     // processor operation but an i64 (which is not legal) requires two.  So the
11357     // transform should not be done in this case.
11358     if (Value.getOpcode() != ISD::TargetConstantFP) {
11359       SDValue Tmp;
11360       switch (CFP->getSimpleValueType(0).SimpleTy) {
11361       default: llvm_unreachable("Unknown FP type");
11362       case MVT::f16:    // We don't do this for these yet.
11363       case MVT::f80:
11364       case MVT::f128:
11365       case MVT::ppcf128:
11366         break;
11367       case MVT::f32:
11368         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11369             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11370           ;
11371           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11372                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11373                               MVT::i32);
11374           return DAG.getStore(Chain, SDLoc(N), Tmp,
11375                               Ptr, ST->getMemOperand());
11376         }
11377         break;
11378       case MVT::f64:
11379         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11380              !ST->isVolatile()) ||
11381             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11382           ;
11383           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11384                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11385           return DAG.getStore(Chain, SDLoc(N), Tmp,
11386                               Ptr, ST->getMemOperand());
11387         }
11388
11389         if (!ST->isVolatile() &&
11390             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11391           // Many FP stores are not made apparent until after legalize, e.g. for
11392           // argument passing.  Since this is so common, custom legalize the
11393           // 64-bit integer store into two 32-bit stores.
11394           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11395           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11396           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11397           if (DAG.getDataLayout().isBigEndian())
11398             std::swap(Lo, Hi);
11399
11400           unsigned Alignment = ST->getAlignment();
11401           bool isVolatile = ST->isVolatile();
11402           bool isNonTemporal = ST->isNonTemporal();
11403           AAMDNodes AAInfo = ST->getAAInfo();
11404
11405           SDLoc DL(N);
11406
11407           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11408                                      Ptr, ST->getPointerInfo(),
11409                                      isVolatile, isNonTemporal,
11410                                      ST->getAlignment(), AAInfo);
11411           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11412                             DAG.getConstant(4, DL, Ptr.getValueType()));
11413           Alignment = MinAlign(Alignment, 4U);
11414           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11415                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11416                                      isVolatile, isNonTemporal,
11417                                      Alignment, AAInfo);
11418           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11419                              St0, St1);
11420         }
11421
11422         break;
11423       }
11424     }
11425   }
11426
11427   // Try to infer better alignment information than the store already has.
11428   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11429     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11430       if (Align > ST->getAlignment()) {
11431         SDValue NewStore =
11432                DAG.getTruncStore(Chain, SDLoc(N), Value,
11433                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11434                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11435                                  ST->getAAInfo());
11436         if (NewStore.getNode() != N)
11437           return CombineTo(ST, NewStore, true);
11438       }
11439     }
11440   }
11441
11442   // Try transforming a pair floating point load / store ops to integer
11443   // load / store ops.
11444   if (SDValue NewST = TransformFPLoadStorePair(N))
11445     return NewST;
11446
11447   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11448                                                   : DAG.getSubtarget().useAA();
11449 #ifndef NDEBUG
11450   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11451       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11452     UseAA = false;
11453 #endif
11454   if (UseAA && ST->isUnindexed()) {
11455     // FIXME: We should do this even without AA enabled. AA will just allow
11456     // FindBetterChain to work in more situations. The problem with this is that
11457     // any combine that expects memory operations to be on consecutive chains
11458     // first needs to be updated to look for users of the same chain.
11459
11460     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11461     // adjacent stores.
11462     if (findBetterNeighborChains(ST)) {
11463       // replaceStoreChain uses CombineTo, which handled all of the worklist
11464       // manipulation. Return the original node to not do anything else.
11465       return SDValue(ST, 0);
11466     }
11467   }
11468
11469   // Try transforming N to an indexed store.
11470   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11471     return SDValue(N, 0);
11472
11473   // FIXME: is there such a thing as a truncating indexed store?
11474   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11475       Value.getValueType().isInteger()) {
11476     // See if we can simplify the input to this truncstore with knowledge that
11477     // only the low bits are being used.  For example:
11478     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11479     SDValue Shorter =
11480       GetDemandedBits(Value,
11481                       APInt::getLowBitsSet(
11482                         Value.getValueType().getScalarType().getSizeInBits(),
11483                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11484     AddToWorklist(Value.getNode());
11485     if (Shorter.getNode())
11486       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11487                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11488
11489     // Otherwise, see if we can simplify the operation with
11490     // SimplifyDemandedBits, which only works if the value has a single use.
11491     if (SimplifyDemandedBits(Value,
11492                         APInt::getLowBitsSet(
11493                           Value.getValueType().getScalarType().getSizeInBits(),
11494                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11495       return SDValue(N, 0);
11496   }
11497
11498   // If this is a load followed by a store to the same location, then the store
11499   // is dead/noop.
11500   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11501     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11502         ST->isUnindexed() && !ST->isVolatile() &&
11503         // There can't be any side effects between the load and store, such as
11504         // a call or store.
11505         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11506       // The store is dead, remove it.
11507       return Chain;
11508     }
11509   }
11510
11511   // If this is a store followed by a store with the same value to the same
11512   // location, then the store is dead/noop.
11513   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11514     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11515         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11516         ST1->isUnindexed() && !ST1->isVolatile()) {
11517       // The store is dead, remove it.
11518       return Chain;
11519     }
11520   }
11521
11522   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11523   // truncating store.  We can do this even if this is already a truncstore.
11524   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11525       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11526       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11527                             ST->getMemoryVT())) {
11528     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11529                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11530   }
11531
11532   // Only perform this optimization before the types are legal, because we
11533   // don't want to perform this optimization on every DAGCombine invocation.
11534   if (!LegalTypes) {
11535     bool EverChanged = false;
11536
11537     do {
11538       // There can be multiple store sequences on the same chain.
11539       // Keep trying to merge store sequences until we are unable to do so
11540       // or until we merge the last store on the chain.
11541       bool Changed = MergeConsecutiveStores(ST);
11542       EverChanged |= Changed;
11543       if (!Changed) break;
11544     } while (ST->getOpcode() != ISD::DELETED_NODE);
11545
11546     if (EverChanged)
11547       return SDValue(N, 0);
11548   }
11549
11550   return ReduceLoadOpStoreWidth(N);
11551 }
11552
11553 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11554   SDValue InVec = N->getOperand(0);
11555   SDValue InVal = N->getOperand(1);
11556   SDValue EltNo = N->getOperand(2);
11557   SDLoc dl(N);
11558
11559   // If the inserted element is an UNDEF, just use the input vector.
11560   if (InVal.getOpcode() == ISD::UNDEF)
11561     return InVec;
11562
11563   EVT VT = InVec.getValueType();
11564
11565   // If we can't generate a legal BUILD_VECTOR, exit
11566   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11567     return SDValue();
11568
11569   // Check that we know which element is being inserted
11570   if (!isa<ConstantSDNode>(EltNo))
11571     return SDValue();
11572   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11573
11574   // Canonicalize insert_vector_elt dag nodes.
11575   // Example:
11576   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11577   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11578   //
11579   // Do this only if the child insert_vector node has one use; also
11580   // do this only if indices are both constants and Idx1 < Idx0.
11581   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11582       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11583     unsigned OtherElt =
11584       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11585     if (Elt < OtherElt) {
11586       // Swap nodes.
11587       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11588                                   InVec.getOperand(0), InVal, EltNo);
11589       AddToWorklist(NewOp.getNode());
11590       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11591                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11592     }
11593   }
11594
11595   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11596   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11597   // vector elements.
11598   SmallVector<SDValue, 8> Ops;
11599   // Do not combine these two vectors if the output vector will not replace
11600   // the input vector.
11601   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11602     Ops.append(InVec.getNode()->op_begin(),
11603                InVec.getNode()->op_end());
11604   } else if (InVec.getOpcode() == ISD::UNDEF) {
11605     unsigned NElts = VT.getVectorNumElements();
11606     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11607   } else {
11608     return SDValue();
11609   }
11610
11611   // Insert the element
11612   if (Elt < Ops.size()) {
11613     // All the operands of BUILD_VECTOR must have the same type;
11614     // we enforce that here.
11615     EVT OpVT = Ops[0].getValueType();
11616     if (InVal.getValueType() != OpVT)
11617       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11618                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11619                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11620     Ops[Elt] = InVal;
11621   }
11622
11623   // Return the new vector
11624   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11625 }
11626
11627 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11628     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11629   EVT ResultVT = EVE->getValueType(0);
11630   EVT VecEltVT = InVecVT.getVectorElementType();
11631   unsigned Align = OriginalLoad->getAlignment();
11632   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11633       VecEltVT.getTypeForEVT(*DAG.getContext()));
11634
11635   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11636     return SDValue();
11637
11638   Align = NewAlign;
11639
11640   SDValue NewPtr = OriginalLoad->getBasePtr();
11641   SDValue Offset;
11642   EVT PtrType = NewPtr.getValueType();
11643   MachinePointerInfo MPI;
11644   SDLoc DL(EVE);
11645   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11646     int Elt = ConstEltNo->getZExtValue();
11647     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11648     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11649     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11650   } else {
11651     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11652     Offset = DAG.getNode(
11653         ISD::MUL, DL, PtrType, Offset,
11654         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11655     MPI = OriginalLoad->getPointerInfo();
11656   }
11657   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11658
11659   // The replacement we need to do here is a little tricky: we need to
11660   // replace an extractelement of a load with a load.
11661   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11662   // Note that this replacement assumes that the extractvalue is the only
11663   // use of the load; that's okay because we don't want to perform this
11664   // transformation in other cases anyway.
11665   SDValue Load;
11666   SDValue Chain;
11667   if (ResultVT.bitsGT(VecEltVT)) {
11668     // If the result type of vextract is wider than the load, then issue an
11669     // extending load instead.
11670     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11671                                                   VecEltVT)
11672                                    ? ISD::ZEXTLOAD
11673                                    : ISD::EXTLOAD;
11674     Load = DAG.getExtLoad(
11675         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11676         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11677         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11678     Chain = Load.getValue(1);
11679   } else {
11680     Load = DAG.getLoad(
11681         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11682         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11683         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11684     Chain = Load.getValue(1);
11685     if (ResultVT.bitsLT(VecEltVT))
11686       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11687     else
11688       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11689   }
11690   WorklistRemover DeadNodes(*this);
11691   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11692   SDValue To[] = { Load, Chain };
11693   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11694   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11695   // worklist explicitly as well.
11696   AddToWorklist(Load.getNode());
11697   AddUsersToWorklist(Load.getNode()); // Add users too
11698   // Make sure to revisit this node to clean it up; it will usually be dead.
11699   AddToWorklist(EVE);
11700   ++OpsNarrowed;
11701   return SDValue(EVE, 0);
11702 }
11703
11704 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11705   // (vextract (scalar_to_vector val, 0) -> val
11706   SDValue InVec = N->getOperand(0);
11707   EVT VT = InVec.getValueType();
11708   EVT NVT = N->getValueType(0);
11709
11710   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11711     // Check if the result type doesn't match the inserted element type. A
11712     // SCALAR_TO_VECTOR may truncate the inserted element and the
11713     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11714     SDValue InOp = InVec.getOperand(0);
11715     if (InOp.getValueType() != NVT) {
11716       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11717       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11718     }
11719     return InOp;
11720   }
11721
11722   SDValue EltNo = N->getOperand(1);
11723   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11724
11725   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11726   // We only perform this optimization before the op legalization phase because
11727   // we may introduce new vector instructions which are not backed by TD
11728   // patterns. For example on AVX, extracting elements from a wide vector
11729   // without using extract_subvector. However, if we can find an underlying
11730   // scalar value, then we can always use that.
11731   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11732       && ConstEltNo) {
11733     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11734     int NumElem = VT.getVectorNumElements();
11735     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11736     // Find the new index to extract from.
11737     int OrigElt = SVOp->getMaskElt(Elt);
11738
11739     // Extracting an undef index is undef.
11740     if (OrigElt == -1)
11741       return DAG.getUNDEF(NVT);
11742
11743     // Select the right vector half to extract from.
11744     SDValue SVInVec;
11745     if (OrigElt < NumElem) {
11746       SVInVec = InVec->getOperand(0);
11747     } else {
11748       SVInVec = InVec->getOperand(1);
11749       OrigElt -= NumElem;
11750     }
11751
11752     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11753       SDValue InOp = SVInVec.getOperand(OrigElt);
11754       if (InOp.getValueType() != NVT) {
11755         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11756         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11757       }
11758
11759       return InOp;
11760     }
11761
11762     // FIXME: We should handle recursing on other vector shuffles and
11763     // scalar_to_vector here as well.
11764
11765     if (!LegalOperations) {
11766       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11767       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11768                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11769     }
11770   }
11771
11772   bool BCNumEltsChanged = false;
11773   EVT ExtVT = VT.getVectorElementType();
11774   EVT LVT = ExtVT;
11775
11776   // If the result of load has to be truncated, then it's not necessarily
11777   // profitable.
11778   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11779     return SDValue();
11780
11781   if (InVec.getOpcode() == ISD::BITCAST) {
11782     // Don't duplicate a load with other uses.
11783     if (!InVec.hasOneUse())
11784       return SDValue();
11785
11786     EVT BCVT = InVec.getOperand(0).getValueType();
11787     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11788       return SDValue();
11789     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11790       BCNumEltsChanged = true;
11791     InVec = InVec.getOperand(0);
11792     ExtVT = BCVT.getVectorElementType();
11793   }
11794
11795   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11796   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11797       ISD::isNormalLoad(InVec.getNode()) &&
11798       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11799     SDValue Index = N->getOperand(1);
11800     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11801       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11802                                                            OrigLoad);
11803   }
11804
11805   // Perform only after legalization to ensure build_vector / vector_shuffle
11806   // optimizations have already been done.
11807   if (!LegalOperations) return SDValue();
11808
11809   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11810   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11811   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11812
11813   if (ConstEltNo) {
11814     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11815
11816     LoadSDNode *LN0 = nullptr;
11817     const ShuffleVectorSDNode *SVN = nullptr;
11818     if (ISD::isNormalLoad(InVec.getNode())) {
11819       LN0 = cast<LoadSDNode>(InVec);
11820     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11821                InVec.getOperand(0).getValueType() == ExtVT &&
11822                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11823       // Don't duplicate a load with other uses.
11824       if (!InVec.hasOneUse())
11825         return SDValue();
11826
11827       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11828     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11829       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11830       // =>
11831       // (load $addr+1*size)
11832
11833       // Don't duplicate a load with other uses.
11834       if (!InVec.hasOneUse())
11835         return SDValue();
11836
11837       // If the bit convert changed the number of elements, it is unsafe
11838       // to examine the mask.
11839       if (BCNumEltsChanged)
11840         return SDValue();
11841
11842       // Select the input vector, guarding against out of range extract vector.
11843       unsigned NumElems = VT.getVectorNumElements();
11844       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11845       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11846
11847       if (InVec.getOpcode() == ISD::BITCAST) {
11848         // Don't duplicate a load with other uses.
11849         if (!InVec.hasOneUse())
11850           return SDValue();
11851
11852         InVec = InVec.getOperand(0);
11853       }
11854       if (ISD::isNormalLoad(InVec.getNode())) {
11855         LN0 = cast<LoadSDNode>(InVec);
11856         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11857         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11858       }
11859     }
11860
11861     // Make sure we found a non-volatile load and the extractelement is
11862     // the only use.
11863     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11864       return SDValue();
11865
11866     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11867     if (Elt == -1)
11868       return DAG.getUNDEF(LVT);
11869
11870     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11871   }
11872
11873   return SDValue();
11874 }
11875
11876 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11877 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11878   // We perform this optimization post type-legalization because
11879   // the type-legalizer often scalarizes integer-promoted vectors.
11880   // Performing this optimization before may create bit-casts which
11881   // will be type-legalized to complex code sequences.
11882   // We perform this optimization only before the operation legalizer because we
11883   // may introduce illegal operations.
11884   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11885     return SDValue();
11886
11887   unsigned NumInScalars = N->getNumOperands();
11888   SDLoc dl(N);
11889   EVT VT = N->getValueType(0);
11890
11891   // Check to see if this is a BUILD_VECTOR of a bunch of values
11892   // which come from any_extend or zero_extend nodes. If so, we can create
11893   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11894   // optimizations. We do not handle sign-extend because we can't fill the sign
11895   // using shuffles.
11896   EVT SourceType = MVT::Other;
11897   bool AllAnyExt = true;
11898
11899   for (unsigned i = 0; i != NumInScalars; ++i) {
11900     SDValue In = N->getOperand(i);
11901     // Ignore undef inputs.
11902     if (In.getOpcode() == ISD::UNDEF) continue;
11903
11904     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11905     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11906
11907     // Abort if the element is not an extension.
11908     if (!ZeroExt && !AnyExt) {
11909       SourceType = MVT::Other;
11910       break;
11911     }
11912
11913     // The input is a ZeroExt or AnyExt. Check the original type.
11914     EVT InTy = In.getOperand(0).getValueType();
11915
11916     // Check that all of the widened source types are the same.
11917     if (SourceType == MVT::Other)
11918       // First time.
11919       SourceType = InTy;
11920     else if (InTy != SourceType) {
11921       // Multiple income types. Abort.
11922       SourceType = MVT::Other;
11923       break;
11924     }
11925
11926     // Check if all of the extends are ANY_EXTENDs.
11927     AllAnyExt &= AnyExt;
11928   }
11929
11930   // In order to have valid types, all of the inputs must be extended from the
11931   // same source type and all of the inputs must be any or zero extend.
11932   // Scalar sizes must be a power of two.
11933   EVT OutScalarTy = VT.getScalarType();
11934   bool ValidTypes = SourceType != MVT::Other &&
11935                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11936                  isPowerOf2_32(SourceType.getSizeInBits());
11937
11938   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11939   // turn into a single shuffle instruction.
11940   if (!ValidTypes)
11941     return SDValue();
11942
11943   bool isLE = DAG.getDataLayout().isLittleEndian();
11944   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11945   assert(ElemRatio > 1 && "Invalid element size ratio");
11946   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11947                                DAG.getConstant(0, SDLoc(N), SourceType);
11948
11949   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11950   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11951
11952   // Populate the new build_vector
11953   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11954     SDValue Cast = N->getOperand(i);
11955     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11956             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11957             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11958     SDValue In;
11959     if (Cast.getOpcode() == ISD::UNDEF)
11960       In = DAG.getUNDEF(SourceType);
11961     else
11962       In = Cast->getOperand(0);
11963     unsigned Index = isLE ? (i * ElemRatio) :
11964                             (i * ElemRatio + (ElemRatio - 1));
11965
11966     assert(Index < Ops.size() && "Invalid index");
11967     Ops[Index] = In;
11968   }
11969
11970   // The type of the new BUILD_VECTOR node.
11971   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11972   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11973          "Invalid vector size");
11974   // Check if the new vector type is legal.
11975   if (!isTypeLegal(VecVT)) return SDValue();
11976
11977   // Make the new BUILD_VECTOR.
11978   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11979
11980   // The new BUILD_VECTOR node has the potential to be further optimized.
11981   AddToWorklist(BV.getNode());
11982   // Bitcast to the desired type.
11983   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11984 }
11985
11986 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11987   EVT VT = N->getValueType(0);
11988
11989   unsigned NumInScalars = N->getNumOperands();
11990   SDLoc dl(N);
11991
11992   EVT SrcVT = MVT::Other;
11993   unsigned Opcode = ISD::DELETED_NODE;
11994   unsigned NumDefs = 0;
11995
11996   for (unsigned i = 0; i != NumInScalars; ++i) {
11997     SDValue In = N->getOperand(i);
11998     unsigned Opc = In.getOpcode();
11999
12000     if (Opc == ISD::UNDEF)
12001       continue;
12002
12003     // If all scalar values are floats and converted from integers.
12004     if (Opcode == ISD::DELETED_NODE &&
12005         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12006       Opcode = Opc;
12007     }
12008
12009     if (Opc != Opcode)
12010       return SDValue();
12011
12012     EVT InVT = In.getOperand(0).getValueType();
12013
12014     // If all scalar values are typed differently, bail out. It's chosen to
12015     // simplify BUILD_VECTOR of integer types.
12016     if (SrcVT == MVT::Other)
12017       SrcVT = InVT;
12018     if (SrcVT != InVT)
12019       return SDValue();
12020     NumDefs++;
12021   }
12022
12023   // If the vector has just one element defined, it's not worth to fold it into
12024   // a vectorized one.
12025   if (NumDefs < 2)
12026     return SDValue();
12027
12028   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12029          && "Should only handle conversion from integer to float.");
12030   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12031
12032   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12033
12034   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12035     return SDValue();
12036
12037   // Just because the floating-point vector type is legal does not necessarily
12038   // mean that the corresponding integer vector type is.
12039   if (!isTypeLegal(NVT))
12040     return SDValue();
12041
12042   SmallVector<SDValue, 8> Opnds;
12043   for (unsigned i = 0; i != NumInScalars; ++i) {
12044     SDValue In = N->getOperand(i);
12045
12046     if (In.getOpcode() == ISD::UNDEF)
12047       Opnds.push_back(DAG.getUNDEF(SrcVT));
12048     else
12049       Opnds.push_back(In.getOperand(0));
12050   }
12051   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12052   AddToWorklist(BV.getNode());
12053
12054   return DAG.getNode(Opcode, dl, VT, BV);
12055 }
12056
12057 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12058   unsigned NumInScalars = N->getNumOperands();
12059   SDLoc dl(N);
12060   EVT VT = N->getValueType(0);
12061
12062   // A vector built entirely of undefs is undef.
12063   if (ISD::allOperandsUndef(N))
12064     return DAG.getUNDEF(VT);
12065
12066   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12067     return V;
12068
12069   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12070     return V;
12071
12072   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12073   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12074   // at most two distinct vectors, turn this into a shuffle node.
12075
12076   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12077   if (!isTypeLegal(VT))
12078     return SDValue();
12079
12080   // May only combine to shuffle after legalize if shuffle is legal.
12081   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12082     return SDValue();
12083
12084   SDValue VecIn1, VecIn2;
12085   bool UsesZeroVector = false;
12086   for (unsigned i = 0; i != NumInScalars; ++i) {
12087     SDValue Op = N->getOperand(i);
12088     // Ignore undef inputs.
12089     if (Op.getOpcode() == ISD::UNDEF) continue;
12090
12091     // See if we can combine this build_vector into a blend with a zero vector.
12092     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12093       UsesZeroVector = true;
12094       continue;
12095     }
12096
12097     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12098     // constant index, bail out.
12099     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12100         !isa<ConstantSDNode>(Op.getOperand(1))) {
12101       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12102       break;
12103     }
12104
12105     // We allow up to two distinct input vectors.
12106     SDValue ExtractedFromVec = Op.getOperand(0);
12107     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12108       continue;
12109
12110     if (!VecIn1.getNode()) {
12111       VecIn1 = ExtractedFromVec;
12112     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12113       VecIn2 = ExtractedFromVec;
12114     } else {
12115       // Too many inputs.
12116       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12117       break;
12118     }
12119   }
12120
12121   // If everything is good, we can make a shuffle operation.
12122   if (VecIn1.getNode()) {
12123     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12124     SmallVector<int, 8> Mask;
12125     for (unsigned i = 0; i != NumInScalars; ++i) {
12126       unsigned Opcode = N->getOperand(i).getOpcode();
12127       if (Opcode == ISD::UNDEF) {
12128         Mask.push_back(-1);
12129         continue;
12130       }
12131
12132       // Operands can also be zero.
12133       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12134         assert(UsesZeroVector &&
12135                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12136                "Unexpected node found!");
12137         Mask.push_back(NumInScalars+i);
12138         continue;
12139       }
12140
12141       // If extracting from the first vector, just use the index directly.
12142       SDValue Extract = N->getOperand(i);
12143       SDValue ExtVal = Extract.getOperand(1);
12144       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12145       if (Extract.getOperand(0) == VecIn1) {
12146         Mask.push_back(ExtIndex);
12147         continue;
12148       }
12149
12150       // Otherwise, use InIdx + InputVecSize
12151       Mask.push_back(InNumElements + ExtIndex);
12152     }
12153
12154     // Avoid introducing illegal shuffles with zero.
12155     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12156       return SDValue();
12157
12158     // We can't generate a shuffle node with mismatched input and output types.
12159     // Attempt to transform a single input vector to the correct type.
12160     if ((VT != VecIn1.getValueType())) {
12161       // If the input vector type has a different base type to the output
12162       // vector type, bail out.
12163       EVT VTElemType = VT.getVectorElementType();
12164       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12165           (VecIn2.getNode() &&
12166            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12167         return SDValue();
12168
12169       // If the input vector is too small, widen it.
12170       // We only support widening of vectors which are half the size of the
12171       // output registers. For example XMM->YMM widening on X86 with AVX.
12172       EVT VecInT = VecIn1.getValueType();
12173       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12174         // If we only have one small input, widen it by adding undef values.
12175         if (!VecIn2.getNode())
12176           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12177                                DAG.getUNDEF(VecIn1.getValueType()));
12178         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12179           // If we have two small inputs of the same type, try to concat them.
12180           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12181           VecIn2 = SDValue(nullptr, 0);
12182         } else
12183           return SDValue();
12184       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12185         // If the input vector is too large, try to split it.
12186         // We don't support having two input vectors that are too large.
12187         // If the zero vector was used, we can not split the vector,
12188         // since we'd need 3 inputs.
12189         if (UsesZeroVector || VecIn2.getNode())
12190           return SDValue();
12191
12192         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12193           return SDValue();
12194
12195         // Try to replace VecIn1 with two extract_subvectors
12196         // No need to update the masks, they should still be correct.
12197         VecIn2 = DAG.getNode(
12198             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12199             DAG.getConstant(VT.getVectorNumElements(), dl,
12200                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12201         VecIn1 = DAG.getNode(
12202             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12203             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12204       } else
12205         return SDValue();
12206     }
12207
12208     if (UsesZeroVector)
12209       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12210                                 DAG.getConstantFP(0.0, dl, VT);
12211     else
12212       // If VecIn2 is unused then change it to undef.
12213       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12214
12215     // Check that we were able to transform all incoming values to the same
12216     // type.
12217     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12218         VecIn1.getValueType() != VT)
12219           return SDValue();
12220
12221     // Return the new VECTOR_SHUFFLE node.
12222     SDValue Ops[2];
12223     Ops[0] = VecIn1;
12224     Ops[1] = VecIn2;
12225     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12226   }
12227
12228   return SDValue();
12229 }
12230
12231 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12232   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12233   EVT OpVT = N->getOperand(0).getValueType();
12234
12235   // If the operands are legal vectors, leave them alone.
12236   if (TLI.isTypeLegal(OpVT))
12237     return SDValue();
12238
12239   SDLoc DL(N);
12240   EVT VT = N->getValueType(0);
12241   SmallVector<SDValue, 8> Ops;
12242
12243   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12244   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12245
12246   // Keep track of what we encounter.
12247   bool AnyInteger = false;
12248   bool AnyFP = false;
12249   for (const SDValue &Op : N->ops()) {
12250     if (ISD::BITCAST == Op.getOpcode() &&
12251         !Op.getOperand(0).getValueType().isVector())
12252       Ops.push_back(Op.getOperand(0));
12253     else if (ISD::UNDEF == Op.getOpcode())
12254       Ops.push_back(ScalarUndef);
12255     else
12256       return SDValue();
12257
12258     // Note whether we encounter an integer or floating point scalar.
12259     // If it's neither, bail out, it could be something weird like x86mmx.
12260     EVT LastOpVT = Ops.back().getValueType();
12261     if (LastOpVT.isFloatingPoint())
12262       AnyFP = true;
12263     else if (LastOpVT.isInteger())
12264       AnyInteger = true;
12265     else
12266       return SDValue();
12267   }
12268
12269   // If any of the operands is a floating point scalar bitcast to a vector,
12270   // use floating point types throughout, and bitcast everything.
12271   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12272   if (AnyFP) {
12273     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12274     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12275     if (AnyInteger) {
12276       for (SDValue &Op : Ops) {
12277         if (Op.getValueType() == SVT)
12278           continue;
12279         if (Op.getOpcode() == ISD::UNDEF)
12280           Op = ScalarUndef;
12281         else
12282           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12283       }
12284     }
12285   }
12286
12287   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12288                                VT.getSizeInBits() / SVT.getSizeInBits());
12289   return DAG.getNode(ISD::BITCAST, DL, VT,
12290                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12291 }
12292
12293 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12294 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12295 // most two distinct vectors the same size as the result, attempt to turn this
12296 // into a legal shuffle.
12297 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12298   EVT VT = N->getValueType(0);
12299   EVT OpVT = N->getOperand(0).getValueType();
12300   int NumElts = VT.getVectorNumElements();
12301   int NumOpElts = OpVT.getVectorNumElements();
12302
12303   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12304   SmallVector<int, 8> Mask;
12305
12306   for (SDValue Op : N->ops()) {
12307     // Peek through any bitcast.
12308     while (Op.getOpcode() == ISD::BITCAST)
12309       Op = Op.getOperand(0);
12310
12311     // UNDEF nodes convert to UNDEF shuffle mask values.
12312     if (Op.getOpcode() == ISD::UNDEF) {
12313       Mask.append((unsigned)NumOpElts, -1);
12314       continue;
12315     }
12316
12317     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12318       return SDValue();
12319
12320     // What vector are we extracting the subvector from and at what index?
12321     SDValue ExtVec = Op.getOperand(0);
12322
12323     // We want the EVT of the original extraction to correctly scale the
12324     // extraction index.
12325     EVT ExtVT = ExtVec.getValueType();
12326
12327     // Peek through any bitcast.
12328     while (ExtVec.getOpcode() == ISD::BITCAST)
12329       ExtVec = ExtVec.getOperand(0);
12330
12331     // UNDEF nodes convert to UNDEF shuffle mask values.
12332     if (ExtVec.getOpcode() == ISD::UNDEF) {
12333       Mask.append((unsigned)NumOpElts, -1);
12334       continue;
12335     }
12336
12337     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12338       return SDValue();
12339     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12340
12341     // Ensure that we are extracting a subvector from a vector the same
12342     // size as the result.
12343     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12344       return SDValue();
12345
12346     // Scale the subvector index to account for any bitcast.
12347     int NumExtElts = ExtVT.getVectorNumElements();
12348     if (0 == (NumExtElts % NumElts))
12349       ExtIdx /= (NumExtElts / NumElts);
12350     else if (0 == (NumElts % NumExtElts))
12351       ExtIdx *= (NumElts / NumExtElts);
12352     else
12353       return SDValue();
12354
12355     // At most we can reference 2 inputs in the final shuffle.
12356     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12357       SV0 = ExtVec;
12358       for (int i = 0; i != NumOpElts; ++i)
12359         Mask.push_back(i + ExtIdx);
12360     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12361       SV1 = ExtVec;
12362       for (int i = 0; i != NumOpElts; ++i)
12363         Mask.push_back(i + ExtIdx + NumElts);
12364     } else {
12365       return SDValue();
12366     }
12367   }
12368
12369   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12370     return SDValue();
12371
12372   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12373                               DAG.getBitcast(VT, SV1), Mask);
12374 }
12375
12376 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12377   // If we only have one input vector, we don't need to do any concatenation.
12378   if (N->getNumOperands() == 1)
12379     return N->getOperand(0);
12380
12381   // Check if all of the operands are undefs.
12382   EVT VT = N->getValueType(0);
12383   if (ISD::allOperandsUndef(N))
12384     return DAG.getUNDEF(VT);
12385
12386   // Optimize concat_vectors where all but the first of the vectors are undef.
12387   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12388         return Op.getOpcode() == ISD::UNDEF;
12389       })) {
12390     SDValue In = N->getOperand(0);
12391     assert(In.getValueType().isVector() && "Must concat vectors");
12392
12393     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12394     if (In->getOpcode() == ISD::BITCAST &&
12395         !In->getOperand(0)->getValueType(0).isVector()) {
12396       SDValue Scalar = In->getOperand(0);
12397
12398       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12399       // look through the trunc so we can still do the transform:
12400       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12401       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12402           !TLI.isTypeLegal(Scalar.getValueType()) &&
12403           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12404         Scalar = Scalar->getOperand(0);
12405
12406       EVT SclTy = Scalar->getValueType(0);
12407
12408       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12409         return SDValue();
12410
12411       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12412                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12413       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12414         return SDValue();
12415
12416       SDLoc dl = SDLoc(N);
12417       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12418       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12419     }
12420   }
12421
12422   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12423   // We have already tested above for an UNDEF only concatenation.
12424   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12425   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12426   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12427     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12428   };
12429   bool AllBuildVectorsOrUndefs =
12430       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12431   if (AllBuildVectorsOrUndefs) {
12432     SmallVector<SDValue, 8> Opnds;
12433     EVT SVT = VT.getScalarType();
12434
12435     EVT MinVT = SVT;
12436     if (!SVT.isFloatingPoint()) {
12437       // If BUILD_VECTOR are from built from integer, they may have different
12438       // operand types. Get the smallest type and truncate all operands to it.
12439       bool FoundMinVT = false;
12440       for (const SDValue &Op : N->ops())
12441         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12442           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12443           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12444           FoundMinVT = true;
12445         }
12446       assert(FoundMinVT && "Concat vector type mismatch");
12447     }
12448
12449     for (const SDValue &Op : N->ops()) {
12450       EVT OpVT = Op.getValueType();
12451       unsigned NumElts = OpVT.getVectorNumElements();
12452
12453       if (ISD::UNDEF == Op.getOpcode())
12454         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12455
12456       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12457         if (SVT.isFloatingPoint()) {
12458           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12459           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12460         } else {
12461           for (unsigned i = 0; i != NumElts; ++i)
12462             Opnds.push_back(
12463                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12464         }
12465       }
12466     }
12467
12468     assert(VT.getVectorNumElements() == Opnds.size() &&
12469            "Concat vector type mismatch");
12470     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12471   }
12472
12473   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12474   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12475     return V;
12476
12477   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12478   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12479     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12480       return V;
12481
12482   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12483   // nodes often generate nop CONCAT_VECTOR nodes.
12484   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12485   // place the incoming vectors at the exact same location.
12486   SDValue SingleSource = SDValue();
12487   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12488
12489   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12490     SDValue Op = N->getOperand(i);
12491
12492     if (Op.getOpcode() == ISD::UNDEF)
12493       continue;
12494
12495     // Check if this is the identity extract:
12496     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12497       return SDValue();
12498
12499     // Find the single incoming vector for the extract_subvector.
12500     if (SingleSource.getNode()) {
12501       if (Op.getOperand(0) != SingleSource)
12502         return SDValue();
12503     } else {
12504       SingleSource = Op.getOperand(0);
12505
12506       // Check the source type is the same as the type of the result.
12507       // If not, this concat may extend the vector, so we can not
12508       // optimize it away.
12509       if (SingleSource.getValueType() != N->getValueType(0))
12510         return SDValue();
12511     }
12512
12513     unsigned IdentityIndex = i * PartNumElem;
12514     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12515     // The extract index must be constant.
12516     if (!CS)
12517       return SDValue();
12518
12519     // Check that we are reading from the identity index.
12520     if (CS->getZExtValue() != IdentityIndex)
12521       return SDValue();
12522   }
12523
12524   if (SingleSource.getNode())
12525     return SingleSource;
12526
12527   return SDValue();
12528 }
12529
12530 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12531   EVT NVT = N->getValueType(0);
12532   SDValue V = N->getOperand(0);
12533
12534   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12535     // Combine:
12536     //    (extract_subvec (concat V1, V2, ...), i)
12537     // Into:
12538     //    Vi if possible
12539     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12540     // type.
12541     if (V->getOperand(0).getValueType() != NVT)
12542       return SDValue();
12543     unsigned Idx = N->getConstantOperandVal(1);
12544     unsigned NumElems = NVT.getVectorNumElements();
12545     assert((Idx % NumElems) == 0 &&
12546            "IDX in concat is not a multiple of the result vector length.");
12547     return V->getOperand(Idx / NumElems);
12548   }
12549
12550   // Skip bitcasting
12551   if (V->getOpcode() == ISD::BITCAST)
12552     V = V.getOperand(0);
12553
12554   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12555     SDLoc dl(N);
12556     // Handle only simple case where vector being inserted and vector
12557     // being extracted are of same type, and are half size of larger vectors.
12558     EVT BigVT = V->getOperand(0).getValueType();
12559     EVT SmallVT = V->getOperand(1).getValueType();
12560     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12561       return SDValue();
12562
12563     // Only handle cases where both indexes are constants with the same type.
12564     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12565     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12566
12567     if (InsIdx && ExtIdx &&
12568         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12569         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12570       // Combine:
12571       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12572       // Into:
12573       //    indices are equal or bit offsets are equal => V1
12574       //    otherwise => (extract_subvec V1, ExtIdx)
12575       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12576           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12577         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12578       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12579                          DAG.getNode(ISD::BITCAST, dl,
12580                                      N->getOperand(0).getValueType(),
12581                                      V->getOperand(0)), N->getOperand(1));
12582     }
12583   }
12584
12585   return SDValue();
12586 }
12587
12588 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12589                                                  SDValue V, SelectionDAG &DAG) {
12590   SDLoc DL(V);
12591   EVT VT = V.getValueType();
12592
12593   switch (V.getOpcode()) {
12594   default:
12595     return V;
12596
12597   case ISD::CONCAT_VECTORS: {
12598     EVT OpVT = V->getOperand(0).getValueType();
12599     int OpSize = OpVT.getVectorNumElements();
12600     SmallBitVector OpUsedElements(OpSize, false);
12601     bool FoundSimplification = false;
12602     SmallVector<SDValue, 4> NewOps;
12603     NewOps.reserve(V->getNumOperands());
12604     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12605       SDValue Op = V->getOperand(i);
12606       bool OpUsed = false;
12607       for (int j = 0; j < OpSize; ++j)
12608         if (UsedElements[i * OpSize + j]) {
12609           OpUsedElements[j] = true;
12610           OpUsed = true;
12611         }
12612       NewOps.push_back(
12613           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12614                  : DAG.getUNDEF(OpVT));
12615       FoundSimplification |= Op == NewOps.back();
12616       OpUsedElements.reset();
12617     }
12618     if (FoundSimplification)
12619       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12620     return V;
12621   }
12622
12623   case ISD::INSERT_SUBVECTOR: {
12624     SDValue BaseV = V->getOperand(0);
12625     SDValue SubV = V->getOperand(1);
12626     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12627     if (!IdxN)
12628       return V;
12629
12630     int SubSize = SubV.getValueType().getVectorNumElements();
12631     int Idx = IdxN->getZExtValue();
12632     bool SubVectorUsed = false;
12633     SmallBitVector SubUsedElements(SubSize, false);
12634     for (int i = 0; i < SubSize; ++i)
12635       if (UsedElements[i + Idx]) {
12636         SubVectorUsed = true;
12637         SubUsedElements[i] = true;
12638         UsedElements[i + Idx] = false;
12639       }
12640
12641     // Now recurse on both the base and sub vectors.
12642     SDValue SimplifiedSubV =
12643         SubVectorUsed
12644             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12645             : DAG.getUNDEF(SubV.getValueType());
12646     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12647     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12648       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12649                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12650     return V;
12651   }
12652   }
12653 }
12654
12655 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12656                                        SDValue N1, SelectionDAG &DAG) {
12657   EVT VT = SVN->getValueType(0);
12658   int NumElts = VT.getVectorNumElements();
12659   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12660   for (int M : SVN->getMask())
12661     if (M >= 0 && M < NumElts)
12662       N0UsedElements[M] = true;
12663     else if (M >= NumElts)
12664       N1UsedElements[M - NumElts] = true;
12665
12666   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12667   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12668   if (S0 == N0 && S1 == N1)
12669     return SDValue();
12670
12671   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12672 }
12673
12674 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12675 // or turn a shuffle of a single concat into simpler shuffle then concat.
12676 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12677   EVT VT = N->getValueType(0);
12678   unsigned NumElts = VT.getVectorNumElements();
12679
12680   SDValue N0 = N->getOperand(0);
12681   SDValue N1 = N->getOperand(1);
12682   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12683
12684   SmallVector<SDValue, 4> Ops;
12685   EVT ConcatVT = N0.getOperand(0).getValueType();
12686   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12687   unsigned NumConcats = NumElts / NumElemsPerConcat;
12688
12689   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12690   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12691   // half vector elements.
12692   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12693       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12694                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12695     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12696                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12697     N1 = DAG.getUNDEF(ConcatVT);
12698     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12699   }
12700
12701   // Look at every vector that's inserted. We're looking for exact
12702   // subvector-sized copies from a concatenated vector
12703   for (unsigned I = 0; I != NumConcats; ++I) {
12704     // Make sure we're dealing with a copy.
12705     unsigned Begin = I * NumElemsPerConcat;
12706     bool AllUndef = true, NoUndef = true;
12707     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12708       if (SVN->getMaskElt(J) >= 0)
12709         AllUndef = false;
12710       else
12711         NoUndef = false;
12712     }
12713
12714     if (NoUndef) {
12715       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12716         return SDValue();
12717
12718       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12719         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12720           return SDValue();
12721
12722       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12723       if (FirstElt < N0.getNumOperands())
12724         Ops.push_back(N0.getOperand(FirstElt));
12725       else
12726         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12727
12728     } else if (AllUndef) {
12729       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12730     } else { // Mixed with general masks and undefs, can't do optimization.
12731       return SDValue();
12732     }
12733   }
12734
12735   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12736 }
12737
12738 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12739   EVT VT = N->getValueType(0);
12740   unsigned NumElts = VT.getVectorNumElements();
12741
12742   SDValue N0 = N->getOperand(0);
12743   SDValue N1 = N->getOperand(1);
12744
12745   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12746
12747   // Canonicalize shuffle undef, undef -> undef
12748   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12749     return DAG.getUNDEF(VT);
12750
12751   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12752
12753   // Canonicalize shuffle v, v -> v, undef
12754   if (N0 == N1) {
12755     SmallVector<int, 8> NewMask;
12756     for (unsigned i = 0; i != NumElts; ++i) {
12757       int Idx = SVN->getMaskElt(i);
12758       if (Idx >= (int)NumElts) Idx -= NumElts;
12759       NewMask.push_back(Idx);
12760     }
12761     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12762                                 &NewMask[0]);
12763   }
12764
12765   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12766   if (N0.getOpcode() == ISD::UNDEF) {
12767     SmallVector<int, 8> NewMask;
12768     for (unsigned i = 0; i != NumElts; ++i) {
12769       int Idx = SVN->getMaskElt(i);
12770       if (Idx >= 0) {
12771         if (Idx >= (int)NumElts)
12772           Idx -= NumElts;
12773         else
12774           Idx = -1; // remove reference to lhs
12775       }
12776       NewMask.push_back(Idx);
12777     }
12778     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12779                                 &NewMask[0]);
12780   }
12781
12782   // Remove references to rhs if it is undef
12783   if (N1.getOpcode() == ISD::UNDEF) {
12784     bool Changed = false;
12785     SmallVector<int, 8> NewMask;
12786     for (unsigned i = 0; i != NumElts; ++i) {
12787       int Idx = SVN->getMaskElt(i);
12788       if (Idx >= (int)NumElts) {
12789         Idx = -1;
12790         Changed = true;
12791       }
12792       NewMask.push_back(Idx);
12793     }
12794     if (Changed)
12795       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12796   }
12797
12798   // If it is a splat, check if the argument vector is another splat or a
12799   // build_vector.
12800   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12801     SDNode *V = N0.getNode();
12802
12803     // If this is a bit convert that changes the element type of the vector but
12804     // not the number of vector elements, look through it.  Be careful not to
12805     // look though conversions that change things like v4f32 to v2f64.
12806     if (V->getOpcode() == ISD::BITCAST) {
12807       SDValue ConvInput = V->getOperand(0);
12808       if (ConvInput.getValueType().isVector() &&
12809           ConvInput.getValueType().getVectorNumElements() == NumElts)
12810         V = ConvInput.getNode();
12811     }
12812
12813     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12814       assert(V->getNumOperands() == NumElts &&
12815              "BUILD_VECTOR has wrong number of operands");
12816       SDValue Base;
12817       bool AllSame = true;
12818       for (unsigned i = 0; i != NumElts; ++i) {
12819         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12820           Base = V->getOperand(i);
12821           break;
12822         }
12823       }
12824       // Splat of <u, u, u, u>, return <u, u, u, u>
12825       if (!Base.getNode())
12826         return N0;
12827       for (unsigned i = 0; i != NumElts; ++i) {
12828         if (V->getOperand(i) != Base) {
12829           AllSame = false;
12830           break;
12831         }
12832       }
12833       // Splat of <x, x, x, x>, return <x, x, x, x>
12834       if (AllSame)
12835         return N0;
12836
12837       // Canonicalize any other splat as a build_vector.
12838       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12839       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12840       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12841                                   V->getValueType(0), Ops);
12842
12843       // We may have jumped through bitcasts, so the type of the
12844       // BUILD_VECTOR may not match the type of the shuffle.
12845       if (V->getValueType(0) != VT)
12846         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12847       return NewBV;
12848     }
12849   }
12850
12851   // There are various patterns used to build up a vector from smaller vectors,
12852   // subvectors, or elements. Scan chains of these and replace unused insertions
12853   // or components with undef.
12854   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12855     return S;
12856
12857   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12858       Level < AfterLegalizeVectorOps &&
12859       (N1.getOpcode() == ISD::UNDEF ||
12860       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12861        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12862     SDValue V = partitionShuffleOfConcats(N, DAG);
12863
12864     if (V.getNode())
12865       return V;
12866   }
12867
12868   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12869   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12870   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12871     SmallVector<SDValue, 8> Ops;
12872     for (int M : SVN->getMask()) {
12873       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12874       if (M >= 0) {
12875         int Idx = M % NumElts;
12876         SDValue &S = (M < (int)NumElts ? N0 : N1);
12877         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12878           Op = S.getOperand(Idx);
12879         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12880           if (Idx == 0)
12881             Op = S.getOperand(0);
12882         } else {
12883           // Operand can't be combined - bail out.
12884           break;
12885         }
12886       }
12887       Ops.push_back(Op);
12888     }
12889     if (Ops.size() == VT.getVectorNumElements()) {
12890       // BUILD_VECTOR requires all inputs to be of the same type, find the
12891       // maximum type and extend them all.
12892       EVT SVT = VT.getScalarType();
12893       if (SVT.isInteger())
12894         for (SDValue &Op : Ops)
12895           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12896       if (SVT != VT.getScalarType())
12897         for (SDValue &Op : Ops)
12898           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12899                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12900                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12901       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12902     }
12903   }
12904
12905   // If this shuffle only has a single input that is a bitcasted shuffle,
12906   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12907   // back to their original types.
12908   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12909       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12910       TLI.isTypeLegal(VT)) {
12911
12912     // Peek through the bitcast only if there is one user.
12913     SDValue BC0 = N0;
12914     while (BC0.getOpcode() == ISD::BITCAST) {
12915       if (!BC0.hasOneUse())
12916         break;
12917       BC0 = BC0.getOperand(0);
12918     }
12919
12920     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12921       if (Scale == 1)
12922         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12923
12924       SmallVector<int, 8> NewMask;
12925       for (int M : Mask)
12926         for (int s = 0; s != Scale; ++s)
12927           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12928       return NewMask;
12929     };
12930
12931     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12932       EVT SVT = VT.getScalarType();
12933       EVT InnerVT = BC0->getValueType(0);
12934       EVT InnerSVT = InnerVT.getScalarType();
12935
12936       // Determine which shuffle works with the smaller scalar type.
12937       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12938       EVT ScaleSVT = ScaleVT.getScalarType();
12939
12940       if (TLI.isTypeLegal(ScaleVT) &&
12941           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12942           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12943
12944         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12945         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12946
12947         // Scale the shuffle masks to the smaller scalar type.
12948         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12949         SmallVector<int, 8> InnerMask =
12950             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12951         SmallVector<int, 8> OuterMask =
12952             ScaleShuffleMask(SVN->getMask(), OuterScale);
12953
12954         // Merge the shuffle masks.
12955         SmallVector<int, 8> NewMask;
12956         for (int M : OuterMask)
12957           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12958
12959         // Test for shuffle mask legality over both commutations.
12960         SDValue SV0 = BC0->getOperand(0);
12961         SDValue SV1 = BC0->getOperand(1);
12962         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12963         if (!LegalMask) {
12964           std::swap(SV0, SV1);
12965           ShuffleVectorSDNode::commuteMask(NewMask);
12966           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12967         }
12968
12969         if (LegalMask) {
12970           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12971           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12972           return DAG.getNode(
12973               ISD::BITCAST, SDLoc(N), VT,
12974               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12975         }
12976       }
12977     }
12978   }
12979
12980   // Canonicalize shuffles according to rules:
12981   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12982   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12983   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12984   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12985       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12986       TLI.isTypeLegal(VT)) {
12987     // The incoming shuffle must be of the same type as the result of the
12988     // current shuffle.
12989     assert(N1->getOperand(0).getValueType() == VT &&
12990            "Shuffle types don't match");
12991
12992     SDValue SV0 = N1->getOperand(0);
12993     SDValue SV1 = N1->getOperand(1);
12994     bool HasSameOp0 = N0 == SV0;
12995     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12996     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12997       // Commute the operands of this shuffle so that next rule
12998       // will trigger.
12999       return DAG.getCommutedVectorShuffle(*SVN);
13000   }
13001
13002   // Try to fold according to rules:
13003   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13004   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13005   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13006   // Don't try to fold shuffles with illegal type.
13007   // Only fold if this shuffle is the only user of the other shuffle.
13008   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13009       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13010     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13011
13012     // The incoming shuffle must be of the same type as the result of the
13013     // current shuffle.
13014     assert(OtherSV->getOperand(0).getValueType() == VT &&
13015            "Shuffle types don't match");
13016
13017     SDValue SV0, SV1;
13018     SmallVector<int, 4> Mask;
13019     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13020     // operand, and SV1 as the second operand.
13021     for (unsigned i = 0; i != NumElts; ++i) {
13022       int Idx = SVN->getMaskElt(i);
13023       if (Idx < 0) {
13024         // Propagate Undef.
13025         Mask.push_back(Idx);
13026         continue;
13027       }
13028
13029       SDValue CurrentVec;
13030       if (Idx < (int)NumElts) {
13031         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13032         // shuffle mask to identify which vector is actually referenced.
13033         Idx = OtherSV->getMaskElt(Idx);
13034         if (Idx < 0) {
13035           // Propagate Undef.
13036           Mask.push_back(Idx);
13037           continue;
13038         }
13039
13040         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13041                                            : OtherSV->getOperand(1);
13042       } else {
13043         // This shuffle index references an element within N1.
13044         CurrentVec = N1;
13045       }
13046
13047       // Simple case where 'CurrentVec' is UNDEF.
13048       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13049         Mask.push_back(-1);
13050         continue;
13051       }
13052
13053       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13054       // will be the first or second operand of the combined shuffle.
13055       Idx = Idx % NumElts;
13056       if (!SV0.getNode() || SV0 == CurrentVec) {
13057         // Ok. CurrentVec is the left hand side.
13058         // Update the mask accordingly.
13059         SV0 = CurrentVec;
13060         Mask.push_back(Idx);
13061         continue;
13062       }
13063
13064       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13065       if (SV1.getNode() && SV1 != CurrentVec)
13066         return SDValue();
13067
13068       // Ok. CurrentVec is the right hand side.
13069       // Update the mask accordingly.
13070       SV1 = CurrentVec;
13071       Mask.push_back(Idx + NumElts);
13072     }
13073
13074     // Check if all indices in Mask are Undef. In case, propagate Undef.
13075     bool isUndefMask = true;
13076     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13077       isUndefMask &= Mask[i] < 0;
13078
13079     if (isUndefMask)
13080       return DAG.getUNDEF(VT);
13081
13082     if (!SV0.getNode())
13083       SV0 = DAG.getUNDEF(VT);
13084     if (!SV1.getNode())
13085       SV1 = DAG.getUNDEF(VT);
13086
13087     // Avoid introducing shuffles with illegal mask.
13088     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13089       ShuffleVectorSDNode::commuteMask(Mask);
13090
13091       if (!TLI.isShuffleMaskLegal(Mask, VT))
13092         return SDValue();
13093
13094       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13095       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13096       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13097       std::swap(SV0, SV1);
13098     }
13099
13100     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13101     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13102     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13103     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13104   }
13105
13106   return SDValue();
13107 }
13108
13109 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13110   SDValue InVal = N->getOperand(0);
13111   EVT VT = N->getValueType(0);
13112
13113   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13114   // with a VECTOR_SHUFFLE.
13115   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13116     SDValue InVec = InVal->getOperand(0);
13117     SDValue EltNo = InVal->getOperand(1);
13118
13119     // FIXME: We could support implicit truncation if the shuffle can be
13120     // scaled to a smaller vector scalar type.
13121     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13122     if (C0 && VT == InVec.getValueType() &&
13123         VT.getScalarType() == InVal.getValueType()) {
13124       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13125       int Elt = C0->getZExtValue();
13126       NewMask[0] = Elt;
13127
13128       if (TLI.isShuffleMaskLegal(NewMask, VT))
13129         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13130                                     NewMask);
13131     }
13132   }
13133
13134   return SDValue();
13135 }
13136
13137 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13138   SDValue N0 = N->getOperand(0);
13139   SDValue N2 = N->getOperand(2);
13140
13141   // If the input vector is a concatenation, and the insert replaces
13142   // one of the halves, we can optimize into a single concat_vectors.
13143   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13144       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13145     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13146     EVT VT = N->getValueType(0);
13147
13148     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13149     // (concat_vectors Z, Y)
13150     if (InsIdx == 0)
13151       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13152                          N->getOperand(1), N0.getOperand(1));
13153
13154     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13155     // (concat_vectors X, Z)
13156     if (InsIdx == VT.getVectorNumElements()/2)
13157       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13158                          N0.getOperand(0), N->getOperand(1));
13159   }
13160
13161   return SDValue();
13162 }
13163
13164 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13165   SDValue N0 = N->getOperand(0);
13166
13167   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13168   if (N0->getOpcode() == ISD::FP16_TO_FP)
13169     return N0->getOperand(0);
13170
13171   return SDValue();
13172 }
13173
13174 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13175   SDValue N0 = N->getOperand(0);
13176
13177   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13178   if (N0->getOpcode() == ISD::AND) {
13179     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13180     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13181       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13182                          N0.getOperand(0));
13183     }
13184   }
13185
13186   return SDValue();
13187 }
13188
13189 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13190 /// with the destination vector and a zero vector.
13191 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13192 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13193 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13194   EVT VT = N->getValueType(0);
13195   SDValue LHS = N->getOperand(0);
13196   SDValue RHS = N->getOperand(1);
13197   SDLoc dl(N);
13198
13199   // Make sure we're not running after operation legalization where it
13200   // may have custom lowered the vector shuffles.
13201   if (LegalOperations)
13202     return SDValue();
13203
13204   if (N->getOpcode() != ISD::AND)
13205     return SDValue();
13206
13207   if (RHS.getOpcode() == ISD::BITCAST)
13208     RHS = RHS.getOperand(0);
13209
13210   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13211     return SDValue();
13212
13213   EVT RVT = RHS.getValueType();
13214   unsigned NumElts = RHS.getNumOperands();
13215
13216   // Attempt to create a valid clear mask, splitting the mask into
13217   // sub elements and checking to see if each is
13218   // all zeros or all ones - suitable for shuffle masking.
13219   auto BuildClearMask = [&](int Split) {
13220     int NumSubElts = NumElts * Split;
13221     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13222
13223     SmallVector<int, 8> Indices;
13224     for (int i = 0; i != NumSubElts; ++i) {
13225       int EltIdx = i / Split;
13226       int SubIdx = i % Split;
13227       SDValue Elt = RHS.getOperand(EltIdx);
13228       if (Elt.getOpcode() == ISD::UNDEF) {
13229         Indices.push_back(-1);
13230         continue;
13231       }
13232
13233       APInt Bits;
13234       if (isa<ConstantSDNode>(Elt))
13235         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13236       else if (isa<ConstantFPSDNode>(Elt))
13237         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13238       else
13239         return SDValue();
13240
13241       // Extract the sub element from the constant bit mask.
13242       if (DAG.getDataLayout().isBigEndian()) {
13243         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13244       } else {
13245         Bits = Bits.lshr(SubIdx * NumSubBits);
13246       }
13247
13248       if (Split > 1)
13249         Bits = Bits.trunc(NumSubBits);
13250
13251       if (Bits.isAllOnesValue())
13252         Indices.push_back(i);
13253       else if (Bits == 0)
13254         Indices.push_back(i + NumSubElts);
13255       else
13256         return SDValue();
13257     }
13258
13259     // Let's see if the target supports this vector_shuffle.
13260     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13261     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13262     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13263       return SDValue();
13264
13265     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13266     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13267                                                    DAG.getBitcast(ClearVT, LHS),
13268                                                    Zero, &Indices[0]));
13269   };
13270
13271   // Determine maximum split level (byte level masking).
13272   int MaxSplit = 1;
13273   if (RVT.getScalarSizeInBits() % 8 == 0)
13274     MaxSplit = RVT.getScalarSizeInBits() / 8;
13275
13276   for (int Split = 1; Split <= MaxSplit; ++Split)
13277     if (RVT.getScalarSizeInBits() % Split == 0)
13278       if (SDValue S = BuildClearMask(Split))
13279         return S;
13280
13281   return SDValue();
13282 }
13283
13284 /// Visit a binary vector operation, like ADD.
13285 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13286   assert(N->getValueType(0).isVector() &&
13287          "SimplifyVBinOp only works on vectors!");
13288
13289   SDValue LHS = N->getOperand(0);
13290   SDValue RHS = N->getOperand(1);
13291
13292   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13293   // this operation.
13294   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13295       RHS.getOpcode() == ISD::BUILD_VECTOR) {
13296     // Check if both vectors are constants. If not bail out.
13297     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13298           cast<BuildVectorSDNode>(RHS)->isConstant()))
13299       return SDValue();
13300
13301     SmallVector<SDValue, 8> Ops;
13302     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13303       SDValue LHSOp = LHS.getOperand(i);
13304       SDValue RHSOp = RHS.getOperand(i);
13305
13306       // Can't fold divide by zero.
13307       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13308           N->getOpcode() == ISD::FDIV) {
13309         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13310              cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13311           break;
13312       }
13313
13314       EVT VT = LHSOp.getValueType();
13315       EVT RVT = RHSOp.getValueType();
13316       if (RVT != VT) {
13317         // Integer BUILD_VECTOR operands may have types larger than the element
13318         // size (e.g., when the element type is not legal).  Prior to type
13319         // legalization, the types may not match between the two BUILD_VECTORS.
13320         // Truncate one of the operands to make them match.
13321         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13322           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13323         } else {
13324           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13325           VT = RVT;
13326         }
13327       }
13328       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13329                                    LHSOp, RHSOp);
13330       if (FoldOp.getOpcode() != ISD::UNDEF &&
13331           FoldOp.getOpcode() != ISD::Constant &&
13332           FoldOp.getOpcode() != ISD::ConstantFP)
13333         break;
13334       Ops.push_back(FoldOp);
13335       AddToWorklist(FoldOp.getNode());
13336     }
13337
13338     if (Ops.size() == LHS.getNumOperands())
13339       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13340   }
13341
13342   // Try to convert a constant mask AND into a shuffle clear mask.
13343   if (SDValue Shuffle = XformToShuffleWithZero(N))
13344     return Shuffle;
13345
13346   // Type legalization might introduce new shuffles in the DAG.
13347   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13348   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13349   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13350       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13351       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13352       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13353     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13354     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13355
13356     if (SVN0->getMask().equals(SVN1->getMask())) {
13357       EVT VT = N->getValueType(0);
13358       SDValue UndefVector = LHS.getOperand(1);
13359       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13360                                      LHS.getOperand(0), RHS.getOperand(0));
13361       AddUsersToWorklist(N);
13362       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13363                                   &SVN0->getMask()[0]);
13364     }
13365   }
13366
13367   return SDValue();
13368 }
13369
13370 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13371                                     SDValue N1, SDValue N2){
13372   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13373
13374   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13375                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13376
13377   // If we got a simplified select_cc node back from SimplifySelectCC, then
13378   // break it down into a new SETCC node, and a new SELECT node, and then return
13379   // the SELECT node, since we were called with a SELECT node.
13380   if (SCC.getNode()) {
13381     // Check to see if we got a select_cc back (to turn into setcc/select).
13382     // Otherwise, just return whatever node we got back, like fabs.
13383     if (SCC.getOpcode() == ISD::SELECT_CC) {
13384       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13385                                   N0.getValueType(),
13386                                   SCC.getOperand(0), SCC.getOperand(1),
13387                                   SCC.getOperand(4));
13388       AddToWorklist(SETCC.getNode());
13389       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13390                            SCC.getOperand(2), SCC.getOperand(3));
13391     }
13392
13393     return SCC;
13394   }
13395   return SDValue();
13396 }
13397
13398 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13399 /// being selected between, see if we can simplify the select.  Callers of this
13400 /// should assume that TheSelect is deleted if this returns true.  As such, they
13401 /// should return the appropriate thing (e.g. the node) back to the top-level of
13402 /// the DAG combiner loop to avoid it being looked at.
13403 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13404                                     SDValue RHS) {
13405
13406   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13407   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13408   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13409     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13410       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13411       SDValue Sqrt = RHS;
13412       ISD::CondCode CC;
13413       SDValue CmpLHS;
13414       const ConstantFPSDNode *NegZero = nullptr;
13415
13416       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13417         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13418         CmpLHS = TheSelect->getOperand(0);
13419         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13420       } else {
13421         // SELECT or VSELECT
13422         SDValue Cmp = TheSelect->getOperand(0);
13423         if (Cmp.getOpcode() == ISD::SETCC) {
13424           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13425           CmpLHS = Cmp.getOperand(0);
13426           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13427         }
13428       }
13429       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13430           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13431           CC == ISD::SETULT || CC == ISD::SETLT)) {
13432         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13433         CombineTo(TheSelect, Sqrt);
13434         return true;
13435       }
13436     }
13437   }
13438   // Cannot simplify select with vector condition
13439   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13440
13441   // If this is a select from two identical things, try to pull the operation
13442   // through the select.
13443   if (LHS.getOpcode() != RHS.getOpcode() ||
13444       !LHS.hasOneUse() || !RHS.hasOneUse())
13445     return false;
13446
13447   // If this is a load and the token chain is identical, replace the select
13448   // of two loads with a load through a select of the address to load from.
13449   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13450   // constants have been dropped into the constant pool.
13451   if (LHS.getOpcode() == ISD::LOAD) {
13452     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13453     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13454
13455     // Token chains must be identical.
13456     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13457         // Do not let this transformation reduce the number of volatile loads.
13458         LLD->isVolatile() || RLD->isVolatile() ||
13459         // FIXME: If either is a pre/post inc/dec load,
13460         // we'd need to split out the address adjustment.
13461         LLD->isIndexed() || RLD->isIndexed() ||
13462         // If this is an EXTLOAD, the VT's must match.
13463         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13464         // If this is an EXTLOAD, the kind of extension must match.
13465         (LLD->getExtensionType() != RLD->getExtensionType() &&
13466          // The only exception is if one of the extensions is anyext.
13467          LLD->getExtensionType() != ISD::EXTLOAD &&
13468          RLD->getExtensionType() != ISD::EXTLOAD) ||
13469         // FIXME: this discards src value information.  This is
13470         // over-conservative. It would be beneficial to be able to remember
13471         // both potential memory locations.  Since we are discarding
13472         // src value info, don't do the transformation if the memory
13473         // locations are not in the default address space.
13474         LLD->getPointerInfo().getAddrSpace() != 0 ||
13475         RLD->getPointerInfo().getAddrSpace() != 0 ||
13476         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13477                                       LLD->getBasePtr().getValueType()))
13478       return false;
13479
13480     // Check that the select condition doesn't reach either load.  If so,
13481     // folding this will induce a cycle into the DAG.  If not, this is safe to
13482     // xform, so create a select of the addresses.
13483     SDValue Addr;
13484     if (TheSelect->getOpcode() == ISD::SELECT) {
13485       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13486       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13487           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13488         return false;
13489       // The loads must not depend on one another.
13490       if (LLD->isPredecessorOf(RLD) ||
13491           RLD->isPredecessorOf(LLD))
13492         return false;
13493       Addr = DAG.getSelect(SDLoc(TheSelect),
13494                            LLD->getBasePtr().getValueType(),
13495                            TheSelect->getOperand(0), LLD->getBasePtr(),
13496                            RLD->getBasePtr());
13497     } else {  // Otherwise SELECT_CC
13498       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13499       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13500
13501       if ((LLD->hasAnyUseOfValue(1) &&
13502            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13503           (RLD->hasAnyUseOfValue(1) &&
13504            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13505         return false;
13506
13507       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13508                          LLD->getBasePtr().getValueType(),
13509                          TheSelect->getOperand(0),
13510                          TheSelect->getOperand(1),
13511                          LLD->getBasePtr(), RLD->getBasePtr(),
13512                          TheSelect->getOperand(4));
13513     }
13514
13515     SDValue Load;
13516     // It is safe to replace the two loads if they have different alignments,
13517     // but the new load must be the minimum (most restrictive) alignment of the
13518     // inputs.
13519     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13520     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13521     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13522       Load = DAG.getLoad(TheSelect->getValueType(0),
13523                          SDLoc(TheSelect),
13524                          // FIXME: Discards pointer and AA info.
13525                          LLD->getChain(), Addr, MachinePointerInfo(),
13526                          LLD->isVolatile(), LLD->isNonTemporal(),
13527                          isInvariant, Alignment);
13528     } else {
13529       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13530                             RLD->getExtensionType() : LLD->getExtensionType(),
13531                             SDLoc(TheSelect),
13532                             TheSelect->getValueType(0),
13533                             // FIXME: Discards pointer and AA info.
13534                             LLD->getChain(), Addr, MachinePointerInfo(),
13535                             LLD->getMemoryVT(), LLD->isVolatile(),
13536                             LLD->isNonTemporal(), isInvariant, Alignment);
13537     }
13538
13539     // Users of the select now use the result of the load.
13540     CombineTo(TheSelect, Load);
13541
13542     // Users of the old loads now use the new load's chain.  We know the
13543     // old-load value is dead now.
13544     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13545     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13546     return true;
13547   }
13548
13549   return false;
13550 }
13551
13552 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13553 /// where 'cond' is the comparison specified by CC.
13554 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13555                                       SDValue N2, SDValue N3,
13556                                       ISD::CondCode CC, bool NotExtCompare) {
13557   // (x ? y : y) -> y.
13558   if (N2 == N3) return N2;
13559
13560   EVT VT = N2.getValueType();
13561   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13562   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13563
13564   // Determine if the condition we're dealing with is constant
13565   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13566                               N0, N1, CC, DL, false);
13567   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13568
13569   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13570     // fold select_cc true, x, y -> x
13571     // fold select_cc false, x, y -> y
13572     return !SCCC->isNullValue() ? N2 : N3;
13573   }
13574
13575   // Check to see if we can simplify the select into an fabs node
13576   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13577     // Allow either -0.0 or 0.0
13578     if (CFP->isZero()) {
13579       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13580       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13581           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13582           N2 == N3.getOperand(0))
13583         return DAG.getNode(ISD::FABS, DL, VT, N0);
13584
13585       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13586       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13587           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13588           N2.getOperand(0) == N3)
13589         return DAG.getNode(ISD::FABS, DL, VT, N3);
13590     }
13591   }
13592
13593   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13594   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13595   // in it.  This is a win when the constant is not otherwise available because
13596   // it replaces two constant pool loads with one.  We only do this if the FP
13597   // type is known to be legal, because if it isn't, then we are before legalize
13598   // types an we want the other legalization to happen first (e.g. to avoid
13599   // messing with soft float) and if the ConstantFP is not legal, because if
13600   // it is legal, we may not need to store the FP constant in a constant pool.
13601   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13602     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13603       if (TLI.isTypeLegal(N2.getValueType()) &&
13604           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13605                TargetLowering::Legal &&
13606            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13607            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13608           // If both constants have multiple uses, then we won't need to do an
13609           // extra load, they are likely around in registers for other users.
13610           (TV->hasOneUse() || FV->hasOneUse())) {
13611         Constant *Elts[] = {
13612           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13613           const_cast<ConstantFP*>(TV->getConstantFPValue())
13614         };
13615         Type *FPTy = Elts[0]->getType();
13616         const DataLayout &TD = DAG.getDataLayout();
13617
13618         // Create a ConstantArray of the two constants.
13619         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13620         SDValue CPIdx =
13621             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13622                                 TD.getPrefTypeAlignment(FPTy));
13623         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13624
13625         // Get the offsets to the 0 and 1 element of the array so that we can
13626         // select between them.
13627         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13628         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13629         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13630
13631         SDValue Cond = DAG.getSetCC(DL,
13632                                     getSetCCResultType(N0.getValueType()),
13633                                     N0, N1, CC);
13634         AddToWorklist(Cond.getNode());
13635         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13636                                           Cond, One, Zero);
13637         AddToWorklist(CstOffset.getNode());
13638         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13639                             CstOffset);
13640         AddToWorklist(CPIdx.getNode());
13641         return DAG.getLoad(
13642             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13643             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13644             false, false, false, Alignment);
13645       }
13646     }
13647
13648   // Check to see if we can perform the "gzip trick", transforming
13649   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13650   if (isNullConstant(N3) && CC == ISD::SETLT &&
13651       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13652        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13653     EVT XType = N0.getValueType();
13654     EVT AType = N2.getValueType();
13655     if (XType.bitsGE(AType)) {
13656       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13657       // single-bit constant.
13658       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13659         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13660         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13661         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13662                                        getShiftAmountTy(N0.getValueType()));
13663         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13664                                     XType, N0, ShCt);
13665         AddToWorklist(Shift.getNode());
13666
13667         if (XType.bitsGT(AType)) {
13668           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13669           AddToWorklist(Shift.getNode());
13670         }
13671
13672         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13673       }
13674
13675       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13676                                   XType, N0,
13677                                   DAG.getConstant(XType.getSizeInBits() - 1,
13678                                                   SDLoc(N0),
13679                                          getShiftAmountTy(N0.getValueType())));
13680       AddToWorklist(Shift.getNode());
13681
13682       if (XType.bitsGT(AType)) {
13683         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13684         AddToWorklist(Shift.getNode());
13685       }
13686
13687       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13688     }
13689   }
13690
13691   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13692   // where y is has a single bit set.
13693   // A plaintext description would be, we can turn the SELECT_CC into an AND
13694   // when the condition can be materialized as an all-ones register.  Any
13695   // single bit-test can be materialized as an all-ones register with
13696   // shift-left and shift-right-arith.
13697   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13698       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13699     SDValue AndLHS = N0->getOperand(0);
13700     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13701     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13702       // Shift the tested bit over the sign bit.
13703       APInt AndMask = ConstAndRHS->getAPIntValue();
13704       SDValue ShlAmt =
13705         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13706                         getShiftAmountTy(AndLHS.getValueType()));
13707       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13708
13709       // Now arithmetic right shift it all the way over, so the result is either
13710       // all-ones, or zero.
13711       SDValue ShrAmt =
13712         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13713                         getShiftAmountTy(Shl.getValueType()));
13714       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13715
13716       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13717     }
13718   }
13719
13720   // fold select C, 16, 0 -> shl C, 4
13721   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13722       TLI.getBooleanContents(N0.getValueType()) ==
13723           TargetLowering::ZeroOrOneBooleanContent) {
13724
13725     // If the caller doesn't want us to simplify this into a zext of a compare,
13726     // don't do it.
13727     if (NotExtCompare && N2C->isOne())
13728       return SDValue();
13729
13730     // Get a SetCC of the condition
13731     // NOTE: Don't create a SETCC if it's not legal on this target.
13732     if (!LegalOperations ||
13733         TLI.isOperationLegal(ISD::SETCC,
13734           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13735       SDValue Temp, SCC;
13736       // cast from setcc result type to select result type
13737       if (LegalTypes) {
13738         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13739                             N0, N1, CC);
13740         if (N2.getValueType().bitsLT(SCC.getValueType()))
13741           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13742                                         N2.getValueType());
13743         else
13744           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13745                              N2.getValueType(), SCC);
13746       } else {
13747         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13748         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13749                            N2.getValueType(), SCC);
13750       }
13751
13752       AddToWorklist(SCC.getNode());
13753       AddToWorklist(Temp.getNode());
13754
13755       if (N2C->isOne())
13756         return Temp;
13757
13758       // shl setcc result by log2 n2c
13759       return DAG.getNode(
13760           ISD::SHL, DL, N2.getValueType(), Temp,
13761           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13762                           getShiftAmountTy(Temp.getValueType())));
13763     }
13764   }
13765
13766   // Check to see if this is an integer abs.
13767   // select_cc setg[te] X,  0,  X, -X ->
13768   // select_cc setgt    X, -1,  X, -X ->
13769   // select_cc setl[te] X,  0, -X,  X ->
13770   // select_cc setlt    X,  1, -X,  X ->
13771   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13772   if (N1C) {
13773     ConstantSDNode *SubC = nullptr;
13774     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13775          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13776         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13777       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13778     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13779               (N1C->isOne() && CC == ISD::SETLT)) &&
13780              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13781       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13782
13783     EVT XType = N0.getValueType();
13784     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13785       SDLoc DL(N0);
13786       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13787                                   N0,
13788                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13789                                          getShiftAmountTy(N0.getValueType())));
13790       SDValue Add = DAG.getNode(ISD::ADD, DL,
13791                                 XType, N0, Shift);
13792       AddToWorklist(Shift.getNode());
13793       AddToWorklist(Add.getNode());
13794       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13795     }
13796   }
13797
13798   return SDValue();
13799 }
13800
13801 /// This is a stub for TargetLowering::SimplifySetCC.
13802 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13803                                    SDValue N1, ISD::CondCode Cond,
13804                                    SDLoc DL, bool foldBooleans) {
13805   TargetLowering::DAGCombinerInfo
13806     DagCombineInfo(DAG, Level, false, this);
13807   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13808 }
13809
13810 /// Given an ISD::SDIV node expressing a divide by constant, return
13811 /// a DAG expression to select that will generate the same value by multiplying
13812 /// by a magic number.
13813 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13814 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13815   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13816   if (!C)
13817     return SDValue();
13818
13819   // Avoid division by zero.
13820   if (C->isNullValue())
13821     return SDValue();
13822
13823   std::vector<SDNode*> Built;
13824   SDValue S =
13825       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13826
13827   for (SDNode *N : Built)
13828     AddToWorklist(N);
13829   return S;
13830 }
13831
13832 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13833 /// DAG expression that will generate the same value by right shifting.
13834 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13835   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13836   if (!C)
13837     return SDValue();
13838
13839   // Avoid division by zero.
13840   if (C->isNullValue())
13841     return SDValue();
13842
13843   std::vector<SDNode *> Built;
13844   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13845
13846   for (SDNode *N : Built)
13847     AddToWorklist(N);
13848   return S;
13849 }
13850
13851 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13852 /// expression that will generate the same value by multiplying by a magic
13853 /// number.
13854 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13855 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13856   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13857   if (!C)
13858     return SDValue();
13859
13860   // Avoid division by zero.
13861   if (C->isNullValue())
13862     return SDValue();
13863
13864   std::vector<SDNode*> Built;
13865   SDValue S =
13866       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13867
13868   for (SDNode *N : Built)
13869     AddToWorklist(N);
13870   return S;
13871 }
13872
13873 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13874   if (Level >= AfterLegalizeDAG)
13875     return SDValue();
13876
13877   // Expose the DAG combiner to the target combiner implementations.
13878   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13879
13880   unsigned Iterations = 0;
13881   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13882     if (Iterations) {
13883       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13884       // For the reciprocal, we need to find the zero of the function:
13885       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13886       //     =>
13887       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13888       //     does not require additional intermediate precision]
13889       EVT VT = Op.getValueType();
13890       SDLoc DL(Op);
13891       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13892
13893       AddToWorklist(Est.getNode());
13894
13895       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13896       for (unsigned i = 0; i < Iterations; ++i) {
13897         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13898         AddToWorklist(NewEst.getNode());
13899
13900         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13901         AddToWorklist(NewEst.getNode());
13902
13903         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13904         AddToWorklist(NewEst.getNode());
13905
13906         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13907         AddToWorklist(Est.getNode());
13908       }
13909     }
13910     return Est;
13911   }
13912
13913   return SDValue();
13914 }
13915
13916 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13917 /// For the reciprocal sqrt, we need to find the zero of the function:
13918 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13919 ///     =>
13920 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13921 /// As a result, we precompute A/2 prior to the iteration loop.
13922 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13923                                           unsigned Iterations) {
13924   EVT VT = Arg.getValueType();
13925   SDLoc DL(Arg);
13926   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13927
13928   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13929   // this entire sequence requires only one FP constant.
13930   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13931   AddToWorklist(HalfArg.getNode());
13932
13933   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13934   AddToWorklist(HalfArg.getNode());
13935
13936   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13937   for (unsigned i = 0; i < Iterations; ++i) {
13938     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13939     AddToWorklist(NewEst.getNode());
13940
13941     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13942     AddToWorklist(NewEst.getNode());
13943
13944     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13945     AddToWorklist(NewEst.getNode());
13946
13947     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13948     AddToWorklist(Est.getNode());
13949   }
13950   return Est;
13951 }
13952
13953 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13954 /// For the reciprocal sqrt, we need to find the zero of the function:
13955 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13956 ///     =>
13957 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13958 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13959                                           unsigned Iterations) {
13960   EVT VT = Arg.getValueType();
13961   SDLoc DL(Arg);
13962   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13963   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13964
13965   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13966   for (unsigned i = 0; i < Iterations; ++i) {
13967     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13968     AddToWorklist(HalfEst.getNode());
13969
13970     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13971     AddToWorklist(Est.getNode());
13972
13973     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13974     AddToWorklist(Est.getNode());
13975
13976     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13977     AddToWorklist(Est.getNode());
13978
13979     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13980     AddToWorklist(Est.getNode());
13981   }
13982   return Est;
13983 }
13984
13985 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13986   if (Level >= AfterLegalizeDAG)
13987     return SDValue();
13988
13989   // Expose the DAG combiner to the target combiner implementations.
13990   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13991   unsigned Iterations = 0;
13992   bool UseOneConstNR = false;
13993   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13994     AddToWorklist(Est.getNode());
13995     if (Iterations) {
13996       Est = UseOneConstNR ?
13997         BuildRsqrtNROneConst(Op, Est, Iterations) :
13998         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13999     }
14000     return Est;
14001   }
14002
14003   return SDValue();
14004 }
14005
14006 /// Return true if base is a frame index, which is known not to alias with
14007 /// anything but itself.  Provides base object and offset as results.
14008 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14009                            const GlobalValue *&GV, const void *&CV) {
14010   // Assume it is a primitive operation.
14011   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14012
14013   // If it's an adding a simple constant then integrate the offset.
14014   if (Base.getOpcode() == ISD::ADD) {
14015     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14016       Base = Base.getOperand(0);
14017       Offset += C->getZExtValue();
14018     }
14019   }
14020
14021   // Return the underlying GlobalValue, and update the Offset.  Return false
14022   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14023   // by multiple nodes with different offsets.
14024   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14025     GV = G->getGlobal();
14026     Offset += G->getOffset();
14027     return false;
14028   }
14029
14030   // Return the underlying Constant value, and update the Offset.  Return false
14031   // for ConstantSDNodes since the same constant pool entry may be represented
14032   // by multiple nodes with different offsets.
14033   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14034     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14035                                          : (const void *)C->getConstVal();
14036     Offset += C->getOffset();
14037     return false;
14038   }
14039   // If it's any of the following then it can't alias with anything but itself.
14040   return isa<FrameIndexSDNode>(Base);
14041 }
14042
14043 /// Return true if there is any possibility that the two addresses overlap.
14044 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14045   // If they are the same then they must be aliases.
14046   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14047
14048   // If they are both volatile then they cannot be reordered.
14049   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14050
14051   // If one operation reads from invariant memory, and the other may store, they
14052   // cannot alias. These should really be checking the equivalent of mayWrite,
14053   // but it only matters for memory nodes other than load /store.
14054   if (Op0->isInvariant() && Op1->writeMem())
14055     return false;
14056
14057   if (Op1->isInvariant() && Op0->writeMem())
14058     return false;
14059
14060   // Gather base node and offset information.
14061   SDValue Base1, Base2;
14062   int64_t Offset1, Offset2;
14063   const GlobalValue *GV1, *GV2;
14064   const void *CV1, *CV2;
14065   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14066                                       Base1, Offset1, GV1, CV1);
14067   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14068                                       Base2, Offset2, GV2, CV2);
14069
14070   // If they have a same base address then check to see if they overlap.
14071   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14072     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14073              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14074
14075   // It is possible for different frame indices to alias each other, mostly
14076   // when tail call optimization reuses return address slots for arguments.
14077   // To catch this case, look up the actual index of frame indices to compute
14078   // the real alias relationship.
14079   if (isFrameIndex1 && isFrameIndex2) {
14080     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14081     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14082     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14083     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14084              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14085   }
14086
14087   // Otherwise, if we know what the bases are, and they aren't identical, then
14088   // we know they cannot alias.
14089   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14090     return false;
14091
14092   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14093   // compared to the size and offset of the access, we may be able to prove they
14094   // do not alias.  This check is conservative for now to catch cases created by
14095   // splitting vector types.
14096   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14097       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14098       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14099        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14100       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14101     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14102     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14103
14104     // There is no overlap between these relatively aligned accesses of similar
14105     // size, return no alias.
14106     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14107         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14108       return false;
14109   }
14110
14111   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14112                    ? CombinerGlobalAA
14113                    : DAG.getSubtarget().useAA();
14114 #ifndef NDEBUG
14115   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14116       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14117     UseAA = false;
14118 #endif
14119   if (UseAA &&
14120       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14121     // Use alias analysis information.
14122     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14123                                  Op1->getSrcValueOffset());
14124     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14125         Op0->getSrcValueOffset() - MinOffset;
14126     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14127         Op1->getSrcValueOffset() - MinOffset;
14128     AliasResult AAResult =
14129         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14130                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14131                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14132                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14133     if (AAResult == NoAlias)
14134       return false;
14135   }
14136
14137   // Otherwise we have to assume they alias.
14138   return true;
14139 }
14140
14141 /// Walk up chain skipping non-aliasing memory nodes,
14142 /// looking for aliasing nodes and adding them to the Aliases vector.
14143 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14144                                    SmallVectorImpl<SDValue> &Aliases) {
14145   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14146   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14147
14148   // Get alias information for node.
14149   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14150
14151   // Starting off.
14152   Chains.push_back(OriginalChain);
14153   unsigned Depth = 0;
14154
14155   // Look at each chain and determine if it is an alias.  If so, add it to the
14156   // aliases list.  If not, then continue up the chain looking for the next
14157   // candidate.
14158   while (!Chains.empty()) {
14159     SDValue Chain = Chains.pop_back_val();
14160
14161     // For TokenFactor nodes, look at each operand and only continue up the
14162     // chain until we find two aliases.  If we've seen two aliases, assume we'll
14163     // find more and revert to original chain since the xform is unlikely to be
14164     // profitable.
14165     //
14166     // FIXME: The depth check could be made to return the last non-aliasing
14167     // chain we found before we hit a tokenfactor rather than the original
14168     // chain.
14169     if (Depth > 6 || Aliases.size() == 2) {
14170       Aliases.clear();
14171       Aliases.push_back(OriginalChain);
14172       return;
14173     }
14174
14175     // Don't bother if we've been before.
14176     if (!Visited.insert(Chain.getNode()).second)
14177       continue;
14178
14179     switch (Chain.getOpcode()) {
14180     case ISD::EntryToken:
14181       // Entry token is ideal chain operand, but handled in FindBetterChain.
14182       break;
14183
14184     case ISD::LOAD:
14185     case ISD::STORE: {
14186       // Get alias information for Chain.
14187       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14188           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14189
14190       // If chain is alias then stop here.
14191       if (!(IsLoad && IsOpLoad) &&
14192           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14193         Aliases.push_back(Chain);
14194       } else {
14195         // Look further up the chain.
14196         Chains.push_back(Chain.getOperand(0));
14197         ++Depth;
14198       }
14199       break;
14200     }
14201
14202     case ISD::TokenFactor:
14203       // We have to check each of the operands of the token factor for "small"
14204       // token factors, so we queue them up.  Adding the operands to the queue
14205       // (stack) in reverse order maintains the original order and increases the
14206       // likelihood that getNode will find a matching token factor (CSE.)
14207       if (Chain.getNumOperands() > 16) {
14208         Aliases.push_back(Chain);
14209         break;
14210       }
14211       for (unsigned n = Chain.getNumOperands(); n;)
14212         Chains.push_back(Chain.getOperand(--n));
14213       ++Depth;
14214       break;
14215
14216     default:
14217       // For all other instructions we will just have to take what we can get.
14218       Aliases.push_back(Chain);
14219       break;
14220     }
14221   }
14222
14223   // We need to be careful here to also search for aliases through the
14224   // value operand of a store, etc. Consider the following situation:
14225   //   Token1 = ...
14226   //   L1 = load Token1, %52
14227   //   S1 = store Token1, L1, %51
14228   //   L2 = load Token1, %52+8
14229   //   S2 = store Token1, L2, %51+8
14230   //   Token2 = Token(S1, S2)
14231   //   L3 = load Token2, %53
14232   //   S3 = store Token2, L3, %52
14233   //   L4 = load Token2, %53+8
14234   //   S4 = store Token2, L4, %52+8
14235   // If we search for aliases of S3 (which loads address %52), and we look
14236   // only through the chain, then we'll miss the trivial dependence on L1
14237   // (which also loads from %52). We then might change all loads and
14238   // stores to use Token1 as their chain operand, which could result in
14239   // copying %53 into %52 before copying %52 into %51 (which should
14240   // happen first).
14241   //
14242   // The problem is, however, that searching for such data dependencies
14243   // can become expensive, and the cost is not directly related to the
14244   // chain depth. Instead, we'll rule out such configurations here by
14245   // insisting that we've visited all chain users (except for users
14246   // of the original chain, which is not necessary). When doing this,
14247   // we need to look through nodes we don't care about (otherwise, things
14248   // like register copies will interfere with trivial cases).
14249
14250   SmallVector<const SDNode *, 16> Worklist;
14251   for (const SDNode *N : Visited)
14252     if (N != OriginalChain.getNode())
14253       Worklist.push_back(N);
14254
14255   while (!Worklist.empty()) {
14256     const SDNode *M = Worklist.pop_back_val();
14257
14258     // We have already visited M, and want to make sure we've visited any uses
14259     // of M that we care about. For uses that we've not visisted, and don't
14260     // care about, queue them to the worklist.
14261
14262     for (SDNode::use_iterator UI = M->use_begin(),
14263          UIE = M->use_end(); UI != UIE; ++UI)
14264       if (UI.getUse().getValueType() == MVT::Other &&
14265           Visited.insert(*UI).second) {
14266         if (isa<MemSDNode>(*UI)) {
14267           // We've not visited this use, and we care about it (it could have an
14268           // ordering dependency with the original node).
14269           Aliases.clear();
14270           Aliases.push_back(OriginalChain);
14271           return;
14272         }
14273
14274         // We've not visited this use, but we don't care about it. Mark it as
14275         // visited and enqueue it to the worklist.
14276         Worklist.push_back(*UI);
14277       }
14278   }
14279 }
14280
14281 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14282 /// (aliasing node.)
14283 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14284   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14285
14286   // Accumulate all the aliases to this node.
14287   GatherAllAliases(N, OldChain, Aliases);
14288
14289   // If no operands then chain to entry token.
14290   if (Aliases.size() == 0)
14291     return DAG.getEntryNode();
14292
14293   // If a single operand then chain to it.  We don't need to revisit it.
14294   if (Aliases.size() == 1)
14295     return Aliases[0];
14296
14297   // Construct a custom tailored token factor.
14298   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14299 }
14300
14301 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14302   // This holds the base pointer, index, and the offset in bytes from the base
14303   // pointer.
14304   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14305
14306   // We must have a base and an offset.
14307   if (!BasePtr.Base.getNode())
14308     return false;
14309
14310   // Do not handle stores to undef base pointers.
14311   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14312     return false;
14313
14314   SmallVector<StoreSDNode *, 8> ChainedStores;
14315   ChainedStores.push_back(St);
14316
14317   // Walk up the chain and look for nodes with offsets from the same
14318   // base pointer. Stop when reaching an instruction with a different kind
14319   // or instruction which has a different base pointer.
14320   StoreSDNode *Index = St;
14321   while (Index) {
14322     // If the chain has more than one use, then we can't reorder the mem ops.
14323     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14324       break;
14325
14326     // Find the base pointer and offset for this memory node.
14327     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14328
14329     // Check that the base pointer is the same as the original one.
14330     if (!Ptr.equalBaseIndex(BasePtr))
14331       break;
14332
14333     if (Index->isVolatile() || Index->isIndexed())
14334       break;
14335
14336     // Find the next memory operand in the chain. If the next operand in the
14337     // chain is a store then move up and continue the scan with the next
14338     // memory operand. If the next operand is a load save it and use alias
14339     // information to check if it interferes with anything.
14340     SDNode *NextInChain = Index->getChain().getNode();
14341     while (true) {
14342       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14343         // We found a store node. Use it for the next iteration.
14344         ChainedStores.push_back(STn);
14345         Index = STn;
14346         break;
14347       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14348         NextInChain = Ldn->getChain().getNode();
14349         continue;
14350       } else {
14351         Index = nullptr;
14352         break;
14353       }
14354     }
14355   }
14356
14357   bool MadeChange = false;
14358   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14359
14360   for (StoreSDNode *ChainedStore : ChainedStores) {
14361     SDValue Chain = ChainedStore->getChain();
14362     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14363
14364     if (Chain != BetterChain) {
14365       MadeChange = true;
14366       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14367     }
14368   }
14369
14370   // Do all replacements after finding the replacements to make to avoid making
14371   // the chains more complicated by introducing new TokenFactors.
14372   for (auto Replacement : BetterChains)
14373     replaceStoreChain(Replacement.first, Replacement.second);
14374
14375   return MadeChange;
14376 }
14377
14378 /// This is the entry point for the file.
14379 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14380                            CodeGenOpt::Level OptLevel) {
14381   /// This is the main entry point to this class.
14382   DAGCombiner(*this, AA, OptLevel).Run(Level);
14383 }