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/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <algorithm>
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "dagcombine"
45 
46 STATISTIC(NodesCombined   , "Number of dag nodes combined");
47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
49 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
50 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
51 STATISTIC(SlicedLoads, "Number of load sliced");
52 
53 namespace {
54   static cl::opt<bool>
55     CombinerAA("combiner-alias-analysis", cl::Hidden,
56                cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 
58   static cl::opt<bool>
59     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60                cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 
62   static cl::opt<bool>
63     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
64                cl::desc("Enable DAG combiner's use of TBAA"));
65 
66 #ifndef NDEBUG
67   static cl::opt<std::string>
68     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
69                cl::desc("Only use DAG-combiner alias analysis in this"
70                         " function"));
71 #endif
72 
73   /// Hidden option to stress test load slicing, i.e., when this option
74   /// is enabled, load slicing bypasses most of its profitability guards.
75   static cl::opt<bool>
76   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
77                     cl::desc("Bypass the profitability model of load "
78                              "slicing"),
79                     cl::init(false));
80 
81   static cl::opt<bool>
82     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
83                       cl::desc("DAG combiner may split indexing from loads"));
84 
85 //------------------------------ DAGCombiner ---------------------------------//
86 
87   class DAGCombiner {
88     SelectionDAG &DAG;
89     const TargetLowering &TLI;
90     CombineLevel Level;
91     CodeGenOpt::Level OptLevel;
92     bool LegalOperations;
93     bool LegalTypes;
94     bool ForCodeSize;
95 
96     /// \brief Worklist of all of the nodes that need to be simplified.
97     ///
98     /// This must behave as a stack -- new nodes to process are pushed onto the
99     /// back and when processing we pop off of the back.
100     ///
101     /// The worklist will not contain duplicates but may contain null entries
102     /// due to nodes being deleted from the underlying DAG.
103     SmallVector<SDNode *, 64> Worklist;
104 
105     /// \brief Mapping from an SDNode to its position on the worklist.
106     ///
107     /// This is used to find and remove nodes from the worklist (by nulling
108     /// them) when they are deleted from the underlying DAG. It relies on
109     /// stable indices of nodes within the worklist.
110     DenseMap<SDNode *, unsigned> WorklistMap;
111 
112     /// \brief Set of nodes which have been combined (at least once).
113     ///
114     /// This is used to allow us to reliably add any operands of a DAG node
115     /// which have not yet been combined to the worklist.
116     SmallPtrSet<SDNode *, 32> CombinedNodes;
117 
118     // AA - Used for DAG load/store alias analysis.
119     AliasAnalysis &AA;
120 
121     /// When an instruction is simplified, add all users of the instruction to
122     /// the work lists because they might get more simplified now.
123     void AddUsersToWorklist(SDNode *N) {
124       for (SDNode *Node : N->uses())
125         AddToWorklist(Node);
126     }
127 
128     /// Call the node-specific routine that folds each particular type of node.
129     SDValue visit(SDNode *N);
130 
131   public:
132     /// Add to the worklist making sure its instance is at the back (next to be
133     /// processed.)
134     void AddToWorklist(SDNode *N) {
135       // Skip handle nodes as they can't usefully be combined and confuse the
136       // zero-use deletion strategy.
137       if (N->getOpcode() == ISD::HANDLENODE)
138         return;
139 
140       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141         Worklist.push_back(N);
142     }
143 
144     /// Remove all instances of N from the worklist.
145     void removeFromWorklist(SDNode *N) {
146       CombinedNodes.erase(N);
147 
148       auto It = WorklistMap.find(N);
149       if (It == WorklistMap.end())
150         return; // Not in the worklist.
151 
152       // Null out the entry rather than erasing it to avoid a linear operation.
153       Worklist[It->second] = nullptr;
154       WorklistMap.erase(It);
155     }
156 
157     void deleteAndRecombine(SDNode *N);
158     bool recursivelyDeleteUnusedNodes(SDNode *N);
159 
160     /// Replaces all uses of the results of one DAG node with new values.
161     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162                       bool AddTo = true);
163 
164     /// Replaces all uses of the results of one DAG node with new values.
165     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
166       return CombineTo(N, &Res, 1, AddTo);
167     }
168 
169     /// Replaces all uses of the results of one DAG node with new values.
170     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
171                       bool AddTo = true) {
172       SDValue To[] = { Res0, Res1 };
173       return CombineTo(N, To, 2, AddTo);
174     }
175 
176     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
177 
178   private:
179 
180     /// Check the specified integer node value to see if it can be simplified or
181     /// if things it uses can be simplified by bit propagation.
182     /// If so, return true.
183     bool SimplifyDemandedBits(SDValue Op) {
184       unsigned BitWidth = Op.getScalarValueSizeInBits();
185       APInt Demanded = APInt::getAllOnesValue(BitWidth);
186       return SimplifyDemandedBits(Op, Demanded);
187     }
188 
189     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
190 
191     bool CombineToPreIndexedLoadStore(SDNode *N);
192     bool CombineToPostIndexedLoadStore(SDNode *N);
193     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
194     bool SliceUpLoad(SDNode *N);
195 
196     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
197     ///   load.
198     ///
199     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
200     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
201     /// \param EltNo index of the vector element to load.
202     /// \param OriginalLoad load that EVE came from to be replaced.
203     /// \returns EVE on success SDValue() on failure.
204     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
205         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
206     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
207     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
208     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
210     SDValue PromoteIntBinOp(SDValue Op);
211     SDValue PromoteIntShiftOp(SDValue Op);
212     SDValue PromoteExtend(SDValue Op);
213     bool PromoteLoad(SDValue Op);
214 
215     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
216                          SDValue ExtLoad, const SDLoc &DL,
217                          ISD::NodeType ExtType);
218 
219     /// Call the node-specific routine that knows how to fold each
220     /// particular type of node. If that doesn't do anything, try the
221     /// target-specific DAG combines.
222     SDValue combine(SDNode *N);
223 
224     // Visitation implementation - Implement dag node combining for different
225     // node types.  The semantics are as follows:
226     // Return Value:
227     //   SDValue.getNode() == 0 - No change was made
228     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
229     //   otherwise              - N should be replaced by the returned Operand.
230     //
231     SDValue visitTokenFactor(SDNode *N);
232     SDValue visitMERGE_VALUES(SDNode *N);
233     SDValue visitADD(SDNode *N);
234     SDValue visitSUB(SDNode *N);
235     SDValue visitADDC(SDNode *N);
236     SDValue visitSUBC(SDNode *N);
237     SDValue visitADDE(SDNode *N);
238     SDValue visitSUBE(SDNode *N);
239     SDValue visitMUL(SDNode *N);
240     SDValue useDivRem(SDNode *N);
241     SDValue visitSDIV(SDNode *N);
242     SDValue visitUDIV(SDNode *N);
243     SDValue visitREM(SDNode *N);
244     SDValue visitMULHU(SDNode *N);
245     SDValue visitMULHS(SDNode *N);
246     SDValue visitSMUL_LOHI(SDNode *N);
247     SDValue visitUMUL_LOHI(SDNode *N);
248     SDValue visitSMULO(SDNode *N);
249     SDValue visitUMULO(SDNode *N);
250     SDValue visitIMINMAX(SDNode *N);
251     SDValue visitAND(SDNode *N);
252     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitOR(SDNode *N);
254     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
255     SDValue visitXOR(SDNode *N);
256     SDValue SimplifyVBinOp(SDNode *N);
257     SDValue visitSHL(SDNode *N);
258     SDValue visitSRA(SDNode *N);
259     SDValue visitSRL(SDNode *N);
260     SDValue visitRotate(SDNode *N);
261     SDValue visitBSWAP(SDNode *N);
262     SDValue visitBITREVERSE(SDNode *N);
263     SDValue visitCTLZ(SDNode *N);
264     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
265     SDValue visitCTTZ(SDNode *N);
266     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
267     SDValue visitCTPOP(SDNode *N);
268     SDValue visitSELECT(SDNode *N);
269     SDValue visitVSELECT(SDNode *N);
270     SDValue visitSELECT_CC(SDNode *N);
271     SDValue visitSETCC(SDNode *N);
272     SDValue visitSETCCE(SDNode *N);
273     SDValue visitSIGN_EXTEND(SDNode *N);
274     SDValue visitZERO_EXTEND(SDNode *N);
275     SDValue visitANY_EXTEND(SDNode *N);
276     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
277     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
278     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
279     SDValue visitTRUNCATE(SDNode *N);
280     SDValue visitBITCAST(SDNode *N);
281     SDValue visitBUILD_PAIR(SDNode *N);
282     SDValue visitFADD(SDNode *N);
283     SDValue visitFSUB(SDNode *N);
284     SDValue visitFMUL(SDNode *N);
285     SDValue visitFMA(SDNode *N);
286     SDValue visitFDIV(SDNode *N);
287     SDValue visitFREM(SDNode *N);
288     SDValue visitFSQRT(SDNode *N);
289     SDValue visitFCOPYSIGN(SDNode *N);
290     SDValue visitSINT_TO_FP(SDNode *N);
291     SDValue visitUINT_TO_FP(SDNode *N);
292     SDValue visitFP_TO_SINT(SDNode *N);
293     SDValue visitFP_TO_UINT(SDNode *N);
294     SDValue visitFP_ROUND(SDNode *N);
295     SDValue visitFP_ROUND_INREG(SDNode *N);
296     SDValue visitFP_EXTEND(SDNode *N);
297     SDValue visitFNEG(SDNode *N);
298     SDValue visitFABS(SDNode *N);
299     SDValue visitFCEIL(SDNode *N);
300     SDValue visitFTRUNC(SDNode *N);
301     SDValue visitFFLOOR(SDNode *N);
302     SDValue visitFMINNUM(SDNode *N);
303     SDValue visitFMAXNUM(SDNode *N);
304     SDValue visitBRCOND(SDNode *N);
305     SDValue visitBR_CC(SDNode *N);
306     SDValue visitLOAD(SDNode *N);
307 
308     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
309     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
310 
311     SDValue visitSTORE(SDNode *N);
312     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
313     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
314     SDValue visitBUILD_VECTOR(SDNode *N);
315     SDValue visitCONCAT_VECTORS(SDNode *N);
316     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
317     SDValue visitVECTOR_SHUFFLE(SDNode *N);
318     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
319     SDValue visitINSERT_SUBVECTOR(SDNode *N);
320     SDValue visitMLOAD(SDNode *N);
321     SDValue visitMSTORE(SDNode *N);
322     SDValue visitMGATHER(SDNode *N);
323     SDValue visitMSCATTER(SDNode *N);
324     SDValue visitFP_TO_FP16(SDNode *N);
325     SDValue visitFP16_TO_FP(SDNode *N);
326 
327     SDValue visitFADDForFMACombine(SDNode *N);
328     SDValue visitFSUBForFMACombine(SDNode *N);
329     SDValue visitFMULForFMACombine(SDNode *N);
330 
331     SDValue XformToShuffleWithZero(SDNode *N);
332     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
333                            SDValue RHS);
334 
335     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
336 
337     SDValue foldSelectOfConstants(SDNode *N);
338     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
339     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
340     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
341     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
342                              SDValue N2, SDValue N3, ISD::CondCode CC,
343                              bool NotExtCompare = false);
344     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
345                           const SDLoc &DL, bool foldBooleans = true);
346 
347     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
348                            SDValue &CC) const;
349     bool isOneUseSetCC(SDValue N) const;
350 
351     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
352                                          unsigned HiOp);
353     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
354     SDValue CombineExtLoad(SDNode *N);
355     SDValue combineRepeatedFPDivisors(SDNode *N);
356     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
357     SDValue BuildSDIV(SDNode *N);
358     SDValue BuildSDIVPow2(SDNode *N);
359     SDValue BuildUDIV(SDNode *N);
360     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
361     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
362     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
363     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
364     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
365                                 SDNodeFlags *Flags, bool Reciprocal);
366     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
367                                 SDNodeFlags *Flags, bool Reciprocal);
368     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
369                                bool DemandHighBits = true);
370     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
371     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
372                               SDValue InnerPos, SDValue InnerNeg,
373                               unsigned PosOpcode, unsigned NegOpcode,
374                               const SDLoc &DL);
375     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
376     SDValue ReduceLoadWidth(SDNode *N);
377     SDValue ReduceLoadOpStoreWidth(SDNode *N);
378     SDValue splitMergedValStore(StoreSDNode *ST);
379     SDValue TransformFPLoadStorePair(SDNode *N);
380     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
381     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
382     SDValue reduceBuildVecToShuffle(SDNode *N);
383     SDValue createBuildVecShuffle(SDLoc DL, SDNode *N, ArrayRef<int> VectorMask,
384                                   SDValue VecIn1, SDValue VecIn2,
385                                   unsigned LeftIdx);
386 
387     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
388 
389     /// Walk up chain skipping non-aliasing memory nodes,
390     /// looking for aliasing nodes and adding them to the Aliases vector.
391     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
392                           SmallVectorImpl<SDValue> &Aliases);
393 
394     /// Return true if there is any possibility that the two addresses overlap.
395     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
396 
397     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
398     /// chain (aliasing node.)
399     SDValue FindBetterChain(SDNode *N, SDValue Chain);
400 
401     /// Try to replace a store and any possibly adjacent stores on
402     /// consecutive chains with better chains. Return true only if St is
403     /// replaced.
404     ///
405     /// Notice that other chains may still be replaced even if the function
406     /// returns false.
407     bool findBetterNeighborChains(StoreSDNode *St);
408 
409     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
410     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
411 
412     /// Holds a pointer to an LSBaseSDNode as well as information on where it
413     /// is located in a sequence of memory operations connected by a chain.
414     struct MemOpLink {
415       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
416       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
417       // Ptr to the mem node.
418       LSBaseSDNode *MemNode;
419       // Offset from the base ptr.
420       int64_t OffsetFromBase;
421       // What is the sequence number of this mem node.
422       // Lowest mem operand in the DAG starts at zero.
423       unsigned SequenceNum;
424     };
425 
426     /// This is a helper function for visitMUL to check the profitability
427     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
428     /// MulNode is the original multiply, AddNode is (add x, c1),
429     /// and ConstNode is c2.
430     bool isMulAddWithConstProfitable(SDNode *MulNode,
431                                      SDValue &AddNode,
432                                      SDValue &ConstNode);
433 
434     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
435     /// constant build_vector of the stored constant values in Stores.
436     SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL,
437                                          ArrayRef<MemOpLink> Stores,
438                                          SmallVectorImpl<SDValue> &Chains,
439                                          EVT Ty) const;
440 
441     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
442     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
443     /// the type of the loaded value to be extended.  LoadedVT returns the type
444     /// of the original loaded value.  NarrowLoad returns whether the load would
445     /// need to be narrowed in order to match.
446     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
447                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
448                           bool &NarrowLoad);
449 
450     /// This is a helper function for MergeConsecutiveStores. When the source
451     /// elements of the consecutive stores are all constants or all extracted
452     /// vector elements, try to merge them into one larger store.
453     /// \return number of stores that were merged into a merged store (always
454     /// a prefix of \p StoreNode).
455     bool MergeStoresOfConstantsOrVecElts(
456         SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
457         bool IsConstantSrc, bool UseVector);
458 
459     /// This is a helper function for MergeConsecutiveStores.
460     /// Stores that may be merged are placed in StoreNodes.
461     /// Loads that may alias with those stores are placed in AliasLoadNodes.
462     void getStoreMergeAndAliasCandidates(
463         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
464         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
465 
466     /// Helper function for MergeConsecutiveStores. Checks if
467     /// Candidate stores have indirect dependency through their
468     /// operands. \return True if safe to merge
469     bool checkMergeStoreCandidatesForDependencies(
470         SmallVectorImpl<MemOpLink> &StoreNodes);
471 
472     /// Merge consecutive store operations into a wide store.
473     /// This optimization uses wide integers or vectors when possible.
474     /// \return number of stores that were merged into a merged store (the
475     /// affected nodes are stored as a prefix in \p StoreNodes).
476     bool MergeConsecutiveStores(StoreSDNode *N,
477                                 SmallVectorImpl<MemOpLink> &StoreNodes);
478 
479     /// \brief Try to transform a truncation where C is a constant:
480     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
481     ///
482     /// \p N needs to be a truncation and its first operand an AND. Other
483     /// requirements are checked by the function (e.g. that trunc is
484     /// single-use) and if missed an empty SDValue is returned.
485     SDValue distributeTruncateThroughAnd(SDNode *N);
486 
487   public:
488     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
489         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
490           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
491       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
492     }
493 
494     /// Runs the dag combiner on all nodes in the work list
495     void Run(CombineLevel AtLevel);
496 
497     SelectionDAG &getDAG() const { return DAG; }
498 
499     /// Returns a type large enough to hold any valid shift amount - before type
500     /// legalization these can be huge.
501     EVT getShiftAmountTy(EVT LHSTy) {
502       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
503       if (LHSTy.isVector())
504         return LHSTy;
505       auto &DL = DAG.getDataLayout();
506       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
507                         : TLI.getPointerTy(DL);
508     }
509 
510     /// This method returns true if we are running before type legalization or
511     /// if the specified VT is legal.
512     bool isTypeLegal(const EVT &VT) {
513       if (!LegalTypes) return true;
514       return TLI.isTypeLegal(VT);
515     }
516 
517     /// Convenience wrapper around TargetLowering::getSetCCResultType
518     EVT getSetCCResultType(EVT VT) const {
519       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
520     }
521   };
522 }
523 
524 
525 namespace {
526 /// This class is a DAGUpdateListener that removes any deleted
527 /// nodes from the worklist.
528 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
529   DAGCombiner &DC;
530 public:
531   explicit WorklistRemover(DAGCombiner &dc)
532     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
533 
534   void NodeDeleted(SDNode *N, SDNode *E) override {
535     DC.removeFromWorklist(N);
536   }
537 };
538 }
539 
540 //===----------------------------------------------------------------------===//
541 //  TargetLowering::DAGCombinerInfo implementation
542 //===----------------------------------------------------------------------===//
543 
544 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
545   ((DAGCombiner*)DC)->AddToWorklist(N);
546 }
547 
548 SDValue TargetLowering::DAGCombinerInfo::
549 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
550   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
551 }
552 
553 SDValue TargetLowering::DAGCombinerInfo::
554 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
555   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
556 }
557 
558 
559 SDValue TargetLowering::DAGCombinerInfo::
560 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
561   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
562 }
563 
564 void TargetLowering::DAGCombinerInfo::
565 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
566   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
567 }
568 
569 //===----------------------------------------------------------------------===//
570 // Helper Functions
571 //===----------------------------------------------------------------------===//
572 
573 void DAGCombiner::deleteAndRecombine(SDNode *N) {
574   removeFromWorklist(N);
575 
576   // If the operands of this node are only used by the node, they will now be
577   // dead. Make sure to re-visit them and recursively delete dead nodes.
578   for (const SDValue &Op : N->ops())
579     // For an operand generating multiple values, one of the values may
580     // become dead allowing further simplification (e.g. split index
581     // arithmetic from an indexed load).
582     if (Op->hasOneUse() || Op->getNumValues() > 1)
583       AddToWorklist(Op.getNode());
584 
585   DAG.DeleteNode(N);
586 }
587 
588 /// Return 1 if we can compute the negated form of the specified expression for
589 /// the same cost as the expression itself, or 2 if we can compute the negated
590 /// form more cheaply than the expression itself.
591 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
592                                const TargetLowering &TLI,
593                                const TargetOptions *Options,
594                                unsigned Depth = 0) {
595   // fneg is removable even if it has multiple uses.
596   if (Op.getOpcode() == ISD::FNEG) return 2;
597 
598   // Don't allow anything with multiple uses.
599   if (!Op.hasOneUse()) return 0;
600 
601   // Don't recurse exponentially.
602   if (Depth > 6) return 0;
603 
604   switch (Op.getOpcode()) {
605   default: return false;
606   case ISD::ConstantFP:
607     // Don't invert constant FP values after legalize.  The negated constant
608     // isn't necessarily legal.
609     return LegalOperations ? 0 : 1;
610   case ISD::FADD:
611     // FIXME: determine better conditions for this xform.
612     if (!Options->UnsafeFPMath) return 0;
613 
614     // After operation legalization, it might not be legal to create new FSUBs.
615     if (LegalOperations &&
616         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
617       return 0;
618 
619     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
620     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
621                                     Options, Depth + 1))
622       return V;
623     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
624     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
625                               Depth + 1);
626   case ISD::FSUB:
627     // We can't turn -(A-B) into B-A when we honor signed zeros.
628     if (!Options->UnsafeFPMath && !Op.getNode()->getFlags()->hasNoSignedZeros())
629       return 0;
630 
631     // fold (fneg (fsub A, B)) -> (fsub B, A)
632     return 1;
633 
634   case ISD::FMUL:
635   case ISD::FDIV:
636     if (Options->HonorSignDependentRoundingFPMath()) return 0;
637 
638     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
639     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
640                                     Options, Depth + 1))
641       return V;
642 
643     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
644                               Depth + 1);
645 
646   case ISD::FP_EXTEND:
647   case ISD::FP_ROUND:
648   case ISD::FSIN:
649     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
650                               Depth + 1);
651   }
652 }
653 
654 /// If isNegatibleForFree returns true, return the newly negated expression.
655 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
656                                     bool LegalOperations, unsigned Depth = 0) {
657   const TargetOptions &Options = DAG.getTarget().Options;
658   // fneg is removable even if it has multiple uses.
659   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
660 
661   // Don't allow anything with multiple uses.
662   assert(Op.hasOneUse() && "Unknown reuse!");
663 
664   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
665 
666   const SDNodeFlags *Flags = Op.getNode()->getFlags();
667 
668   switch (Op.getOpcode()) {
669   default: llvm_unreachable("Unknown code");
670   case ISD::ConstantFP: {
671     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
672     V.changeSign();
673     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
674   }
675   case ISD::FADD:
676     // FIXME: determine better conditions for this xform.
677     assert(Options.UnsafeFPMath);
678 
679     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
680     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
681                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
682       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
683                          GetNegatedExpression(Op.getOperand(0), DAG,
684                                               LegalOperations, Depth+1),
685                          Op.getOperand(1), Flags);
686     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
687     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
688                        GetNegatedExpression(Op.getOperand(1), DAG,
689                                             LegalOperations, Depth+1),
690                        Op.getOperand(0), Flags);
691   case ISD::FSUB:
692     // fold (fneg (fsub 0, B)) -> B
693     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
694       if (N0CFP->isZero())
695         return Op.getOperand(1);
696 
697     // fold (fneg (fsub A, B)) -> (fsub B, A)
698     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
699                        Op.getOperand(1), Op.getOperand(0), Flags);
700 
701   case ISD::FMUL:
702   case ISD::FDIV:
703     assert(!Options.HonorSignDependentRoundingFPMath());
704 
705     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
706     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
707                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
708       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
709                          GetNegatedExpression(Op.getOperand(0), DAG,
710                                               LegalOperations, Depth+1),
711                          Op.getOperand(1), Flags);
712 
713     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
714     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
715                        Op.getOperand(0),
716                        GetNegatedExpression(Op.getOperand(1), DAG,
717                                             LegalOperations, Depth+1), Flags);
718 
719   case ISD::FP_EXTEND:
720   case ISD::FSIN:
721     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
722                        GetNegatedExpression(Op.getOperand(0), DAG,
723                                             LegalOperations, Depth+1));
724   case ISD::FP_ROUND:
725       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
726                          GetNegatedExpression(Op.getOperand(0), DAG,
727                                               LegalOperations, Depth+1),
728                          Op.getOperand(1));
729   }
730 }
731 
732 // APInts must be the same size for most operations, this helper
733 // function zero extends the shorter of the pair so that they match.
734 // We provide an Offset so that we can create bitwidths that won't overflow.
735 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
736   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
737   LHS = LHS.zextOrSelf(Bits);
738   RHS = RHS.zextOrSelf(Bits);
739 }
740 
741 // Return true if this node is a setcc, or is a select_cc
742 // that selects between the target values used for true and false, making it
743 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
744 // the appropriate nodes based on the type of node we are checking. This
745 // simplifies life a bit for the callers.
746 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
747                                     SDValue &CC) const {
748   if (N.getOpcode() == ISD::SETCC) {
749     LHS = N.getOperand(0);
750     RHS = N.getOperand(1);
751     CC  = N.getOperand(2);
752     return true;
753   }
754 
755   if (N.getOpcode() != ISD::SELECT_CC ||
756       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
757       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
758     return false;
759 
760   if (TLI.getBooleanContents(N.getValueType()) ==
761       TargetLowering::UndefinedBooleanContent)
762     return false;
763 
764   LHS = N.getOperand(0);
765   RHS = N.getOperand(1);
766   CC  = N.getOperand(4);
767   return true;
768 }
769 
770 /// Return true if this is a SetCC-equivalent operation with only one use.
771 /// If this is true, it allows the users to invert the operation for free when
772 /// it is profitable to do so.
773 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
774   SDValue N0, N1, N2;
775   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
776     return true;
777   return false;
778 }
779 
780 // \brief Returns the SDNode if it is a constant float BuildVector
781 // or constant float.
782 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
783   if (isa<ConstantFPSDNode>(N))
784     return N.getNode();
785   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
786     return N.getNode();
787   return nullptr;
788 }
789 
790 // Determines if it is a constant integer or a build vector of constant
791 // integers (and undefs).
792 // Do not permit build vector implicit truncation.
793 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
794   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
795     return !(Const->isOpaque() && NoOpaques);
796   if (N.getOpcode() != ISD::BUILD_VECTOR)
797     return false;
798   unsigned BitWidth = N.getScalarValueSizeInBits();
799   for (const SDValue &Op : N->op_values()) {
800     if (Op.isUndef())
801       continue;
802     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
803     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
804         (Const->isOpaque() && NoOpaques))
805       return false;
806   }
807   return true;
808 }
809 
810 // Determines if it is a constant null integer or a splatted vector of a
811 // constant null integer (with no undefs).
812 // Build vector implicit truncation is not an issue for null values.
813 static bool isNullConstantOrNullSplatConstant(SDValue N) {
814   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
815     return Splat->isNullValue();
816   return false;
817 }
818 
819 // Determines if it is a constant integer of one or a splatted vector of a
820 // constant integer of one (with no undefs).
821 // Do not permit build vector implicit truncation.
822 static bool isOneConstantOrOneSplatConstant(SDValue N) {
823   unsigned BitWidth = N.getScalarValueSizeInBits();
824   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
825     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
826   return false;
827 }
828 
829 // Determines if it is a constant integer of all ones or a splatted vector of a
830 // constant integer of all ones (with no undefs).
831 // Do not permit build vector implicit truncation.
832 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
833   unsigned BitWidth = N.getScalarValueSizeInBits();
834   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
835     return Splat->isAllOnesValue() &&
836            Splat->getAPIntValue().getBitWidth() == BitWidth;
837   return false;
838 }
839 
840 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
841 // undef's.
842 static bool isAnyConstantBuildVector(const SDNode *N) {
843   return ISD::isBuildVectorOfConstantSDNodes(N) ||
844          ISD::isBuildVectorOfConstantFPSDNodes(N);
845 }
846 
847 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
848                                     SDValue N1) {
849   EVT VT = N0.getValueType();
850   if (N0.getOpcode() == Opc) {
851     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
852       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
853         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
854         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
855           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
856         return SDValue();
857       }
858       if (N0.hasOneUse()) {
859         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
860         // use
861         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
862         if (!OpNode.getNode())
863           return SDValue();
864         AddToWorklist(OpNode.getNode());
865         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
866       }
867     }
868   }
869 
870   if (N1.getOpcode() == Opc) {
871     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
872       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
873         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
874         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
875           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
876         return SDValue();
877       }
878       if (N1.hasOneUse()) {
879         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
880         // use
881         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
882         if (!OpNode.getNode())
883           return SDValue();
884         AddToWorklist(OpNode.getNode());
885         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
886       }
887     }
888   }
889 
890   return SDValue();
891 }
892 
893 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
894                                bool AddTo) {
895   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
896   ++NodesCombined;
897   DEBUG(dbgs() << "\nReplacing.1 ";
898         N->dump(&DAG);
899         dbgs() << "\nWith: ";
900         To[0].getNode()->dump(&DAG);
901         dbgs() << " and " << NumTo-1 << " other values\n");
902   for (unsigned i = 0, e = NumTo; i != e; ++i)
903     assert((!To[i].getNode() ||
904             N->getValueType(i) == To[i].getValueType()) &&
905            "Cannot combine value to value of different type!");
906 
907   WorklistRemover DeadNodes(*this);
908   DAG.ReplaceAllUsesWith(N, To);
909   if (AddTo) {
910     // Push the new nodes and any users onto the worklist
911     for (unsigned i = 0, e = NumTo; i != e; ++i) {
912       if (To[i].getNode()) {
913         AddToWorklist(To[i].getNode());
914         AddUsersToWorklist(To[i].getNode());
915       }
916     }
917   }
918 
919   // Finally, if the node is now dead, remove it from the graph.  The node
920   // may not be dead if the replacement process recursively simplified to
921   // something else needing this node.
922   if (N->use_empty())
923     deleteAndRecombine(N);
924   return SDValue(N, 0);
925 }
926 
927 void DAGCombiner::
928 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
929   // Replace all uses.  If any nodes become isomorphic to other nodes and
930   // are deleted, make sure to remove them from our worklist.
931   WorklistRemover DeadNodes(*this);
932   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
933 
934   // Push the new node and any (possibly new) users onto the worklist.
935   AddToWorklist(TLO.New.getNode());
936   AddUsersToWorklist(TLO.New.getNode());
937 
938   // Finally, if the node is now dead, remove it from the graph.  The node
939   // may not be dead if the replacement process recursively simplified to
940   // something else needing this node.
941   if (TLO.Old.getNode()->use_empty())
942     deleteAndRecombine(TLO.Old.getNode());
943 }
944 
945 /// Check the specified integer node value to see if it can be simplified or if
946 /// things it uses can be simplified by bit propagation. If so, return true.
947 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
948   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
949   APInt KnownZero, KnownOne;
950   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
951     return false;
952 
953   // Revisit the node.
954   AddToWorklist(Op.getNode());
955 
956   // Replace the old value with the new one.
957   ++NodesCombined;
958   DEBUG(dbgs() << "\nReplacing.2 ";
959         TLO.Old.getNode()->dump(&DAG);
960         dbgs() << "\nWith: ";
961         TLO.New.getNode()->dump(&DAG);
962         dbgs() << '\n');
963 
964   CommitTargetLoweringOpt(TLO);
965   return true;
966 }
967 
968 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
969   SDLoc DL(Load);
970   EVT VT = Load->getValueType(0);
971   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
972 
973   DEBUG(dbgs() << "\nReplacing.9 ";
974         Load->dump(&DAG);
975         dbgs() << "\nWith: ";
976         Trunc.getNode()->dump(&DAG);
977         dbgs() << '\n');
978   WorklistRemover DeadNodes(*this);
979   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
980   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
981   deleteAndRecombine(Load);
982   AddToWorklist(Trunc.getNode());
983 }
984 
985 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
986   Replace = false;
987   SDLoc DL(Op);
988   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
989     LoadSDNode *LD = cast<LoadSDNode>(Op);
990     EVT MemVT = LD->getMemoryVT();
991     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
992       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
993                                                        : ISD::EXTLOAD)
994       : LD->getExtensionType();
995     Replace = true;
996     return DAG.getExtLoad(ExtType, DL, PVT,
997                           LD->getChain(), LD->getBasePtr(),
998                           MemVT, LD->getMemOperand());
999   }
1000 
1001   unsigned Opc = Op.getOpcode();
1002   switch (Opc) {
1003   default: break;
1004   case ISD::AssertSext:
1005     return DAG.getNode(ISD::AssertSext, DL, PVT,
1006                        SExtPromoteOperand(Op.getOperand(0), PVT),
1007                        Op.getOperand(1));
1008   case ISD::AssertZext:
1009     return DAG.getNode(ISD::AssertZext, DL, PVT,
1010                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1011                        Op.getOperand(1));
1012   case ISD::Constant: {
1013     unsigned ExtOpc =
1014       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1015     return DAG.getNode(ExtOpc, DL, PVT, Op);
1016   }
1017   }
1018 
1019   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1020     return SDValue();
1021   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1022 }
1023 
1024 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1025   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1026     return SDValue();
1027   EVT OldVT = Op.getValueType();
1028   SDLoc DL(Op);
1029   bool Replace = false;
1030   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1031   if (!NewOp.getNode())
1032     return SDValue();
1033   AddToWorklist(NewOp.getNode());
1034 
1035   if (Replace)
1036     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1037   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1038                      DAG.getValueType(OldVT));
1039 }
1040 
1041 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1042   EVT OldVT = Op.getValueType();
1043   SDLoc DL(Op);
1044   bool Replace = false;
1045   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1046   if (!NewOp.getNode())
1047     return SDValue();
1048   AddToWorklist(NewOp.getNode());
1049 
1050   if (Replace)
1051     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1052   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1053 }
1054 
1055 /// Promote the specified integer binary operation if the target indicates it is
1056 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1057 /// i32 since i16 instructions are longer.
1058 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1059   if (!LegalOperations)
1060     return SDValue();
1061 
1062   EVT VT = Op.getValueType();
1063   if (VT.isVector() || !VT.isInteger())
1064     return SDValue();
1065 
1066   // If operation type is 'undesirable', e.g. i16 on x86, consider
1067   // promoting it.
1068   unsigned Opc = Op.getOpcode();
1069   if (TLI.isTypeDesirableForOp(Opc, VT))
1070     return SDValue();
1071 
1072   EVT PVT = VT;
1073   // Consult target whether it is a good idea to promote this operation and
1074   // what's the right type to promote it to.
1075   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1076     assert(PVT != VT && "Don't know what type to promote to!");
1077 
1078     bool Replace0 = false;
1079     SDValue N0 = Op.getOperand(0);
1080     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1081     if (!NN0.getNode())
1082       return SDValue();
1083 
1084     bool Replace1 = false;
1085     SDValue N1 = Op.getOperand(1);
1086     SDValue NN1;
1087     if (N0 == N1)
1088       NN1 = NN0;
1089     else {
1090       NN1 = PromoteOperand(N1, PVT, Replace1);
1091       if (!NN1.getNode())
1092         return SDValue();
1093     }
1094 
1095     AddToWorklist(NN0.getNode());
1096     if (NN1.getNode())
1097       AddToWorklist(NN1.getNode());
1098 
1099     if (Replace0)
1100       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1101     if (Replace1)
1102       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1103 
1104     DEBUG(dbgs() << "\nPromoting ";
1105           Op.getNode()->dump(&DAG));
1106     SDLoc DL(Op);
1107     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1108                        DAG.getNode(Opc, DL, PVT, NN0, NN1));
1109   }
1110   return SDValue();
1111 }
1112 
1113 /// Promote the specified integer shift operation if the target indicates it is
1114 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1115 /// i32 since i16 instructions are longer.
1116 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1117   if (!LegalOperations)
1118     return SDValue();
1119 
1120   EVT VT = Op.getValueType();
1121   if (VT.isVector() || !VT.isInteger())
1122     return SDValue();
1123 
1124   // If operation type is 'undesirable', e.g. i16 on x86, consider
1125   // promoting it.
1126   unsigned Opc = Op.getOpcode();
1127   if (TLI.isTypeDesirableForOp(Opc, VT))
1128     return SDValue();
1129 
1130   EVT PVT = VT;
1131   // Consult target whether it is a good idea to promote this operation and
1132   // what's the right type to promote it to.
1133   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1134     assert(PVT != VT && "Don't know what type to promote to!");
1135 
1136     bool Replace = false;
1137     SDValue N0 = Op.getOperand(0);
1138     if (Opc == ISD::SRA)
1139       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1140     else if (Opc == ISD::SRL)
1141       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1142     else
1143       N0 = PromoteOperand(N0, PVT, Replace);
1144     if (!N0.getNode())
1145       return SDValue();
1146 
1147     AddToWorklist(N0.getNode());
1148     if (Replace)
1149       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1150 
1151     DEBUG(dbgs() << "\nPromoting ";
1152           Op.getNode()->dump(&DAG));
1153     SDLoc DL(Op);
1154     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1155                        DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1)));
1156   }
1157   return SDValue();
1158 }
1159 
1160 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1161   if (!LegalOperations)
1162     return SDValue();
1163 
1164   EVT VT = Op.getValueType();
1165   if (VT.isVector() || !VT.isInteger())
1166     return SDValue();
1167 
1168   // If operation type is 'undesirable', e.g. i16 on x86, consider
1169   // promoting it.
1170   unsigned Opc = Op.getOpcode();
1171   if (TLI.isTypeDesirableForOp(Opc, VT))
1172     return SDValue();
1173 
1174   EVT PVT = VT;
1175   // Consult target whether it is a good idea to promote this operation and
1176   // what's the right type to promote it to.
1177   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1178     assert(PVT != VT && "Don't know what type to promote to!");
1179     // fold (aext (aext x)) -> (aext x)
1180     // fold (aext (zext x)) -> (zext x)
1181     // fold (aext (sext x)) -> (sext x)
1182     DEBUG(dbgs() << "\nPromoting ";
1183           Op.getNode()->dump(&DAG));
1184     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1185   }
1186   return SDValue();
1187 }
1188 
1189 bool DAGCombiner::PromoteLoad(SDValue Op) {
1190   if (!LegalOperations)
1191     return false;
1192 
1193   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1194     return false;
1195 
1196   EVT VT = Op.getValueType();
1197   if (VT.isVector() || !VT.isInteger())
1198     return false;
1199 
1200   // If operation type is 'undesirable', e.g. i16 on x86, consider
1201   // promoting it.
1202   unsigned Opc = Op.getOpcode();
1203   if (TLI.isTypeDesirableForOp(Opc, VT))
1204     return false;
1205 
1206   EVT PVT = VT;
1207   // Consult target whether it is a good idea to promote this operation and
1208   // what's the right type to promote it to.
1209   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1210     assert(PVT != VT && "Don't know what type to promote to!");
1211 
1212     SDLoc DL(Op);
1213     SDNode *N = Op.getNode();
1214     LoadSDNode *LD = cast<LoadSDNode>(N);
1215     EVT MemVT = LD->getMemoryVT();
1216     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1217       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1218                                                        : ISD::EXTLOAD)
1219       : LD->getExtensionType();
1220     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1221                                    LD->getChain(), LD->getBasePtr(),
1222                                    MemVT, LD->getMemOperand());
1223     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1224 
1225     DEBUG(dbgs() << "\nPromoting ";
1226           N->dump(&DAG);
1227           dbgs() << "\nTo: ";
1228           Result.getNode()->dump(&DAG);
1229           dbgs() << '\n');
1230     WorklistRemover DeadNodes(*this);
1231     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1232     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1233     deleteAndRecombine(N);
1234     AddToWorklist(Result.getNode());
1235     return true;
1236   }
1237   return false;
1238 }
1239 
1240 /// \brief Recursively delete a node which has no uses and any operands for
1241 /// which it is the only use.
1242 ///
1243 /// Note that this both deletes the nodes and removes them from the worklist.
1244 /// It also adds any nodes who have had a user deleted to the worklist as they
1245 /// may now have only one use and subject to other combines.
1246 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1247   if (!N->use_empty())
1248     return false;
1249 
1250   SmallSetVector<SDNode *, 16> Nodes;
1251   Nodes.insert(N);
1252   do {
1253     N = Nodes.pop_back_val();
1254     if (!N)
1255       continue;
1256 
1257     if (N->use_empty()) {
1258       for (const SDValue &ChildN : N->op_values())
1259         Nodes.insert(ChildN.getNode());
1260 
1261       removeFromWorklist(N);
1262       DAG.DeleteNode(N);
1263     } else {
1264       AddToWorklist(N);
1265     }
1266   } while (!Nodes.empty());
1267   return true;
1268 }
1269 
1270 //===----------------------------------------------------------------------===//
1271 //  Main DAG Combiner implementation
1272 //===----------------------------------------------------------------------===//
1273 
1274 void DAGCombiner::Run(CombineLevel AtLevel) {
1275   // set the instance variables, so that the various visit routines may use it.
1276   Level = AtLevel;
1277   LegalOperations = Level >= AfterLegalizeVectorOps;
1278   LegalTypes = Level >= AfterLegalizeTypes;
1279 
1280   // Add all the dag nodes to the worklist.
1281   for (SDNode &Node : DAG.allnodes())
1282     AddToWorklist(&Node);
1283 
1284   // Create a dummy node (which is not added to allnodes), that adds a reference
1285   // to the root node, preventing it from being deleted, and tracking any
1286   // changes of the root.
1287   HandleSDNode Dummy(DAG.getRoot());
1288 
1289   // While the worklist isn't empty, find a node and try to combine it.
1290   while (!WorklistMap.empty()) {
1291     SDNode *N;
1292     // The Worklist holds the SDNodes in order, but it may contain null entries.
1293     do {
1294       N = Worklist.pop_back_val();
1295     } while (!N);
1296 
1297     bool GoodWorklistEntry = WorklistMap.erase(N);
1298     (void)GoodWorklistEntry;
1299     assert(GoodWorklistEntry &&
1300            "Found a worklist entry without a corresponding map entry!");
1301 
1302     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1303     // N is deleted from the DAG, since they too may now be dead or may have a
1304     // reduced number of uses, allowing other xforms.
1305     if (recursivelyDeleteUnusedNodes(N))
1306       continue;
1307 
1308     WorklistRemover DeadNodes(*this);
1309 
1310     // If this combine is running after legalizing the DAG, re-legalize any
1311     // nodes pulled off the worklist.
1312     if (Level == AfterLegalizeDAG) {
1313       SmallSetVector<SDNode *, 16> UpdatedNodes;
1314       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1315 
1316       for (SDNode *LN : UpdatedNodes) {
1317         AddToWorklist(LN);
1318         AddUsersToWorklist(LN);
1319       }
1320       if (!NIsValid)
1321         continue;
1322     }
1323 
1324     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1325 
1326     // Add any operands of the new node which have not yet been combined to the
1327     // worklist as well. Because the worklist uniques things already, this
1328     // won't repeatedly process the same operand.
1329     CombinedNodes.insert(N);
1330     for (const SDValue &ChildN : N->op_values())
1331       if (!CombinedNodes.count(ChildN.getNode()))
1332         AddToWorklist(ChildN.getNode());
1333 
1334     SDValue RV = combine(N);
1335 
1336     if (!RV.getNode())
1337       continue;
1338 
1339     ++NodesCombined;
1340 
1341     // If we get back the same node we passed in, rather than a new node or
1342     // zero, we know that the node must have defined multiple values and
1343     // CombineTo was used.  Since CombineTo takes care of the worklist
1344     // mechanics for us, we have no work to do in this case.
1345     if (RV.getNode() == N)
1346       continue;
1347 
1348     assert(N->getOpcode() != ISD::DELETED_NODE &&
1349            RV.getOpcode() != ISD::DELETED_NODE &&
1350            "Node was deleted but visit returned new node!");
1351 
1352     DEBUG(dbgs() << " ... into: ";
1353           RV.getNode()->dump(&DAG));
1354 
1355     if (N->getNumValues() == RV.getNode()->getNumValues())
1356       DAG.ReplaceAllUsesWith(N, RV.getNode());
1357     else {
1358       assert(N->getValueType(0) == RV.getValueType() &&
1359              N->getNumValues() == 1 && "Type mismatch");
1360       SDValue OpV = RV;
1361       DAG.ReplaceAllUsesWith(N, &OpV);
1362     }
1363 
1364     // Push the new node and any users onto the worklist
1365     AddToWorklist(RV.getNode());
1366     AddUsersToWorklist(RV.getNode());
1367 
1368     // Finally, if the node is now dead, remove it from the graph.  The node
1369     // may not be dead if the replacement process recursively simplified to
1370     // something else needing this node. This will also take care of adding any
1371     // operands which have lost a user to the worklist.
1372     recursivelyDeleteUnusedNodes(N);
1373   }
1374 
1375   // If the root changed (e.g. it was a dead load, update the root).
1376   DAG.setRoot(Dummy.getValue());
1377   DAG.RemoveDeadNodes();
1378 }
1379 
1380 SDValue DAGCombiner::visit(SDNode *N) {
1381   switch (N->getOpcode()) {
1382   default: break;
1383   case ISD::TokenFactor:        return visitTokenFactor(N);
1384   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1385   case ISD::ADD:                return visitADD(N);
1386   case ISD::SUB:                return visitSUB(N);
1387   case ISD::ADDC:               return visitADDC(N);
1388   case ISD::SUBC:               return visitSUBC(N);
1389   case ISD::ADDE:               return visitADDE(N);
1390   case ISD::SUBE:               return visitSUBE(N);
1391   case ISD::MUL:                return visitMUL(N);
1392   case ISD::SDIV:               return visitSDIV(N);
1393   case ISD::UDIV:               return visitUDIV(N);
1394   case ISD::SREM:
1395   case ISD::UREM:               return visitREM(N);
1396   case ISD::MULHU:              return visitMULHU(N);
1397   case ISD::MULHS:              return visitMULHS(N);
1398   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1399   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1400   case ISD::SMULO:              return visitSMULO(N);
1401   case ISD::UMULO:              return visitUMULO(N);
1402   case ISD::SMIN:
1403   case ISD::SMAX:
1404   case ISD::UMIN:
1405   case ISD::UMAX:               return visitIMINMAX(N);
1406   case ISD::AND:                return visitAND(N);
1407   case ISD::OR:                 return visitOR(N);
1408   case ISD::XOR:                return visitXOR(N);
1409   case ISD::SHL:                return visitSHL(N);
1410   case ISD::SRA:                return visitSRA(N);
1411   case ISD::SRL:                return visitSRL(N);
1412   case ISD::ROTR:
1413   case ISD::ROTL:               return visitRotate(N);
1414   case ISD::BSWAP:              return visitBSWAP(N);
1415   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1416   case ISD::CTLZ:               return visitCTLZ(N);
1417   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1418   case ISD::CTTZ:               return visitCTTZ(N);
1419   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1420   case ISD::CTPOP:              return visitCTPOP(N);
1421   case ISD::SELECT:             return visitSELECT(N);
1422   case ISD::VSELECT:            return visitVSELECT(N);
1423   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1424   case ISD::SETCC:              return visitSETCC(N);
1425   case ISD::SETCCE:             return visitSETCCE(N);
1426   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1427   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1428   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1429   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1430   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1431   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1432   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1433   case ISD::BITCAST:            return visitBITCAST(N);
1434   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1435   case ISD::FADD:               return visitFADD(N);
1436   case ISD::FSUB:               return visitFSUB(N);
1437   case ISD::FMUL:               return visitFMUL(N);
1438   case ISD::FMA:                return visitFMA(N);
1439   case ISD::FDIV:               return visitFDIV(N);
1440   case ISD::FREM:               return visitFREM(N);
1441   case ISD::FSQRT:              return visitFSQRT(N);
1442   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1443   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1444   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1445   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1446   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1447   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1448   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1449   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1450   case ISD::FNEG:               return visitFNEG(N);
1451   case ISD::FABS:               return visitFABS(N);
1452   case ISD::FFLOOR:             return visitFFLOOR(N);
1453   case ISD::FMINNUM:            return visitFMINNUM(N);
1454   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1455   case ISD::FCEIL:              return visitFCEIL(N);
1456   case ISD::FTRUNC:             return visitFTRUNC(N);
1457   case ISD::BRCOND:             return visitBRCOND(N);
1458   case ISD::BR_CC:              return visitBR_CC(N);
1459   case ISD::LOAD:               return visitLOAD(N);
1460   case ISD::STORE:              return visitSTORE(N);
1461   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1462   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1463   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1464   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1465   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1466   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1467   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1468   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1469   case ISD::MGATHER:            return visitMGATHER(N);
1470   case ISD::MLOAD:              return visitMLOAD(N);
1471   case ISD::MSCATTER:           return visitMSCATTER(N);
1472   case ISD::MSTORE:             return visitMSTORE(N);
1473   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1474   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1475   }
1476   return SDValue();
1477 }
1478 
1479 SDValue DAGCombiner::combine(SDNode *N) {
1480   SDValue RV = visit(N);
1481 
1482   // If nothing happened, try a target-specific DAG combine.
1483   if (!RV.getNode()) {
1484     assert(N->getOpcode() != ISD::DELETED_NODE &&
1485            "Node was deleted but visit returned NULL!");
1486 
1487     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1488         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1489 
1490       // Expose the DAG combiner to the target combiner impls.
1491       TargetLowering::DAGCombinerInfo
1492         DagCombineInfo(DAG, Level, false, this);
1493 
1494       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1495     }
1496   }
1497 
1498   // If nothing happened still, try promoting the operation.
1499   if (!RV.getNode()) {
1500     switch (N->getOpcode()) {
1501     default: break;
1502     case ISD::ADD:
1503     case ISD::SUB:
1504     case ISD::MUL:
1505     case ISD::AND:
1506     case ISD::OR:
1507     case ISD::XOR:
1508       RV = PromoteIntBinOp(SDValue(N, 0));
1509       break;
1510     case ISD::SHL:
1511     case ISD::SRA:
1512     case ISD::SRL:
1513       RV = PromoteIntShiftOp(SDValue(N, 0));
1514       break;
1515     case ISD::SIGN_EXTEND:
1516     case ISD::ZERO_EXTEND:
1517     case ISD::ANY_EXTEND:
1518       RV = PromoteExtend(SDValue(N, 0));
1519       break;
1520     case ISD::LOAD:
1521       if (PromoteLoad(SDValue(N, 0)))
1522         RV = SDValue(N, 0);
1523       break;
1524     }
1525   }
1526 
1527   // If N is a commutative binary node, try commuting it to enable more
1528   // sdisel CSE.
1529   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1530       N->getNumValues() == 1) {
1531     SDValue N0 = N->getOperand(0);
1532     SDValue N1 = N->getOperand(1);
1533 
1534     // Constant operands are canonicalized to RHS.
1535     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1536       SDValue Ops[] = {N1, N0};
1537       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1538                                             N->getFlags());
1539       if (CSENode)
1540         return SDValue(CSENode, 0);
1541     }
1542   }
1543 
1544   return RV;
1545 }
1546 
1547 /// Given a node, return its input chain if it has one, otherwise return a null
1548 /// sd operand.
1549 static SDValue getInputChainForNode(SDNode *N) {
1550   if (unsigned NumOps = N->getNumOperands()) {
1551     if (N->getOperand(0).getValueType() == MVT::Other)
1552       return N->getOperand(0);
1553     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1554       return N->getOperand(NumOps-1);
1555     for (unsigned i = 1; i < NumOps-1; ++i)
1556       if (N->getOperand(i).getValueType() == MVT::Other)
1557         return N->getOperand(i);
1558   }
1559   return SDValue();
1560 }
1561 
1562 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1563   // If N has two operands, where one has an input chain equal to the other,
1564   // the 'other' chain is redundant.
1565   if (N->getNumOperands() == 2) {
1566     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1567       return N->getOperand(0);
1568     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1569       return N->getOperand(1);
1570   }
1571 
1572   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1573   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1574   SmallPtrSet<SDNode*, 16> SeenOps;
1575   bool Changed = false;             // If we should replace this token factor.
1576 
1577   // Start out with this token factor.
1578   TFs.push_back(N);
1579 
1580   // Iterate through token factors.  The TFs grows when new token factors are
1581   // encountered.
1582   for (unsigned i = 0; i < TFs.size(); ++i) {
1583     SDNode *TF = TFs[i];
1584 
1585     // Check each of the operands.
1586     for (const SDValue &Op : TF->op_values()) {
1587 
1588       switch (Op.getOpcode()) {
1589       case ISD::EntryToken:
1590         // Entry tokens don't need to be added to the list. They are
1591         // redundant.
1592         Changed = true;
1593         break;
1594 
1595       case ISD::TokenFactor:
1596         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1597           // Queue up for processing.
1598           TFs.push_back(Op.getNode());
1599           // Clean up in case the token factor is removed.
1600           AddToWorklist(Op.getNode());
1601           Changed = true;
1602           break;
1603         }
1604         LLVM_FALLTHROUGH;
1605 
1606       default:
1607         // Only add if it isn't already in the list.
1608         if (SeenOps.insert(Op.getNode()).second)
1609           Ops.push_back(Op);
1610         else
1611           Changed = true;
1612         break;
1613       }
1614     }
1615   }
1616 
1617   SDValue Result;
1618 
1619   // If we've changed things around then replace token factor.
1620   if (Changed) {
1621     if (Ops.empty()) {
1622       // The entry token is the only possible outcome.
1623       Result = DAG.getEntryNode();
1624     } else {
1625       // New and improved token factor.
1626       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1627     }
1628 
1629     // Add users to worklist if AA is enabled, since it may introduce
1630     // a lot of new chained token factors while removing memory deps.
1631     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1632       : DAG.getSubtarget().useAA();
1633     return CombineTo(N, Result, UseAA /*add to worklist*/);
1634   }
1635 
1636   return Result;
1637 }
1638 
1639 /// MERGE_VALUES can always be eliminated.
1640 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1641   WorklistRemover DeadNodes(*this);
1642   // Replacing results may cause a different MERGE_VALUES to suddenly
1643   // be CSE'd with N, and carry its uses with it. Iterate until no
1644   // uses remain, to ensure that the node can be safely deleted.
1645   // First add the users of this node to the work list so that they
1646   // can be tried again once they have new operands.
1647   AddUsersToWorklist(N);
1648   do {
1649     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1650       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1651   } while (!N->use_empty());
1652   deleteAndRecombine(N);
1653   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1654 }
1655 
1656 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1657 /// ConstantSDNode pointer else nullptr.
1658 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1659   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1660   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1661 }
1662 
1663 SDValue DAGCombiner::visitADD(SDNode *N) {
1664   SDValue N0 = N->getOperand(0);
1665   SDValue N1 = N->getOperand(1);
1666   EVT VT = N0.getValueType();
1667   SDLoc DL(N);
1668 
1669   // fold vector ops
1670   if (VT.isVector()) {
1671     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1672       return FoldedVOp;
1673 
1674     // fold (add x, 0) -> x, vector edition
1675     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1676       return N0;
1677     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1678       return N1;
1679   }
1680 
1681   // fold (add x, undef) -> undef
1682   if (N0.isUndef())
1683     return N0;
1684 
1685   if (N1.isUndef())
1686     return N1;
1687 
1688   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1689     // canonicalize constant to RHS
1690     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1691       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1692     // fold (add c1, c2) -> c1+c2
1693     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1694                                       N1.getNode());
1695   }
1696 
1697   // fold (add x, 0) -> x
1698   if (isNullConstant(N1))
1699     return N0;
1700 
1701   // fold ((c1-A)+c2) -> (c1+c2)-A
1702   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1703     if (N0.getOpcode() == ISD::SUB)
1704       if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1705         return DAG.getNode(ISD::SUB, DL, VT,
1706                            DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1707                            N0.getOperand(1));
1708       }
1709   }
1710 
1711   // reassociate add
1712   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1713     return RADD;
1714 
1715   // fold ((0-A) + B) -> B-A
1716   if (N0.getOpcode() == ISD::SUB &&
1717       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1718     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1719 
1720   // fold (A + (0-B)) -> A-B
1721   if (N1.getOpcode() == ISD::SUB &&
1722       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1723     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1724 
1725   // fold (A+(B-A)) -> B
1726   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1727     return N1.getOperand(0);
1728 
1729   // fold ((B-A)+A) -> B
1730   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1731     return N0.getOperand(0);
1732 
1733   // fold (A+(B-(A+C))) to (B-C)
1734   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1735       N0 == N1.getOperand(1).getOperand(0))
1736     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1737                        N1.getOperand(1).getOperand(1));
1738 
1739   // fold (A+(B-(C+A))) to (B-C)
1740   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1741       N0 == N1.getOperand(1).getOperand(1))
1742     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1743                        N1.getOperand(1).getOperand(0));
1744 
1745   // fold (A+((B-A)+or-C)) to (B+or-C)
1746   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1747       N1.getOperand(0).getOpcode() == ISD::SUB &&
1748       N0 == N1.getOperand(0).getOperand(1))
1749     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1750                        N1.getOperand(1));
1751 
1752   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1753   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1754     SDValue N00 = N0.getOperand(0);
1755     SDValue N01 = N0.getOperand(1);
1756     SDValue N10 = N1.getOperand(0);
1757     SDValue N11 = N1.getOperand(1);
1758 
1759     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1760       return DAG.getNode(ISD::SUB, DL, VT,
1761                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1762                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1763   }
1764 
1765   if (SimplifyDemandedBits(SDValue(N, 0)))
1766     return SDValue(N, 0);
1767 
1768   // fold (a+b) -> (a|b) iff a and b share no bits.
1769   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1770       VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1771     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1772 
1773   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1774   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1775       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1776     return DAG.getNode(ISD::SUB, DL, VT, N0,
1777                        DAG.getNode(ISD::SHL, DL, VT,
1778                                    N1.getOperand(0).getOperand(1),
1779                                    N1.getOperand(1)));
1780   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1781       isNullConstantOrNullSplatConstant(N0.getOperand(0).getOperand(0)))
1782     return DAG.getNode(ISD::SUB, DL, VT, N1,
1783                        DAG.getNode(ISD::SHL, DL, VT,
1784                                    N0.getOperand(0).getOperand(1),
1785                                    N0.getOperand(1)));
1786 
1787   if (N1.getOpcode() == ISD::AND) {
1788     SDValue AndOp0 = N1.getOperand(0);
1789     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1790     unsigned DestBits = VT.getScalarSizeInBits();
1791 
1792     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1793     // and similar xforms where the inner op is either ~0 or 0.
1794     if (NumSignBits == DestBits &&
1795         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1796       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1797   }
1798 
1799   // add (sext i1), X -> sub X, (zext i1)
1800   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1801       N0.getOperand(0).getValueType() == MVT::i1 &&
1802       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1803     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1804     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1805   }
1806 
1807   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1808   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1809     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1810     if (TN->getVT() == MVT::i1) {
1811       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1812                                  DAG.getConstant(1, DL, VT));
1813       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1814     }
1815   }
1816 
1817   return SDValue();
1818 }
1819 
1820 SDValue DAGCombiner::visitADDC(SDNode *N) {
1821   SDValue N0 = N->getOperand(0);
1822   SDValue N1 = N->getOperand(1);
1823   EVT VT = N0.getValueType();
1824 
1825   // If the flag result is dead, turn this into an ADD.
1826   if (!N->hasAnyUseOfValue(1))
1827     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1828                      DAG.getNode(ISD::CARRY_FALSE,
1829                                  SDLoc(N), MVT::Glue));
1830 
1831   // canonicalize constant to RHS.
1832   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1833   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1834   if (N0C && !N1C)
1835     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1836 
1837   // fold (addc x, 0) -> x + no carry out
1838   if (isNullConstant(N1))
1839     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1840                                         SDLoc(N), MVT::Glue));
1841 
1842   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1843   APInt LHSZero, LHSOne;
1844   APInt RHSZero, RHSOne;
1845   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1846 
1847   if (LHSZero.getBoolValue()) {
1848     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1849 
1850     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1851     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1852     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1853       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1854                        DAG.getNode(ISD::CARRY_FALSE,
1855                                    SDLoc(N), MVT::Glue));
1856   }
1857 
1858   return SDValue();
1859 }
1860 
1861 SDValue DAGCombiner::visitADDE(SDNode *N) {
1862   SDValue N0 = N->getOperand(0);
1863   SDValue N1 = N->getOperand(1);
1864   SDValue CarryIn = N->getOperand(2);
1865 
1866   // canonicalize constant to RHS
1867   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1868   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1869   if (N0C && !N1C)
1870     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1871                        N1, N0, CarryIn);
1872 
1873   // fold (adde x, y, false) -> (addc x, y)
1874   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1875     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1876 
1877   return SDValue();
1878 }
1879 
1880 // Since it may not be valid to emit a fold to zero for vector initializers
1881 // check if we can before folding.
1882 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1883                              SelectionDAG &DAG, bool LegalOperations,
1884                              bool LegalTypes) {
1885   if (!VT.isVector())
1886     return DAG.getConstant(0, DL, VT);
1887   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1888     return DAG.getConstant(0, DL, VT);
1889   return SDValue();
1890 }
1891 
1892 SDValue DAGCombiner::visitSUB(SDNode *N) {
1893   SDValue N0 = N->getOperand(0);
1894   SDValue N1 = N->getOperand(1);
1895   EVT VT = N0.getValueType();
1896   SDLoc DL(N);
1897 
1898   // fold vector ops
1899   if (VT.isVector()) {
1900     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1901       return FoldedVOp;
1902 
1903     // fold (sub x, 0) -> x, vector edition
1904     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1905       return N0;
1906   }
1907 
1908   // fold (sub x, x) -> 0
1909   // FIXME: Refactor this and xor and other similar operations together.
1910   if (N0 == N1)
1911     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
1912   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1913       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1914     // fold (sub c1, c2) -> c1-c2
1915     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
1916                                       N1.getNode());
1917   }
1918 
1919   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1920 
1921   // fold (sub x, c) -> (add x, -c)
1922   if (N1C) {
1923     return DAG.getNode(ISD::ADD, DL, VT, N0,
1924                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1925   }
1926 
1927   if (isNullConstantOrNullSplatConstant(N0)) {
1928     unsigned BitWidth = VT.getScalarSizeInBits();
1929     // Right-shifting everything out but the sign bit followed by negation is
1930     // the same as flipping arithmetic/logical shift type without the negation:
1931     // -(X >>u 31) -> (X >>s 31)
1932     // -(X >>s 31) -> (X >>u 31)
1933     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
1934       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
1935       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
1936         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
1937         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
1938           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
1939       }
1940     }
1941 
1942     // 0 - X --> 0 if the sub is NUW.
1943     if (N->getFlags()->hasNoUnsignedWrap())
1944       return N0;
1945 
1946     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignBit(BitWidth))) {
1947       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
1948       // N1 must be 0 because negating the minimum signed value is undefined.
1949       if (N->getFlags()->hasNoSignedWrap())
1950         return N0;
1951 
1952       // 0 - X --> X if X is 0 or the minimum signed value.
1953       return N1;
1954     }
1955   }
1956 
1957   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1958   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
1959     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
1960 
1961   // fold A-(A-B) -> B
1962   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1963     return N1.getOperand(1);
1964 
1965   // fold (A+B)-A -> B
1966   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1967     return N0.getOperand(1);
1968 
1969   // fold (A+B)-B -> A
1970   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1971     return N0.getOperand(0);
1972 
1973   // fold C2-(A+C1) -> (C2-C1)-A
1974   if (N1.getOpcode() == ISD::ADD) {
1975     SDValue N11 = N1.getOperand(1);
1976     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
1977         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
1978       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
1979       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
1980     }
1981   }
1982 
1983   // fold ((A+(B+or-C))-B) -> A+or-C
1984   if (N0.getOpcode() == ISD::ADD &&
1985       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1986        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1987       N0.getOperand(1).getOperand(0) == N1)
1988     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
1989                        N0.getOperand(1).getOperand(1));
1990 
1991   // fold ((A+(C+B))-B) -> A+C
1992   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
1993       N0.getOperand(1).getOperand(1) == N1)
1994     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
1995                        N0.getOperand(1).getOperand(0));
1996 
1997   // fold ((A-(B-C))-C) -> A-B
1998   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
1999       N0.getOperand(1).getOperand(1) == N1)
2000     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2001                        N0.getOperand(1).getOperand(0));
2002 
2003   // If either operand of a sub is undef, the result is undef
2004   if (N0.isUndef())
2005     return N0;
2006   if (N1.isUndef())
2007     return N1;
2008 
2009   // If the relocation model supports it, consider symbol offsets.
2010   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2011     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2012       // fold (sub Sym, c) -> Sym-c
2013       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2014         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2015                                     GA->getOffset() -
2016                                         (uint64_t)N1C->getSExtValue());
2017       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2018       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2019         if (GA->getGlobal() == GB->getGlobal())
2020           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2021                                  DL, VT);
2022     }
2023 
2024   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2025   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2026     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2027     if (TN->getVT() == MVT::i1) {
2028       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2029                                  DAG.getConstant(1, DL, VT));
2030       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2031     }
2032   }
2033 
2034   return SDValue();
2035 }
2036 
2037 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2038   SDValue N0 = N->getOperand(0);
2039   SDValue N1 = N->getOperand(1);
2040   EVT VT = N0.getValueType();
2041   SDLoc DL(N);
2042 
2043   // If the flag result is dead, turn this into an SUB.
2044   if (!N->hasAnyUseOfValue(1))
2045     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2046                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2047 
2048   // fold (subc x, x) -> 0 + no borrow
2049   if (N0 == N1)
2050     return CombineTo(N, DAG.getConstant(0, DL, VT),
2051                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2052 
2053   // fold (subc x, 0) -> x + no borrow
2054   if (isNullConstant(N1))
2055     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2056 
2057   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2058   if (isAllOnesConstant(N0))
2059     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2060                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2061 
2062   return SDValue();
2063 }
2064 
2065 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2066   SDValue N0 = N->getOperand(0);
2067   SDValue N1 = N->getOperand(1);
2068   SDValue CarryIn = N->getOperand(2);
2069 
2070   // fold (sube x, y, false) -> (subc x, y)
2071   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2072     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2073 
2074   return SDValue();
2075 }
2076 
2077 SDValue DAGCombiner::visitMUL(SDNode *N) {
2078   SDValue N0 = N->getOperand(0);
2079   SDValue N1 = N->getOperand(1);
2080   EVT VT = N0.getValueType();
2081 
2082   // fold (mul x, undef) -> 0
2083   if (N0.isUndef() || N1.isUndef())
2084     return DAG.getConstant(0, SDLoc(N), VT);
2085 
2086   bool N0IsConst = false;
2087   bool N1IsConst = false;
2088   bool N1IsOpaqueConst = false;
2089   bool N0IsOpaqueConst = false;
2090   APInt ConstValue0, ConstValue1;
2091   // fold vector ops
2092   if (VT.isVector()) {
2093     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2094       return FoldedVOp;
2095 
2096     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2097     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2098   } else {
2099     N0IsConst = isa<ConstantSDNode>(N0);
2100     if (N0IsConst) {
2101       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2102       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2103     }
2104     N1IsConst = isa<ConstantSDNode>(N1);
2105     if (N1IsConst) {
2106       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2107       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2108     }
2109   }
2110 
2111   // fold (mul c1, c2) -> c1*c2
2112   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2113     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2114                                       N0.getNode(), N1.getNode());
2115 
2116   // canonicalize constant to RHS (vector doesn't have to splat)
2117   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2118      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2119     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2120   // fold (mul x, 0) -> 0
2121   if (N1IsConst && ConstValue1 == 0)
2122     return N1;
2123   // We require a splat of the entire scalar bit width for non-contiguous
2124   // bit patterns.
2125   bool IsFullSplat =
2126     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2127   // fold (mul x, 1) -> x
2128   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2129     return N0;
2130   // fold (mul x, -1) -> 0-x
2131   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2132     SDLoc DL(N);
2133     return DAG.getNode(ISD::SUB, DL, VT,
2134                        DAG.getConstant(0, DL, VT), N0);
2135   }
2136   // fold (mul x, (1 << c)) -> x << c
2137   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2138       IsFullSplat) {
2139     SDLoc DL(N);
2140     return DAG.getNode(ISD::SHL, DL, VT, N0,
2141                        DAG.getConstant(ConstValue1.logBase2(), DL,
2142                                        getShiftAmountTy(N0.getValueType())));
2143   }
2144   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2145   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2146       IsFullSplat) {
2147     unsigned Log2Val = (-ConstValue1).logBase2();
2148     SDLoc DL(N);
2149     // FIXME: If the input is something that is easily negated (e.g. a
2150     // single-use add), we should put the negate there.
2151     return DAG.getNode(ISD::SUB, DL, VT,
2152                        DAG.getConstant(0, DL, VT),
2153                        DAG.getNode(ISD::SHL, DL, VT, N0,
2154                             DAG.getConstant(Log2Val, DL,
2155                                       getShiftAmountTy(N0.getValueType()))));
2156   }
2157 
2158   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2159   if (N0.getOpcode() == ISD::SHL &&
2160       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2161       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2162     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2163     if (isConstantOrConstantVector(C3))
2164       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2165   }
2166 
2167   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2168   // use.
2169   {
2170     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2171 
2172     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2173     if (N0.getOpcode() == ISD::SHL &&
2174         isConstantOrConstantVector(N0.getOperand(1)) &&
2175         N0.getNode()->hasOneUse()) {
2176       Sh = N0; Y = N1;
2177     } else if (N1.getOpcode() == ISD::SHL &&
2178                isConstantOrConstantVector(N1.getOperand(1)) &&
2179                N1.getNode()->hasOneUse()) {
2180       Sh = N1; Y = N0;
2181     }
2182 
2183     if (Sh.getNode()) {
2184       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2185       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2186     }
2187   }
2188 
2189   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2190   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2191       N0.getOpcode() == ISD::ADD &&
2192       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2193       isMulAddWithConstProfitable(N, N0, N1))
2194       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2195                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2196                                      N0.getOperand(0), N1),
2197                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2198                                      N0.getOperand(1), N1));
2199 
2200   // reassociate mul
2201   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2202     return RMUL;
2203 
2204   return SDValue();
2205 }
2206 
2207 /// Return true if divmod libcall is available.
2208 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2209                                      const TargetLowering &TLI) {
2210   RTLIB::Libcall LC;
2211   EVT NodeType = Node->getValueType(0);
2212   if (!NodeType.isSimple())
2213     return false;
2214   switch (NodeType.getSimpleVT().SimpleTy) {
2215   default: return false; // No libcall for vector types.
2216   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2217   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2218   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2219   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2220   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2221   }
2222 
2223   return TLI.getLibcallName(LC) != nullptr;
2224 }
2225 
2226 /// Issue divrem if both quotient and remainder are needed.
2227 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2228   if (Node->use_empty())
2229     return SDValue(); // This is a dead node, leave it alone.
2230 
2231   unsigned Opcode = Node->getOpcode();
2232   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2233   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2234 
2235   // DivMod lib calls can still work on non-legal types if using lib-calls.
2236   EVT VT = Node->getValueType(0);
2237   if (VT.isVector() || !VT.isInteger())
2238     return SDValue();
2239 
2240   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2241     return SDValue();
2242 
2243   // If DIVREM is going to get expanded into a libcall,
2244   // but there is no libcall available, then don't combine.
2245   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2246       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2247     return SDValue();
2248 
2249   // If div is legal, it's better to do the normal expansion
2250   unsigned OtherOpcode = 0;
2251   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2252     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2253     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2254       return SDValue();
2255   } else {
2256     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2257     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2258       return SDValue();
2259   }
2260 
2261   SDValue Op0 = Node->getOperand(0);
2262   SDValue Op1 = Node->getOperand(1);
2263   SDValue combined;
2264   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2265          UE = Op0.getNode()->use_end(); UI != UE;) {
2266     SDNode *User = *UI++;
2267     if (User == Node || User->use_empty())
2268       continue;
2269     // Convert the other matching node(s), too;
2270     // otherwise, the DIVREM may get target-legalized into something
2271     // target-specific that we won't be able to recognize.
2272     unsigned UserOpc = User->getOpcode();
2273     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2274         User->getOperand(0) == Op0 &&
2275         User->getOperand(1) == Op1) {
2276       if (!combined) {
2277         if (UserOpc == OtherOpcode) {
2278           SDVTList VTs = DAG.getVTList(VT, VT);
2279           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2280         } else if (UserOpc == DivRemOpc) {
2281           combined = SDValue(User, 0);
2282         } else {
2283           assert(UserOpc == Opcode);
2284           continue;
2285         }
2286       }
2287       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2288         CombineTo(User, combined);
2289       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2290         CombineTo(User, combined.getValue(1));
2291     }
2292   }
2293   return combined;
2294 }
2295 
2296 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2297   SDValue N0 = N->getOperand(0);
2298   SDValue N1 = N->getOperand(1);
2299   EVT VT = N->getValueType(0);
2300 
2301   // fold vector ops
2302   if (VT.isVector())
2303     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2304       return FoldedVOp;
2305 
2306   SDLoc DL(N);
2307 
2308   // fold (sdiv c1, c2) -> c1/c2
2309   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2310   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2311   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2312     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2313   // fold (sdiv X, 1) -> X
2314   if (N1C && N1C->isOne())
2315     return N0;
2316   // fold (sdiv X, -1) -> 0-X
2317   if (N1C && N1C->isAllOnesValue())
2318     return DAG.getNode(ISD::SUB, DL, VT,
2319                        DAG.getConstant(0, DL, VT), N0);
2320 
2321   // If we know the sign bits of both operands are zero, strength reduce to a
2322   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2323   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2324     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2325 
2326   // fold (sdiv X, pow2) -> simple ops after legalize
2327   // FIXME: We check for the exact bit here because the generic lowering gives
2328   // better results in that case. The target-specific lowering should learn how
2329   // to handle exact sdivs efficiently.
2330   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2331       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2332       (N1C->getAPIntValue().isPowerOf2() ||
2333        (-N1C->getAPIntValue()).isPowerOf2())) {
2334     // Target-specific implementation of sdiv x, pow2.
2335     if (SDValue Res = BuildSDIVPow2(N))
2336       return Res;
2337 
2338     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2339 
2340     // Splat the sign bit into the register
2341     SDValue SGN =
2342         DAG.getNode(ISD::SRA, DL, VT, N0,
2343                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2344                                     getShiftAmountTy(N0.getValueType())));
2345     AddToWorklist(SGN.getNode());
2346 
2347     // Add (N0 < 0) ? abs2 - 1 : 0;
2348     SDValue SRL =
2349         DAG.getNode(ISD::SRL, DL, VT, SGN,
2350                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2351                                     getShiftAmountTy(SGN.getValueType())));
2352     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2353     AddToWorklist(SRL.getNode());
2354     AddToWorklist(ADD.getNode());    // Divide by pow2
2355     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2356                   DAG.getConstant(lg2, DL,
2357                                   getShiftAmountTy(ADD.getValueType())));
2358 
2359     // If we're dividing by a positive value, we're done.  Otherwise, we must
2360     // negate the result.
2361     if (N1C->getAPIntValue().isNonNegative())
2362       return SRA;
2363 
2364     AddToWorklist(SRA.getNode());
2365     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2366   }
2367 
2368   // If integer divide is expensive and we satisfy the requirements, emit an
2369   // alternate sequence.  Targets may check function attributes for size/speed
2370   // trade-offs.
2371   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2372   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2373     if (SDValue Op = BuildSDIV(N))
2374       return Op;
2375 
2376   // sdiv, srem -> sdivrem
2377   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2378   // Otherwise, we break the simplification logic in visitREM().
2379   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2380     if (SDValue DivRem = useDivRem(N))
2381         return DivRem;
2382 
2383   // undef / X -> 0
2384   if (N0.isUndef())
2385     return DAG.getConstant(0, DL, VT);
2386   // X / undef -> undef
2387   if (N1.isUndef())
2388     return N1;
2389 
2390   return SDValue();
2391 }
2392 
2393 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2394   SDValue N0 = N->getOperand(0);
2395   SDValue N1 = N->getOperand(1);
2396   EVT VT = N->getValueType(0);
2397 
2398   // fold vector ops
2399   if (VT.isVector())
2400     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2401       return FoldedVOp;
2402 
2403   SDLoc DL(N);
2404 
2405   // fold (udiv c1, c2) -> c1/c2
2406   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2407   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2408   if (N0C && N1C)
2409     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2410                                                     N0C, N1C))
2411       return Folded;
2412 
2413   // fold (udiv x, (1 << c)) -> x >>u c
2414   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2415     return DAG.getNode(ISD::SRL, DL, VT, N0,
2416                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2417                                        getShiftAmountTy(N0.getValueType())));
2418 
2419   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2420   if (N1.getOpcode() == ISD::SHL) {
2421     if (ConstantSDNode *SHC = isConstOrConstSplat(N1.getOperand(0))) {
2422       if (!SHC->isOpaque() && SHC->getAPIntValue().isPowerOf2()) {
2423         EVT ADDVT = N1.getOperand(1).getValueType();
2424         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2425                                   N1.getOperand(1),
2426                                   DAG.getConstant(SHC->getAPIntValue()
2427                                                                   .logBase2(),
2428                                                   DL, ADDVT));
2429         AddToWorklist(Add.getNode());
2430         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2431       }
2432     }
2433   }
2434 
2435   // fold (udiv x, c) -> alternate
2436   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2437   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2438     if (SDValue Op = BuildUDIV(N))
2439       return Op;
2440 
2441   // sdiv, srem -> sdivrem
2442   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2443   // Otherwise, we break the simplification logic in visitREM().
2444   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2445     if (SDValue DivRem = useDivRem(N))
2446         return DivRem;
2447 
2448   // undef / X -> 0
2449   if (N0.isUndef())
2450     return DAG.getConstant(0, DL, VT);
2451   // X / undef -> undef
2452   if (N1.isUndef())
2453     return N1;
2454 
2455   return SDValue();
2456 }
2457 
2458 // handles ISD::SREM and ISD::UREM
2459 SDValue DAGCombiner::visitREM(SDNode *N) {
2460   unsigned Opcode = N->getOpcode();
2461   SDValue N0 = N->getOperand(0);
2462   SDValue N1 = N->getOperand(1);
2463   EVT VT = N->getValueType(0);
2464   bool isSigned = (Opcode == ISD::SREM);
2465   SDLoc DL(N);
2466 
2467   // fold (rem c1, c2) -> c1%c2
2468   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2469   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2470   if (N0C && N1C)
2471     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2472       return Folded;
2473 
2474   if (isSigned) {
2475     // If we know the sign bits of both operands are zero, strength reduce to a
2476     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2477     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2478       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2479   } else {
2480     // fold (urem x, pow2) -> (and x, pow2-1)
2481     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2482         N1C->getAPIntValue().isPowerOf2()) {
2483       return DAG.getNode(ISD::AND, DL, VT, N0,
2484                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2485     }
2486     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2487     if (N1.getOpcode() == ISD::SHL) {
2488       ConstantSDNode *SHC = isConstOrConstSplat(N1.getOperand(0));
2489       if (SHC && !SHC->isOpaque() && SHC->getAPIntValue().isPowerOf2()) {
2490         APInt NegOne = APInt::getAllOnesValue(VT.getScalarSizeInBits());
2491         SDValue Add =
2492             DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2493         AddToWorklist(Add.getNode());
2494         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2495       }
2496     }
2497   }
2498 
2499   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2500 
2501   // If X/C can be simplified by the division-by-constant logic, lower
2502   // X%C to the equivalent of X-X/C*C.
2503   // To avoid mangling nodes, this simplification requires that the combine()
2504   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2505   // against this by skipping the simplification if isIntDivCheap().  When
2506   // div is not cheap, combine will not return a DIVREM.  Regardless,
2507   // checking cheapness here makes sense since the simplification results in
2508   // fatter code.
2509   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2510     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2511     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2512     AddToWorklist(Div.getNode());
2513     SDValue OptimizedDiv = combine(Div.getNode());
2514     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2515       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2516              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2517       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2518       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2519       AddToWorklist(Mul.getNode());
2520       return Sub;
2521     }
2522   }
2523 
2524   // sdiv, srem -> sdivrem
2525   if (SDValue DivRem = useDivRem(N))
2526     return DivRem.getValue(1);
2527 
2528   // undef % X -> 0
2529   if (N0.isUndef())
2530     return DAG.getConstant(0, DL, VT);
2531   // X % undef -> undef
2532   if (N1.isUndef())
2533     return N1;
2534 
2535   return SDValue();
2536 }
2537 
2538 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2539   SDValue N0 = N->getOperand(0);
2540   SDValue N1 = N->getOperand(1);
2541   EVT VT = N->getValueType(0);
2542   SDLoc DL(N);
2543 
2544   // fold (mulhs x, 0) -> 0
2545   if (isNullConstant(N1))
2546     return N1;
2547   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2548   if (isOneConstant(N1)) {
2549     SDLoc DL(N);
2550     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2551                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2552                                        getShiftAmountTy(N0.getValueType())));
2553   }
2554   // fold (mulhs x, undef) -> 0
2555   if (N0.isUndef() || N1.isUndef())
2556     return DAG.getConstant(0, SDLoc(N), VT);
2557 
2558   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2559   // plus a shift.
2560   if (VT.isSimple() && !VT.isVector()) {
2561     MVT Simple = VT.getSimpleVT();
2562     unsigned SimpleSize = Simple.getSizeInBits();
2563     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2564     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2565       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2566       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2567       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2568       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2569             DAG.getConstant(SimpleSize, DL,
2570                             getShiftAmountTy(N1.getValueType())));
2571       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2572     }
2573   }
2574 
2575   return SDValue();
2576 }
2577 
2578 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2579   SDValue N0 = N->getOperand(0);
2580   SDValue N1 = N->getOperand(1);
2581   EVT VT = N->getValueType(0);
2582   SDLoc DL(N);
2583 
2584   // fold (mulhu x, 0) -> 0
2585   if (isNullConstant(N1))
2586     return N1;
2587   // fold (mulhu x, 1) -> 0
2588   if (isOneConstant(N1))
2589     return DAG.getConstant(0, DL, N0.getValueType());
2590   // fold (mulhu x, undef) -> 0
2591   if (N0.isUndef() || N1.isUndef())
2592     return DAG.getConstant(0, DL, VT);
2593 
2594   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2595   // plus a shift.
2596   if (VT.isSimple() && !VT.isVector()) {
2597     MVT Simple = VT.getSimpleVT();
2598     unsigned SimpleSize = Simple.getSizeInBits();
2599     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2600     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2601       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2602       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2603       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2604       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2605             DAG.getConstant(SimpleSize, DL,
2606                             getShiftAmountTy(N1.getValueType())));
2607       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2608     }
2609   }
2610 
2611   return SDValue();
2612 }
2613 
2614 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2615 /// give the opcodes for the two computations that are being performed. Return
2616 /// true if a simplification was made.
2617 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2618                                                 unsigned HiOp) {
2619   // If the high half is not needed, just compute the low half.
2620   bool HiExists = N->hasAnyUseOfValue(1);
2621   if (!HiExists &&
2622       (!LegalOperations ||
2623        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2624     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2625     return CombineTo(N, Res, Res);
2626   }
2627 
2628   // If the low half is not needed, just compute the high half.
2629   bool LoExists = N->hasAnyUseOfValue(0);
2630   if (!LoExists &&
2631       (!LegalOperations ||
2632        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2633     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2634     return CombineTo(N, Res, Res);
2635   }
2636 
2637   // If both halves are used, return as it is.
2638   if (LoExists && HiExists)
2639     return SDValue();
2640 
2641   // If the two computed results can be simplified separately, separate them.
2642   if (LoExists) {
2643     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2644     AddToWorklist(Lo.getNode());
2645     SDValue LoOpt = combine(Lo.getNode());
2646     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2647         (!LegalOperations ||
2648          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2649       return CombineTo(N, LoOpt, LoOpt);
2650   }
2651 
2652   if (HiExists) {
2653     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2654     AddToWorklist(Hi.getNode());
2655     SDValue HiOpt = combine(Hi.getNode());
2656     if (HiOpt.getNode() && HiOpt != Hi &&
2657         (!LegalOperations ||
2658          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2659       return CombineTo(N, HiOpt, HiOpt);
2660   }
2661 
2662   return SDValue();
2663 }
2664 
2665 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2666   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2667     return Res;
2668 
2669   EVT VT = N->getValueType(0);
2670   SDLoc DL(N);
2671 
2672   // If the type is twice as wide is legal, transform the mulhu to a wider
2673   // multiply plus a shift.
2674   if (VT.isSimple() && !VT.isVector()) {
2675     MVT Simple = VT.getSimpleVT();
2676     unsigned SimpleSize = Simple.getSizeInBits();
2677     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2678     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2679       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2680       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2681       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2682       // Compute the high part as N1.
2683       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2684             DAG.getConstant(SimpleSize, DL,
2685                             getShiftAmountTy(Lo.getValueType())));
2686       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2687       // Compute the low part as N0.
2688       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2689       return CombineTo(N, Lo, Hi);
2690     }
2691   }
2692 
2693   return SDValue();
2694 }
2695 
2696 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2697   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2698     return Res;
2699 
2700   EVT VT = N->getValueType(0);
2701   SDLoc DL(N);
2702 
2703   // If the type is twice as wide is legal, transform the mulhu to a wider
2704   // multiply plus a shift.
2705   if (VT.isSimple() && !VT.isVector()) {
2706     MVT Simple = VT.getSimpleVT();
2707     unsigned SimpleSize = Simple.getSizeInBits();
2708     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2709     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2710       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2711       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2712       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2713       // Compute the high part as N1.
2714       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2715             DAG.getConstant(SimpleSize, DL,
2716                             getShiftAmountTy(Lo.getValueType())));
2717       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2718       // Compute the low part as N0.
2719       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2720       return CombineTo(N, Lo, Hi);
2721     }
2722   }
2723 
2724   return SDValue();
2725 }
2726 
2727 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2728   // (smulo x, 2) -> (saddo x, x)
2729   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2730     if (C2->getAPIntValue() == 2)
2731       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2732                          N->getOperand(0), N->getOperand(0));
2733 
2734   return SDValue();
2735 }
2736 
2737 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2738   // (umulo x, 2) -> (uaddo x, x)
2739   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2740     if (C2->getAPIntValue() == 2)
2741       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2742                          N->getOperand(0), N->getOperand(0));
2743 
2744   return SDValue();
2745 }
2746 
2747 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2748   SDValue N0 = N->getOperand(0);
2749   SDValue N1 = N->getOperand(1);
2750   EVT VT = N0.getValueType();
2751 
2752   // fold vector ops
2753   if (VT.isVector())
2754     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2755       return FoldedVOp;
2756 
2757   // fold (add c1, c2) -> c1+c2
2758   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2759   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2760   if (N0C && N1C)
2761     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2762 
2763   // canonicalize constant to RHS
2764   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2765      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2766     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2767 
2768   return SDValue();
2769 }
2770 
2771 /// If this is a binary operator with two operands of the same opcode, try to
2772 /// simplify it.
2773 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2774   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2775   EVT VT = N0.getValueType();
2776   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2777 
2778   // Bail early if none of these transforms apply.
2779   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2780 
2781   // For each of OP in AND/OR/XOR:
2782   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2783   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2784   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2785   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2786   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2787   //
2788   // do not sink logical op inside of a vector extend, since it may combine
2789   // into a vsetcc.
2790   EVT Op0VT = N0.getOperand(0).getValueType();
2791   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2792        N0.getOpcode() == ISD::SIGN_EXTEND ||
2793        N0.getOpcode() == ISD::BSWAP ||
2794        // Avoid infinite looping with PromoteIntBinOp.
2795        (N0.getOpcode() == ISD::ANY_EXTEND &&
2796         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2797        (N0.getOpcode() == ISD::TRUNCATE &&
2798         (!TLI.isZExtFree(VT, Op0VT) ||
2799          !TLI.isTruncateFree(Op0VT, VT)) &&
2800         TLI.isTypeLegal(Op0VT))) &&
2801       !VT.isVector() &&
2802       Op0VT == N1.getOperand(0).getValueType() &&
2803       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2804     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2805                                  N0.getOperand(0).getValueType(),
2806                                  N0.getOperand(0), N1.getOperand(0));
2807     AddToWorklist(ORNode.getNode());
2808     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2809   }
2810 
2811   // For each of OP in SHL/SRL/SRA/AND...
2812   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2813   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2814   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2815   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2816        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2817       N0.getOperand(1) == N1.getOperand(1)) {
2818     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2819                                  N0.getOperand(0).getValueType(),
2820                                  N0.getOperand(0), N1.getOperand(0));
2821     AddToWorklist(ORNode.getNode());
2822     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2823                        ORNode, N0.getOperand(1));
2824   }
2825 
2826   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2827   // Only perform this optimization up until type legalization, before
2828   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2829   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2830   // we don't want to undo this promotion.
2831   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2832   // on scalars.
2833   if ((N0.getOpcode() == ISD::BITCAST ||
2834        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2835        Level <= AfterLegalizeTypes) {
2836     SDValue In0 = N0.getOperand(0);
2837     SDValue In1 = N1.getOperand(0);
2838     EVT In0Ty = In0.getValueType();
2839     EVT In1Ty = In1.getValueType();
2840     SDLoc DL(N);
2841     // If both incoming values are integers, and the original types are the
2842     // same.
2843     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2844       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2845       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2846       AddToWorklist(Op.getNode());
2847       return BC;
2848     }
2849   }
2850 
2851   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2852   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2853   // If both shuffles use the same mask, and both shuffle within a single
2854   // vector, then it is worthwhile to move the swizzle after the operation.
2855   // The type-legalizer generates this pattern when loading illegal
2856   // vector types from memory. In many cases this allows additional shuffle
2857   // optimizations.
2858   // There are other cases where moving the shuffle after the xor/and/or
2859   // is profitable even if shuffles don't perform a swizzle.
2860   // If both shuffles use the same mask, and both shuffles have the same first
2861   // or second operand, then it might still be profitable to move the shuffle
2862   // after the xor/and/or operation.
2863   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2864     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2865     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2866 
2867     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2868            "Inputs to shuffles are not the same type");
2869 
2870     // Check that both shuffles use the same mask. The masks are known to be of
2871     // the same length because the result vector type is the same.
2872     // Check also that shuffles have only one use to avoid introducing extra
2873     // instructions.
2874     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2875         SVN0->getMask().equals(SVN1->getMask())) {
2876       SDValue ShOp = N0->getOperand(1);
2877 
2878       // Don't try to fold this node if it requires introducing a
2879       // build vector of all zeros that might be illegal at this stage.
2880       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2881         if (!LegalTypes)
2882           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2883         else
2884           ShOp = SDValue();
2885       }
2886 
2887       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2888       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2889       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2890       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2891         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2892                                       N0->getOperand(0), N1->getOperand(0));
2893         AddToWorklist(NewNode.getNode());
2894         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2895                                     SVN0->getMask());
2896       }
2897 
2898       // Don't try to fold this node if it requires introducing a
2899       // build vector of all zeros that might be illegal at this stage.
2900       ShOp = N0->getOperand(0);
2901       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2902         if (!LegalTypes)
2903           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2904         else
2905           ShOp = SDValue();
2906       }
2907 
2908       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2909       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2910       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2911       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2912         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2913                                       N0->getOperand(1), N1->getOperand(1));
2914         AddToWorklist(NewNode.getNode());
2915         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2916                                     SVN0->getMask());
2917       }
2918     }
2919   }
2920 
2921   return SDValue();
2922 }
2923 
2924 /// This contains all DAGCombine rules which reduce two values combined by
2925 /// an And operation to a single value. This makes them reusable in the context
2926 /// of visitSELECT(). Rules involving constants are not included as
2927 /// visitSELECT() already handles those cases.
2928 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2929                                   SDNode *LocReference) {
2930   EVT VT = N1.getValueType();
2931 
2932   // fold (and x, undef) -> 0
2933   if (N0.isUndef() || N1.isUndef())
2934     return DAG.getConstant(0, SDLoc(LocReference), VT);
2935   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2936   SDValue LL, LR, RL, RR, CC0, CC1;
2937   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2938     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2939     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2940 
2941     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2942         LL.getValueType().isInteger()) {
2943       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2944       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2945         EVT CCVT = getSetCCResultType(LR.getValueType());
2946         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2947           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2948                                        LR.getValueType(), LL, RL);
2949           AddToWorklist(ORNode.getNode());
2950           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2951         }
2952       }
2953       if (isAllOnesConstant(LR)) {
2954         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2955         if (Op1 == ISD::SETEQ) {
2956           EVT CCVT = getSetCCResultType(LR.getValueType());
2957           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2958             SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2959                                           LR.getValueType(), LL, RL);
2960             AddToWorklist(ANDNode.getNode());
2961             return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2962           }
2963         }
2964         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2965         if (Op1 == ISD::SETGT) {
2966           EVT CCVT = getSetCCResultType(LR.getValueType());
2967           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2968             SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2969                                          LR.getValueType(), LL, RL);
2970             AddToWorklist(ORNode.getNode());
2971             return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2972           }
2973         }
2974       }
2975     }
2976     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2977     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2978         Op0 == Op1 && LL.getValueType().isInteger() &&
2979       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2980                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2981       EVT CCVT = getSetCCResultType(LL.getValueType());
2982       if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2983         SDLoc DL(N0);
2984         SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2985                                       LL, DAG.getConstant(1, DL,
2986                                                           LL.getValueType()));
2987         AddToWorklist(ADDNode.getNode());
2988         return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2989                             DAG.getConstant(2, DL, LL.getValueType()),
2990                             ISD::SETUGE);
2991       }
2992     }
2993     // canonicalize equivalent to ll == rl
2994     if (LL == RR && LR == RL) {
2995       Op1 = ISD::getSetCCSwappedOperands(Op1);
2996       std::swap(RL, RR);
2997     }
2998     if (LL == RL && LR == RR) {
2999       bool isInteger = LL.getValueType().isInteger();
3000       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
3001       if (Result != ISD::SETCC_INVALID &&
3002           (!LegalOperations ||
3003            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3004             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3005         EVT CCVT = getSetCCResultType(LL.getValueType());
3006         if (N0.getValueType() == CCVT ||
3007             (!LegalOperations && N0.getValueType() == MVT::i1))
3008           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3009                               LL, LR, Result);
3010       }
3011     }
3012   }
3013 
3014   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3015       VT.getSizeInBits() <= 64) {
3016     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3017       APInt ADDC = ADDI->getAPIntValue();
3018       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3019         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3020         // immediate for an add, but it is legal if its top c2 bits are set,
3021         // transform the ADD so the immediate doesn't need to be materialized
3022         // in a register.
3023         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3024           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3025                                              SRLI->getZExtValue());
3026           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3027             ADDC |= Mask;
3028             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3029               SDLoc DL(N0);
3030               SDValue NewAdd =
3031                 DAG.getNode(ISD::ADD, DL, VT,
3032                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3033               CombineTo(N0.getNode(), NewAdd);
3034               // Return N so it doesn't get rechecked!
3035               return SDValue(LocReference, 0);
3036             }
3037           }
3038         }
3039       }
3040     }
3041   }
3042 
3043   // Reduce bit extract of low half of an integer to the narrower type.
3044   // (and (srl i64:x, K), KMask) ->
3045   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3046   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3047     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3048       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3049         unsigned Size = VT.getSizeInBits();
3050         const APInt &AndMask = CAnd->getAPIntValue();
3051         unsigned ShiftBits = CShift->getZExtValue();
3052 
3053         // Bail out, this node will probably disappear anyway.
3054         if (ShiftBits == 0)
3055           return SDValue();
3056 
3057         unsigned MaskBits = AndMask.countTrailingOnes();
3058         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3059 
3060         if (APIntOps::isMask(AndMask) &&
3061             // Required bits must not span the two halves of the integer and
3062             // must fit in the half size type.
3063             (ShiftBits + MaskBits <= Size / 2) &&
3064             TLI.isNarrowingProfitable(VT, HalfVT) &&
3065             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3066             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3067             TLI.isTruncateFree(VT, HalfVT) &&
3068             TLI.isZExtFree(HalfVT, VT)) {
3069           // The isNarrowingProfitable is to avoid regressions on PPC and
3070           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3071           // on downstream users of this. Those patterns could probably be
3072           // extended to handle extensions mixed in.
3073 
3074           SDValue SL(N0);
3075           assert(MaskBits <= Size);
3076 
3077           // Extracting the highest bit of the low half.
3078           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3079           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3080                                       N0.getOperand(0));
3081 
3082           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3083           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3084           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3085           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3086           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3087         }
3088       }
3089     }
3090   }
3091 
3092   return SDValue();
3093 }
3094 
3095 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3096                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3097                                    bool &NarrowLoad) {
3098   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3099 
3100   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3101     return false;
3102 
3103   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3104   LoadedVT = LoadN->getMemoryVT();
3105 
3106   if (ExtVT == LoadedVT &&
3107       (!LegalOperations ||
3108        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3109     // ZEXTLOAD will match without needing to change the size of the value being
3110     // loaded.
3111     NarrowLoad = false;
3112     return true;
3113   }
3114 
3115   // Do not change the width of a volatile load.
3116   if (LoadN->isVolatile())
3117     return false;
3118 
3119   // Do not generate loads of non-round integer types since these can
3120   // be expensive (and would be wrong if the type is not byte sized).
3121   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3122     return false;
3123 
3124   if (LegalOperations &&
3125       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3126     return false;
3127 
3128   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3129     return false;
3130 
3131   NarrowLoad = true;
3132   return true;
3133 }
3134 
3135 SDValue DAGCombiner::visitAND(SDNode *N) {
3136   SDValue N0 = N->getOperand(0);
3137   SDValue N1 = N->getOperand(1);
3138   EVT VT = N1.getValueType();
3139 
3140   // x & x --> x
3141   if (N0 == N1)
3142     return N0;
3143 
3144   // fold vector ops
3145   if (VT.isVector()) {
3146     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3147       return FoldedVOp;
3148 
3149     // fold (and x, 0) -> 0, vector edition
3150     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3151       // do not return N0, because undef node may exist in N0
3152       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3153                              SDLoc(N), N0.getValueType());
3154     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3155       // do not return N1, because undef node may exist in N1
3156       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3157                              SDLoc(N), N1.getValueType());
3158 
3159     // fold (and x, -1) -> x, vector edition
3160     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3161       return N1;
3162     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3163       return N0;
3164   }
3165 
3166   // fold (and c1, c2) -> c1&c2
3167   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3168   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3169   if (N0C && N1C && !N1C->isOpaque())
3170     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3171   // canonicalize constant to RHS
3172   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3173      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3174     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3175   // fold (and x, -1) -> x
3176   if (isAllOnesConstant(N1))
3177     return N0;
3178   // if (and x, c) is known to be zero, return 0
3179   unsigned BitWidth = VT.getScalarSizeInBits();
3180   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3181                                    APInt::getAllOnesValue(BitWidth)))
3182     return DAG.getConstant(0, SDLoc(N), VT);
3183   // reassociate and
3184   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3185     return RAND;
3186   // fold (and (or x, C), D) -> D if (C & D) == D
3187   if (N1C && N0.getOpcode() == ISD::OR)
3188     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3189       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3190         return N1;
3191   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3192   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3193     SDValue N0Op0 = N0.getOperand(0);
3194     APInt Mask = ~N1C->getAPIntValue();
3195     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3196     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3197       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3198                                  N0.getValueType(), N0Op0);
3199 
3200       // Replace uses of the AND with uses of the Zero extend node.
3201       CombineTo(N, Zext);
3202 
3203       // We actually want to replace all uses of the any_extend with the
3204       // zero_extend, to avoid duplicating things.  This will later cause this
3205       // AND to be folded.
3206       CombineTo(N0.getNode(), Zext);
3207       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3208     }
3209   }
3210   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3211   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3212   // already be zero by virtue of the width of the base type of the load.
3213   //
3214   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3215   // more cases.
3216   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3217        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3218        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3219        N0.getOperand(0).getResNo() == 0) ||
3220       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3221     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3222                                          N0 : N0.getOperand(0) );
3223 
3224     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3225     // This can be a pure constant or a vector splat, in which case we treat the
3226     // vector as a scalar and use the splat value.
3227     APInt Constant = APInt::getNullValue(1);
3228     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3229       Constant = C->getAPIntValue();
3230     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3231       APInt SplatValue, SplatUndef;
3232       unsigned SplatBitSize;
3233       bool HasAnyUndefs;
3234       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3235                                              SplatBitSize, HasAnyUndefs);
3236       if (IsSplat) {
3237         // Undef bits can contribute to a possible optimisation if set, so
3238         // set them.
3239         SplatValue |= SplatUndef;
3240 
3241         // The splat value may be something like "0x00FFFFFF", which means 0 for
3242         // the first vector value and FF for the rest, repeating. We need a mask
3243         // that will apply equally to all members of the vector, so AND all the
3244         // lanes of the constant together.
3245         EVT VT = Vector->getValueType(0);
3246         unsigned BitWidth = VT.getScalarSizeInBits();
3247 
3248         // If the splat value has been compressed to a bitlength lower
3249         // than the size of the vector lane, we need to re-expand it to
3250         // the lane size.
3251         if (BitWidth > SplatBitSize)
3252           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3253                SplatBitSize < BitWidth;
3254                SplatBitSize = SplatBitSize * 2)
3255             SplatValue |= SplatValue.shl(SplatBitSize);
3256 
3257         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3258         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3259         if (SplatBitSize % BitWidth == 0) {
3260           Constant = APInt::getAllOnesValue(BitWidth);
3261           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3262             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3263         }
3264       }
3265     }
3266 
3267     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3268     // actually legal and isn't going to get expanded, else this is a false
3269     // optimisation.
3270     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3271                                                     Load->getValueType(0),
3272                                                     Load->getMemoryVT());
3273 
3274     // Resize the constant to the same size as the original memory access before
3275     // extension. If it is still the AllOnesValue then this AND is completely
3276     // unneeded.
3277     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3278 
3279     bool B;
3280     switch (Load->getExtensionType()) {
3281     default: B = false; break;
3282     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3283     case ISD::ZEXTLOAD:
3284     case ISD::NON_EXTLOAD: B = true; break;
3285     }
3286 
3287     if (B && Constant.isAllOnesValue()) {
3288       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3289       // preserve semantics once we get rid of the AND.
3290       SDValue NewLoad(Load, 0);
3291       if (Load->getExtensionType() == ISD::EXTLOAD) {
3292         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3293                               Load->getValueType(0), SDLoc(Load),
3294                               Load->getChain(), Load->getBasePtr(),
3295                               Load->getOffset(), Load->getMemoryVT(),
3296                               Load->getMemOperand());
3297         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3298         if (Load->getNumValues() == 3) {
3299           // PRE/POST_INC loads have 3 values.
3300           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3301                            NewLoad.getValue(2) };
3302           CombineTo(Load, To, 3, true);
3303         } else {
3304           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3305         }
3306       }
3307 
3308       // Fold the AND away, taking care not to fold to the old load node if we
3309       // replaced it.
3310       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3311 
3312       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3313     }
3314   }
3315 
3316   // fold (and (load x), 255) -> (zextload x, i8)
3317   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3318   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3319   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3320                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3321                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3322     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3323     LoadSDNode *LN0 = HasAnyExt
3324       ? cast<LoadSDNode>(N0.getOperand(0))
3325       : cast<LoadSDNode>(N0);
3326     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3327         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3328       auto NarrowLoad = false;
3329       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3330       EVT ExtVT, LoadedVT;
3331       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3332                            NarrowLoad)) {
3333         if (!NarrowLoad) {
3334           SDValue NewLoad =
3335             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3336                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3337                            LN0->getMemOperand());
3338           AddToWorklist(N);
3339           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3340           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3341         } else {
3342           EVT PtrType = LN0->getOperand(1).getValueType();
3343 
3344           unsigned Alignment = LN0->getAlignment();
3345           SDValue NewPtr = LN0->getBasePtr();
3346 
3347           // For big endian targets, we need to add an offset to the pointer
3348           // to load the correct bytes.  For little endian systems, we merely
3349           // need to read fewer bytes from the same pointer.
3350           if (DAG.getDataLayout().isBigEndian()) {
3351             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3352             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3353             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3354             SDLoc DL(LN0);
3355             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3356                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3357             Alignment = MinAlign(Alignment, PtrOff);
3358           }
3359 
3360           AddToWorklist(NewPtr.getNode());
3361 
3362           SDValue Load = DAG.getExtLoad(
3363               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3364               LN0->getPointerInfo(), ExtVT, Alignment,
3365               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3366           AddToWorklist(N);
3367           CombineTo(LN0, Load, Load.getValue(1));
3368           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3369         }
3370       }
3371     }
3372   }
3373 
3374   if (SDValue Combined = visitANDLike(N0, N1, N))
3375     return Combined;
3376 
3377   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3378   if (N0.getOpcode() == N1.getOpcode())
3379     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3380       return Tmp;
3381 
3382   // Masking the negated extension of a boolean is just the zero-extended
3383   // boolean:
3384   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3385   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3386   //
3387   // Note: the SimplifyDemandedBits fold below can make an information-losing
3388   // transform, and then we have no way to find this better fold.
3389   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3390     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3391     SDValue SubRHS = N0.getOperand(1);
3392     if (SubLHS && SubLHS->isNullValue()) {
3393       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3394           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3395         return SubRHS;
3396       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3397           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3398         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3399     }
3400   }
3401 
3402   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3403   // fold (and (sra)) -> (and (srl)) when possible.
3404   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
3405     return SDValue(N, 0);
3406 
3407   // fold (zext_inreg (extload x)) -> (zextload x)
3408   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3409     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3410     EVT MemVT = LN0->getMemoryVT();
3411     // If we zero all the possible extended bits, then we can turn this into
3412     // a zextload if we are running before legalize or the operation is legal.
3413     unsigned BitWidth = N1.getScalarValueSizeInBits();
3414     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3415                            BitWidth - MemVT.getScalarSizeInBits())) &&
3416         ((!LegalOperations && !LN0->isVolatile()) ||
3417          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3418       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3419                                        LN0->getChain(), LN0->getBasePtr(),
3420                                        MemVT, LN0->getMemOperand());
3421       AddToWorklist(N);
3422       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3423       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3424     }
3425   }
3426   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3427   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3428       N0.hasOneUse()) {
3429     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3430     EVT MemVT = LN0->getMemoryVT();
3431     // If we zero all the possible extended bits, then we can turn this into
3432     // a zextload if we are running before legalize or the operation is legal.
3433     unsigned BitWidth = N1.getScalarValueSizeInBits();
3434     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3435                            BitWidth - MemVT.getScalarSizeInBits())) &&
3436         ((!LegalOperations && !LN0->isVolatile()) ||
3437          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3438       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3439                                        LN0->getChain(), LN0->getBasePtr(),
3440                                        MemVT, LN0->getMemOperand());
3441       AddToWorklist(N);
3442       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3443       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3444     }
3445   }
3446   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3447   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3448     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3449                                            N0.getOperand(1), false))
3450       return BSwap;
3451   }
3452 
3453   return SDValue();
3454 }
3455 
3456 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3457 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3458                                         bool DemandHighBits) {
3459   if (!LegalOperations)
3460     return SDValue();
3461 
3462   EVT VT = N->getValueType(0);
3463   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3464     return SDValue();
3465   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3466     return SDValue();
3467 
3468   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3469   bool LookPassAnd0 = false;
3470   bool LookPassAnd1 = false;
3471   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3472       std::swap(N0, N1);
3473   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3474       std::swap(N0, N1);
3475   if (N0.getOpcode() == ISD::AND) {
3476     if (!N0.getNode()->hasOneUse())
3477       return SDValue();
3478     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3479     if (!N01C || N01C->getZExtValue() != 0xFF00)
3480       return SDValue();
3481     N0 = N0.getOperand(0);
3482     LookPassAnd0 = true;
3483   }
3484 
3485   if (N1.getOpcode() == ISD::AND) {
3486     if (!N1.getNode()->hasOneUse())
3487       return SDValue();
3488     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3489     if (!N11C || N11C->getZExtValue() != 0xFF)
3490       return SDValue();
3491     N1 = N1.getOperand(0);
3492     LookPassAnd1 = true;
3493   }
3494 
3495   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3496     std::swap(N0, N1);
3497   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3498     return SDValue();
3499   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3500     return SDValue();
3501 
3502   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3503   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3504   if (!N01C || !N11C)
3505     return SDValue();
3506   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3507     return SDValue();
3508 
3509   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3510   SDValue N00 = N0->getOperand(0);
3511   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3512     if (!N00.getNode()->hasOneUse())
3513       return SDValue();
3514     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3515     if (!N001C || N001C->getZExtValue() != 0xFF)
3516       return SDValue();
3517     N00 = N00.getOperand(0);
3518     LookPassAnd0 = true;
3519   }
3520 
3521   SDValue N10 = N1->getOperand(0);
3522   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3523     if (!N10.getNode()->hasOneUse())
3524       return SDValue();
3525     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3526     if (!N101C || N101C->getZExtValue() != 0xFF00)
3527       return SDValue();
3528     N10 = N10.getOperand(0);
3529     LookPassAnd1 = true;
3530   }
3531 
3532   if (N00 != N10)
3533     return SDValue();
3534 
3535   // Make sure everything beyond the low halfword gets set to zero since the SRL
3536   // 16 will clear the top bits.
3537   unsigned OpSizeInBits = VT.getSizeInBits();
3538   if (DemandHighBits && OpSizeInBits > 16) {
3539     // If the left-shift isn't masked out then the only way this is a bswap is
3540     // if all bits beyond the low 8 are 0. In that case the entire pattern
3541     // reduces to a left shift anyway: leave it for other parts of the combiner.
3542     if (!LookPassAnd0)
3543       return SDValue();
3544 
3545     // However, if the right shift isn't masked out then it might be because
3546     // it's not needed. See if we can spot that too.
3547     if (!LookPassAnd1 &&
3548         !DAG.MaskedValueIsZero(
3549             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3550       return SDValue();
3551   }
3552 
3553   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3554   if (OpSizeInBits > 16) {
3555     SDLoc DL(N);
3556     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3557                       DAG.getConstant(OpSizeInBits - 16, DL,
3558                                       getShiftAmountTy(VT)));
3559   }
3560   return Res;
3561 }
3562 
3563 /// Return true if the specified node is an element that makes up a 32-bit
3564 /// packed halfword byteswap.
3565 /// ((x & 0x000000ff) << 8) |
3566 /// ((x & 0x0000ff00) >> 8) |
3567 /// ((x & 0x00ff0000) << 8) |
3568 /// ((x & 0xff000000) >> 8)
3569 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3570   if (!N.getNode()->hasOneUse())
3571     return false;
3572 
3573   unsigned Opc = N.getOpcode();
3574   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3575     return false;
3576 
3577   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3578   if (!N1C)
3579     return false;
3580 
3581   unsigned Num;
3582   switch (N1C->getZExtValue()) {
3583   default:
3584     return false;
3585   case 0xFF:       Num = 0; break;
3586   case 0xFF00:     Num = 1; break;
3587   case 0xFF0000:   Num = 2; break;
3588   case 0xFF000000: Num = 3; break;
3589   }
3590 
3591   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3592   SDValue N0 = N.getOperand(0);
3593   if (Opc == ISD::AND) {
3594     if (Num == 0 || Num == 2) {
3595       // (x >> 8) & 0xff
3596       // (x >> 8) & 0xff0000
3597       if (N0.getOpcode() != ISD::SRL)
3598         return false;
3599       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3600       if (!C || C->getZExtValue() != 8)
3601         return false;
3602     } else {
3603       // (x << 8) & 0xff00
3604       // (x << 8) & 0xff000000
3605       if (N0.getOpcode() != ISD::SHL)
3606         return false;
3607       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3608       if (!C || C->getZExtValue() != 8)
3609         return false;
3610     }
3611   } else if (Opc == ISD::SHL) {
3612     // (x & 0xff) << 8
3613     // (x & 0xff0000) << 8
3614     if (Num != 0 && Num != 2)
3615       return false;
3616     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3617     if (!C || C->getZExtValue() != 8)
3618       return false;
3619   } else { // Opc == ISD::SRL
3620     // (x & 0xff00) >> 8
3621     // (x & 0xff000000) >> 8
3622     if (Num != 1 && Num != 3)
3623       return false;
3624     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3625     if (!C || C->getZExtValue() != 8)
3626       return false;
3627   }
3628 
3629   if (Parts[Num])
3630     return false;
3631 
3632   Parts[Num] = N0.getOperand(0).getNode();
3633   return true;
3634 }
3635 
3636 /// Match a 32-bit packed halfword bswap. That is
3637 /// ((x & 0x000000ff) << 8) |
3638 /// ((x & 0x0000ff00) >> 8) |
3639 /// ((x & 0x00ff0000) << 8) |
3640 /// ((x & 0xff000000) >> 8)
3641 /// => (rotl (bswap x), 16)
3642 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3643   if (!LegalOperations)
3644     return SDValue();
3645 
3646   EVT VT = N->getValueType(0);
3647   if (VT != MVT::i32)
3648     return SDValue();
3649   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3650     return SDValue();
3651 
3652   // Look for either
3653   // (or (or (and), (and)), (or (and), (and)))
3654   // (or (or (or (and), (and)), (and)), (and))
3655   if (N0.getOpcode() != ISD::OR)
3656     return SDValue();
3657   SDValue N00 = N0.getOperand(0);
3658   SDValue N01 = N0.getOperand(1);
3659   SDNode *Parts[4] = {};
3660 
3661   if (N1.getOpcode() == ISD::OR &&
3662       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3663     // (or (or (and), (and)), (or (and), (and)))
3664     SDValue N000 = N00.getOperand(0);
3665     if (!isBSwapHWordElement(N000, Parts))
3666       return SDValue();
3667 
3668     SDValue N001 = N00.getOperand(1);
3669     if (!isBSwapHWordElement(N001, Parts))
3670       return SDValue();
3671     SDValue N010 = N01.getOperand(0);
3672     if (!isBSwapHWordElement(N010, Parts))
3673       return SDValue();
3674     SDValue N011 = N01.getOperand(1);
3675     if (!isBSwapHWordElement(N011, Parts))
3676       return SDValue();
3677   } else {
3678     // (or (or (or (and), (and)), (and)), (and))
3679     if (!isBSwapHWordElement(N1, Parts))
3680       return SDValue();
3681     if (!isBSwapHWordElement(N01, Parts))
3682       return SDValue();
3683     if (N00.getOpcode() != ISD::OR)
3684       return SDValue();
3685     SDValue N000 = N00.getOperand(0);
3686     if (!isBSwapHWordElement(N000, Parts))
3687       return SDValue();
3688     SDValue N001 = N00.getOperand(1);
3689     if (!isBSwapHWordElement(N001, Parts))
3690       return SDValue();
3691   }
3692 
3693   // Make sure the parts are all coming from the same node.
3694   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3695     return SDValue();
3696 
3697   SDLoc DL(N);
3698   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3699                               SDValue(Parts[0], 0));
3700 
3701   // Result of the bswap should be rotated by 16. If it's not legal, then
3702   // do  (x << 16) | (x >> 16).
3703   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3704   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3705     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3706   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3707     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3708   return DAG.getNode(ISD::OR, DL, VT,
3709                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3710                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3711 }
3712 
3713 /// This contains all DAGCombine rules which reduce two values combined by
3714 /// an Or operation to a single value \see visitANDLike().
3715 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3716   EVT VT = N1.getValueType();
3717   // fold (or x, undef) -> -1
3718   if (!LegalOperations &&
3719       (N0.isUndef() || N1.isUndef())) {
3720     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3721     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3722                            SDLoc(LocReference), VT);
3723   }
3724   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3725   SDValue LL, LR, RL, RR, CC0, CC1;
3726   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3727     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3728     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3729 
3730     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3731       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3732       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3733       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3734         EVT CCVT = getSetCCResultType(LR.getValueType());
3735         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3736           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3737                                        LR.getValueType(), LL, RL);
3738           AddToWorklist(ORNode.getNode());
3739           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3740         }
3741       }
3742       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3743       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3744       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3745         EVT CCVT = getSetCCResultType(LR.getValueType());
3746         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3747           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3748                                         LR.getValueType(), LL, RL);
3749           AddToWorklist(ANDNode.getNode());
3750           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3751         }
3752       }
3753     }
3754     // canonicalize equivalent to ll == rl
3755     if (LL == RR && LR == RL) {
3756       Op1 = ISD::getSetCCSwappedOperands(Op1);
3757       std::swap(RL, RR);
3758     }
3759     if (LL == RL && LR == RR) {
3760       bool isInteger = LL.getValueType().isInteger();
3761       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3762       if (Result != ISD::SETCC_INVALID &&
3763           (!LegalOperations ||
3764            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3765             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3766         EVT CCVT = getSetCCResultType(LL.getValueType());
3767         if (N0.getValueType() == CCVT ||
3768             (!LegalOperations && N0.getValueType() == MVT::i1))
3769           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3770                               LL, LR, Result);
3771       }
3772     }
3773   }
3774 
3775   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3776   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3777       // Don't increase # computations.
3778       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3779     // We can only do this xform if we know that bits from X that are set in C2
3780     // but not in C1 are already zero.  Likewise for Y.
3781     if (const ConstantSDNode *N0O1C =
3782         getAsNonOpaqueConstant(N0.getOperand(1))) {
3783       if (const ConstantSDNode *N1O1C =
3784           getAsNonOpaqueConstant(N1.getOperand(1))) {
3785         // We can only do this xform if we know that bits from X that are set in
3786         // C2 but not in C1 are already zero.  Likewise for Y.
3787         const APInt &LHSMask = N0O1C->getAPIntValue();
3788         const APInt &RHSMask = N1O1C->getAPIntValue();
3789 
3790         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3791             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3792           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3793                                   N0.getOperand(0), N1.getOperand(0));
3794           SDLoc DL(LocReference);
3795           return DAG.getNode(ISD::AND, DL, VT, X,
3796                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3797         }
3798       }
3799     }
3800   }
3801 
3802   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3803   if (N0.getOpcode() == ISD::AND &&
3804       N1.getOpcode() == ISD::AND &&
3805       N0.getOperand(0) == N1.getOperand(0) &&
3806       // Don't increase # computations.
3807       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3808     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3809                             N0.getOperand(1), N1.getOperand(1));
3810     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3811   }
3812 
3813   return SDValue();
3814 }
3815 
3816 SDValue DAGCombiner::visitOR(SDNode *N) {
3817   SDValue N0 = N->getOperand(0);
3818   SDValue N1 = N->getOperand(1);
3819   EVT VT = N1.getValueType();
3820 
3821   // x | x --> x
3822   if (N0 == N1)
3823     return N0;
3824 
3825   // fold vector ops
3826   if (VT.isVector()) {
3827     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3828       return FoldedVOp;
3829 
3830     // fold (or x, 0) -> x, vector edition
3831     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3832       return N1;
3833     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3834       return N0;
3835 
3836     // fold (or x, -1) -> -1, vector edition
3837     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3838       // do not return N0, because undef node may exist in N0
3839       return DAG.getConstant(
3840           APInt::getAllOnesValue(N0.getScalarValueSizeInBits()), SDLoc(N),
3841           N0.getValueType());
3842     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3843       // do not return N1, because undef node may exist in N1
3844       return DAG.getConstant(
3845           APInt::getAllOnesValue(N1.getScalarValueSizeInBits()), SDLoc(N),
3846           N1.getValueType());
3847 
3848     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3849     // Do this only if the resulting shuffle is legal.
3850     if (isa<ShuffleVectorSDNode>(N0) &&
3851         isa<ShuffleVectorSDNode>(N1) &&
3852         // Avoid folding a node with illegal type.
3853         TLI.isTypeLegal(VT)) {
3854       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3855       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3856       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3857       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3858       // Ensure both shuffles have a zero input.
3859       if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3860         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3861         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3862         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3863         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3864         bool CanFold = true;
3865         int NumElts = VT.getVectorNumElements();
3866         SmallVector<int, 4> Mask(NumElts);
3867 
3868         for (int i = 0; i != NumElts; ++i) {
3869           int M0 = SV0->getMaskElt(i);
3870           int M1 = SV1->getMaskElt(i);
3871 
3872           // Determine if either index is pointing to a zero vector.
3873           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
3874           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
3875 
3876           // If one element is zero and the otherside is undef, keep undef.
3877           // This also handles the case that both are undef.
3878           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
3879             Mask[i] = -1;
3880             continue;
3881           }
3882 
3883           // Make sure only one of the elements is zero.
3884           if (M0Zero == M1Zero) {
3885             CanFold = false;
3886             break;
3887           }
3888 
3889           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
3890 
3891           // We have a zero and non-zero element. If the non-zero came from
3892           // SV0 make the index a LHS index. If it came from SV1, make it
3893           // a RHS index. We need to mod by NumElts because we don't care
3894           // which operand it came from in the original shuffles.
3895           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3896         }
3897 
3898         if (CanFold) {
3899           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3900           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3901 
3902           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3903           if (!LegalMask) {
3904             std::swap(NewLHS, NewRHS);
3905             ShuffleVectorSDNode::commuteMask(Mask);
3906             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3907           }
3908 
3909           if (LegalMask)
3910             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
3911         }
3912       }
3913     }
3914   }
3915 
3916   // fold (or c1, c2) -> c1|c2
3917   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3918   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3919   if (N0C && N1C && !N1C->isOpaque())
3920     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3921   // canonicalize constant to RHS
3922   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3923      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3924     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3925   // fold (or x, 0) -> x
3926   if (isNullConstant(N1))
3927     return N0;
3928   // fold (or x, -1) -> -1
3929   if (isAllOnesConstant(N1))
3930     return N1;
3931   // fold (or x, c) -> c iff (x & ~c) == 0
3932   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3933     return N1;
3934 
3935   if (SDValue Combined = visitORLike(N0, N1, N))
3936     return Combined;
3937 
3938   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3939   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3940     return BSwap;
3941   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3942     return BSwap;
3943 
3944   // reassociate or
3945   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3946     return ROR;
3947   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3948   // iff (c1 & c2) == 0.
3949   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3950              isa<ConstantSDNode>(N0.getOperand(1))) {
3951     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3952     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3953       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3954                                                    N1C, C1))
3955         return DAG.getNode(
3956             ISD::AND, SDLoc(N), VT,
3957             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3958       return SDValue();
3959     }
3960   }
3961   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3962   if (N0.getOpcode() == N1.getOpcode())
3963     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3964       return Tmp;
3965 
3966   // See if this is some rotate idiom.
3967   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3968     return SDValue(Rot, 0);
3969 
3970   // Simplify the operands using demanded-bits information.
3971   if (!VT.isVector() &&
3972       SimplifyDemandedBits(SDValue(N, 0)))
3973     return SDValue(N, 0);
3974 
3975   return SDValue();
3976 }
3977 
3978 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3979 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3980   if (Op.getOpcode() == ISD::AND) {
3981     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3982       Mask = Op.getOperand(1);
3983       Op = Op.getOperand(0);
3984     } else {
3985       return false;
3986     }
3987   }
3988 
3989   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3990     Shift = Op;
3991     return true;
3992   }
3993 
3994   return false;
3995 }
3996 
3997 // Return true if we can prove that, whenever Neg and Pos are both in the
3998 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3999 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4000 //
4001 //     (or (shift1 X, Neg), (shift2 X, Pos))
4002 //
4003 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4004 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4005 // to consider shift amounts with defined behavior.
4006 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4007   // If EltSize is a power of 2 then:
4008   //
4009   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4010   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4011   //
4012   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4013   // for the stronger condition:
4014   //
4015   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4016   //
4017   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4018   // we can just replace Neg with Neg' for the rest of the function.
4019   //
4020   // In other cases we check for the even stronger condition:
4021   //
4022   //     Neg == EltSize - Pos                                    [B]
4023   //
4024   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4025   // behavior if Pos == 0 (and consequently Neg == EltSize).
4026   //
4027   // We could actually use [A] whenever EltSize is a power of 2, but the
4028   // only extra cases that it would match are those uninteresting ones
4029   // where Neg and Pos are never in range at the same time.  E.g. for
4030   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4031   // as well as (sub 32, Pos), but:
4032   //
4033   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4034   //
4035   // always invokes undefined behavior for 32-bit X.
4036   //
4037   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4038   unsigned MaskLoBits = 0;
4039   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4040     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4041       if (NegC->getAPIntValue() == EltSize - 1) {
4042         Neg = Neg.getOperand(0);
4043         MaskLoBits = Log2_64(EltSize);
4044       }
4045     }
4046   }
4047 
4048   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4049   if (Neg.getOpcode() != ISD::SUB)
4050     return false;
4051   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4052   if (!NegC)
4053     return false;
4054   SDValue NegOp1 = Neg.getOperand(1);
4055 
4056   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4057   // Pos'.  The truncation is redundant for the purpose of the equality.
4058   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4059     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4060       if (PosC->getAPIntValue() == EltSize - 1)
4061         Pos = Pos.getOperand(0);
4062 
4063   // The condition we need is now:
4064   //
4065   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4066   //
4067   // If NegOp1 == Pos then we need:
4068   //
4069   //              EltSize & Mask == NegC & Mask
4070   //
4071   // (because "x & Mask" is a truncation and distributes through subtraction).
4072   APInt Width;
4073   if (Pos == NegOp1)
4074     Width = NegC->getAPIntValue();
4075 
4076   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4077   // Then the condition we want to prove becomes:
4078   //
4079   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4080   //
4081   // which, again because "x & Mask" is a truncation, becomes:
4082   //
4083   //                NegC & Mask == (EltSize - PosC) & Mask
4084   //             EltSize & Mask == (NegC + PosC) & Mask
4085   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4086     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4087       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4088     else
4089       return false;
4090   } else
4091     return false;
4092 
4093   // Now we just need to check that EltSize & Mask == Width & Mask.
4094   if (MaskLoBits)
4095     // EltSize & Mask is 0 since Mask is EltSize - 1.
4096     return Width.getLoBits(MaskLoBits) == 0;
4097   return Width == EltSize;
4098 }
4099 
4100 // A subroutine of MatchRotate used once we have found an OR of two opposite
4101 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4102 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4103 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4104 // Neg with outer conversions stripped away.
4105 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4106                                        SDValue Neg, SDValue InnerPos,
4107                                        SDValue InnerNeg, unsigned PosOpcode,
4108                                        unsigned NegOpcode, const SDLoc &DL) {
4109   // fold (or (shl x, (*ext y)),
4110   //          (srl x, (*ext (sub 32, y)))) ->
4111   //   (rotl x, y) or (rotr x, (sub 32, y))
4112   //
4113   // fold (or (shl x, (*ext (sub 32, y))),
4114   //          (srl x, (*ext y))) ->
4115   //   (rotr x, y) or (rotl x, (sub 32, y))
4116   EVT VT = Shifted.getValueType();
4117   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4118     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4119     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4120                        HasPos ? Pos : Neg).getNode();
4121   }
4122 
4123   return nullptr;
4124 }
4125 
4126 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4127 // idioms for rotate, and if the target supports rotation instructions, generate
4128 // a rot[lr].
4129 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4130   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4131   EVT VT = LHS.getValueType();
4132   if (!TLI.isTypeLegal(VT)) return nullptr;
4133 
4134   // The target must have at least one rotate flavor.
4135   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4136   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4137   if (!HasROTL && !HasROTR) return nullptr;
4138 
4139   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4140   SDValue LHSShift;   // The shift.
4141   SDValue LHSMask;    // AND value if any.
4142   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4143     return nullptr; // Not part of a rotate.
4144 
4145   SDValue RHSShift;   // The shift.
4146   SDValue RHSMask;    // AND value if any.
4147   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4148     return nullptr; // Not part of a rotate.
4149 
4150   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4151     return nullptr;   // Not shifting the same value.
4152 
4153   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4154     return nullptr;   // Shifts must disagree.
4155 
4156   // Canonicalize shl to left side in a shl/srl pair.
4157   if (RHSShift.getOpcode() == ISD::SHL) {
4158     std::swap(LHS, RHS);
4159     std::swap(LHSShift, RHSShift);
4160     std::swap(LHSMask, RHSMask);
4161   }
4162 
4163   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4164   SDValue LHSShiftArg = LHSShift.getOperand(0);
4165   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4166   SDValue RHSShiftArg = RHSShift.getOperand(0);
4167   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4168 
4169   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4170   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4171   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4172     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4173     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4174     if ((LShVal + RShVal) != EltSizeInBits)
4175       return nullptr;
4176 
4177     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4178                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4179 
4180     // If there is an AND of either shifted operand, apply it to the result.
4181     if (LHSMask.getNode() || RHSMask.getNode()) {
4182       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4183       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4184 
4185       if (LHSMask.getNode()) {
4186         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4187         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4188                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4189                                        DAG.getConstant(RHSBits, DL, VT)));
4190       }
4191       if (RHSMask.getNode()) {
4192         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4193         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4194                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4195                                        DAG.getConstant(LHSBits, DL, VT)));
4196       }
4197 
4198       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4199     }
4200 
4201     return Rot.getNode();
4202   }
4203 
4204   // If there is a mask here, and we have a variable shift, we can't be sure
4205   // that we're masking out the right stuff.
4206   if (LHSMask.getNode() || RHSMask.getNode())
4207     return nullptr;
4208 
4209   // If the shift amount is sign/zext/any-extended just peel it off.
4210   SDValue LExtOp0 = LHSShiftAmt;
4211   SDValue RExtOp0 = RHSShiftAmt;
4212   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4213        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4214        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4215        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4216       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4217        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4218        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4219        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4220     LExtOp0 = LHSShiftAmt.getOperand(0);
4221     RExtOp0 = RHSShiftAmt.getOperand(0);
4222   }
4223 
4224   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4225                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4226   if (TryL)
4227     return TryL;
4228 
4229   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4230                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4231   if (TryR)
4232     return TryR;
4233 
4234   return nullptr;
4235 }
4236 
4237 SDValue DAGCombiner::visitXOR(SDNode *N) {
4238   SDValue N0 = N->getOperand(0);
4239   SDValue N1 = N->getOperand(1);
4240   EVT VT = N0.getValueType();
4241 
4242   // fold vector ops
4243   if (VT.isVector()) {
4244     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4245       return FoldedVOp;
4246 
4247     // fold (xor x, 0) -> x, vector edition
4248     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4249       return N1;
4250     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4251       return N0;
4252   }
4253 
4254   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4255   if (N0.isUndef() && N1.isUndef())
4256     return DAG.getConstant(0, SDLoc(N), VT);
4257   // fold (xor x, undef) -> undef
4258   if (N0.isUndef())
4259     return N0;
4260   if (N1.isUndef())
4261     return N1;
4262   // fold (xor c1, c2) -> c1^c2
4263   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4264   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4265   if (N0C && N1C)
4266     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4267   // canonicalize constant to RHS
4268   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4269      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4270     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4271   // fold (xor x, 0) -> x
4272   if (isNullConstant(N1))
4273     return N0;
4274   // reassociate xor
4275   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4276     return RXOR;
4277 
4278   // fold !(x cc y) -> (x !cc y)
4279   SDValue LHS, RHS, CC;
4280   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4281     bool isInt = LHS.getValueType().isInteger();
4282     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4283                                                isInt);
4284 
4285     if (!LegalOperations ||
4286         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4287       switch (N0.getOpcode()) {
4288       default:
4289         llvm_unreachable("Unhandled SetCC Equivalent!");
4290       case ISD::SETCC:
4291         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4292       case ISD::SELECT_CC:
4293         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4294                                N0.getOperand(3), NotCC);
4295       }
4296     }
4297   }
4298 
4299   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4300   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4301       N0.getNode()->hasOneUse() &&
4302       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4303     SDValue V = N0.getOperand(0);
4304     SDLoc DL(N0);
4305     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4306                     DAG.getConstant(1, DL, V.getValueType()));
4307     AddToWorklist(V.getNode());
4308     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4309   }
4310 
4311   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4312   if (isOneConstant(N1) && VT == MVT::i1 &&
4313       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4314     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4315     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4316       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4317       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4318       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4319       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4320       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4321     }
4322   }
4323   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4324   if (isAllOnesConstant(N1) &&
4325       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4326     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4327     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4328       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4329       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4330       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4331       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4332       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4333     }
4334   }
4335   // fold (xor (and x, y), y) -> (and (not x), y)
4336   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4337       N0->getOperand(1) == N1) {
4338     SDValue X = N0->getOperand(0);
4339     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4340     AddToWorklist(NotX.getNode());
4341     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4342   }
4343   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4344   if (N1C && N0.getOpcode() == ISD::XOR) {
4345     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4346       SDLoc DL(N);
4347       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4348                          DAG.getConstant(N1C->getAPIntValue() ^
4349                                          N00C->getAPIntValue(), DL, VT));
4350     }
4351     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4352       SDLoc DL(N);
4353       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4354                          DAG.getConstant(N1C->getAPIntValue() ^
4355                                          N01C->getAPIntValue(), DL, VT));
4356     }
4357   }
4358   // fold (xor x, x) -> 0
4359   if (N0 == N1)
4360     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4361 
4362   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4363   // Here is a concrete example of this equivalence:
4364   // i16   x ==  14
4365   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4366   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4367   //
4368   // =>
4369   //
4370   // i16     ~1      == 0b1111111111111110
4371   // i16 rol(~1, 14) == 0b1011111111111111
4372   //
4373   // Some additional tips to help conceptualize this transform:
4374   // - Try to see the operation as placing a single zero in a value of all ones.
4375   // - There exists no value for x which would allow the result to contain zero.
4376   // - Values of x larger than the bitwidth are undefined and do not require a
4377   //   consistent result.
4378   // - Pushing the zero left requires shifting one bits in from the right.
4379   // A rotate left of ~1 is a nice way of achieving the desired result.
4380   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4381       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4382     SDLoc DL(N);
4383     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4384                        N0.getOperand(1));
4385   }
4386 
4387   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4388   if (N0.getOpcode() == N1.getOpcode())
4389     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4390       return Tmp;
4391 
4392   // Simplify the expression using non-local knowledge.
4393   if (!VT.isVector() &&
4394       SimplifyDemandedBits(SDValue(N, 0)))
4395     return SDValue(N, 0);
4396 
4397   return SDValue();
4398 }
4399 
4400 /// Handle transforms common to the three shifts, when the shift amount is a
4401 /// constant.
4402 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4403   SDNode *LHS = N->getOperand(0).getNode();
4404   if (!LHS->hasOneUse()) return SDValue();
4405 
4406   // We want to pull some binops through shifts, so that we have (and (shift))
4407   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4408   // thing happens with address calculations, so it's important to canonicalize
4409   // it.
4410   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4411 
4412   switch (LHS->getOpcode()) {
4413   default: return SDValue();
4414   case ISD::OR:
4415   case ISD::XOR:
4416     HighBitSet = false; // We can only transform sra if the high bit is clear.
4417     break;
4418   case ISD::AND:
4419     HighBitSet = true;  // We can only transform sra if the high bit is set.
4420     break;
4421   case ISD::ADD:
4422     if (N->getOpcode() != ISD::SHL)
4423       return SDValue(); // only shl(add) not sr[al](add).
4424     HighBitSet = false; // We can only transform sra if the high bit is clear.
4425     break;
4426   }
4427 
4428   // We require the RHS of the binop to be a constant and not opaque as well.
4429   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4430   if (!BinOpCst) return SDValue();
4431 
4432   // FIXME: disable this unless the input to the binop is a shift by a constant.
4433   // If it is not a shift, it pessimizes some common cases like:
4434   //
4435   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4436   //    int bar(int *X, int i) { return X[i & 255]; }
4437   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4438   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4439        BinOpLHSVal->getOpcode() != ISD::SRA &&
4440        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4441       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4442     return SDValue();
4443 
4444   EVT VT = N->getValueType(0);
4445 
4446   // If this is a signed shift right, and the high bit is modified by the
4447   // logical operation, do not perform the transformation. The highBitSet
4448   // boolean indicates the value of the high bit of the constant which would
4449   // cause it to be modified for this operation.
4450   if (N->getOpcode() == ISD::SRA) {
4451     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4452     if (BinOpRHSSignSet != HighBitSet)
4453       return SDValue();
4454   }
4455 
4456   if (!TLI.isDesirableToCommuteWithShift(LHS))
4457     return SDValue();
4458 
4459   // Fold the constants, shifting the binop RHS by the shift amount.
4460   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4461                                N->getValueType(0),
4462                                LHS->getOperand(1), N->getOperand(1));
4463   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4464 
4465   // Create the new shift.
4466   SDValue NewShift = DAG.getNode(N->getOpcode(),
4467                                  SDLoc(LHS->getOperand(0)),
4468                                  VT, LHS->getOperand(0), N->getOperand(1));
4469 
4470   // Create the new binop.
4471   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4472 }
4473 
4474 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4475   assert(N->getOpcode() == ISD::TRUNCATE);
4476   assert(N->getOperand(0).getOpcode() == ISD::AND);
4477 
4478   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4479   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4480     SDValue N01 = N->getOperand(0).getOperand(1);
4481     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
4482       SDLoc DL(N);
4483       EVT TruncVT = N->getValueType(0);
4484       SDValue N00 = N->getOperand(0).getOperand(0);
4485       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
4486       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
4487       AddToWorklist(Trunc00.getNode());
4488       AddToWorklist(Trunc01.getNode());
4489       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
4490     }
4491   }
4492 
4493   return SDValue();
4494 }
4495 
4496 SDValue DAGCombiner::visitRotate(SDNode *N) {
4497   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4498   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4499       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4500     if (SDValue NewOp1 =
4501             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4502       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4503                          N->getOperand(0), NewOp1);
4504   }
4505   return SDValue();
4506 }
4507 
4508 SDValue DAGCombiner::visitSHL(SDNode *N) {
4509   SDValue N0 = N->getOperand(0);
4510   SDValue N1 = N->getOperand(1);
4511   EVT VT = N0.getValueType();
4512   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4513 
4514   // fold vector ops
4515   if (VT.isVector()) {
4516     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4517       return FoldedVOp;
4518 
4519     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4520     // If setcc produces all-one true value then:
4521     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4522     if (N1CV && N1CV->isConstant()) {
4523       if (N0.getOpcode() == ISD::AND) {
4524         SDValue N00 = N0->getOperand(0);
4525         SDValue N01 = N0->getOperand(1);
4526         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4527 
4528         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4529             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4530                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4531           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4532                                                      N01CV, N1CV))
4533             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4534         }
4535       }
4536     }
4537   }
4538 
4539   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4540 
4541   // fold (shl c1, c2) -> c1<<c2
4542   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4543   if (N0C && N1C && !N1C->isOpaque())
4544     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4545   // fold (shl 0, x) -> 0
4546   if (isNullConstant(N0))
4547     return N0;
4548   // fold (shl x, c >= size(x)) -> undef
4549   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4550     return DAG.getUNDEF(VT);
4551   // fold (shl x, 0) -> x
4552   if (N1C && N1C->isNullValue())
4553     return N0;
4554   // fold (shl undef, x) -> 0
4555   if (N0.isUndef())
4556     return DAG.getConstant(0, SDLoc(N), VT);
4557   // if (shl x, c) is known to be zero, return 0
4558   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4559                             APInt::getAllOnesValue(OpSizeInBits)))
4560     return DAG.getConstant(0, SDLoc(N), VT);
4561   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4562   if (N1.getOpcode() == ISD::TRUNCATE &&
4563       N1.getOperand(0).getOpcode() == ISD::AND) {
4564     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4565       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4566   }
4567 
4568   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4569     return SDValue(N, 0);
4570 
4571   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4572   if (N1C && N0.getOpcode() == ISD::SHL) {
4573     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4574       SDLoc DL(N);
4575       APInt c1 = N0C1->getAPIntValue();
4576       APInt c2 = N1C->getAPIntValue();
4577       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4578 
4579       APInt Sum = c1 + c2;
4580       if (Sum.uge(OpSizeInBits))
4581         return DAG.getConstant(0, DL, VT);
4582 
4583       return DAG.getNode(
4584           ISD::SHL, DL, VT, N0.getOperand(0),
4585           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4586     }
4587   }
4588 
4589   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4590   // For this to be valid, the second form must not preserve any of the bits
4591   // that are shifted out by the inner shift in the first form.  This means
4592   // the outer shift size must be >= the number of bits added by the ext.
4593   // As a corollary, we don't care what kind of ext it is.
4594   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4595               N0.getOpcode() == ISD::ANY_EXTEND ||
4596               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4597       N0.getOperand(0).getOpcode() == ISD::SHL) {
4598     SDValue N0Op0 = N0.getOperand(0);
4599     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4600       APInt c1 = N0Op0C1->getAPIntValue();
4601       APInt c2 = N1C->getAPIntValue();
4602       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4603 
4604       EVT InnerShiftVT = N0Op0.getValueType();
4605       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4606       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
4607         SDLoc DL(N0);
4608         APInt Sum = c1 + c2;
4609         if (Sum.uge(OpSizeInBits))
4610           return DAG.getConstant(0, DL, VT);
4611 
4612         return DAG.getNode(
4613             ISD::SHL, DL, VT,
4614             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
4615             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4616       }
4617     }
4618   }
4619 
4620   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4621   // Only fold this if the inner zext has no other uses to avoid increasing
4622   // the total number of instructions.
4623   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4624       N0.getOperand(0).getOpcode() == ISD::SRL) {
4625     SDValue N0Op0 = N0.getOperand(0);
4626     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4627       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
4628         uint64_t c1 = N0Op0C1->getZExtValue();
4629         uint64_t c2 = N1C->getZExtValue();
4630         if (c1 == c2) {
4631           SDValue NewOp0 = N0.getOperand(0);
4632           EVT CountVT = NewOp0.getOperand(1).getValueType();
4633           SDLoc DL(N);
4634           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4635                                        NewOp0,
4636                                        DAG.getConstant(c2, DL, CountVT));
4637           AddToWorklist(NewSHL.getNode());
4638           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4639         }
4640       }
4641     }
4642   }
4643 
4644   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4645   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4646   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4647       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4648     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4649       uint64_t C1 = N0C1->getZExtValue();
4650       uint64_t C2 = N1C->getZExtValue();
4651       SDLoc DL(N);
4652       if (C1 <= C2)
4653         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4654                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4655       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4656                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4657     }
4658   }
4659 
4660   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4661   //                               (and (srl x, (sub c1, c2), MASK)
4662   // Only fold this if the inner shift has no other uses -- if it does, folding
4663   // this will increase the total number of instructions.
4664   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4665     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4666       uint64_t c1 = N0C1->getZExtValue();
4667       if (c1 < OpSizeInBits) {
4668         uint64_t c2 = N1C->getZExtValue();
4669         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4670         SDValue Shift;
4671         if (c2 > c1) {
4672           Mask = Mask.shl(c2 - c1);
4673           SDLoc DL(N);
4674           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4675                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4676         } else {
4677           Mask = Mask.lshr(c1 - c2);
4678           SDLoc DL(N);
4679           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4680                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4681         }
4682         SDLoc DL(N0);
4683         return DAG.getNode(ISD::AND, DL, VT, Shift,
4684                            DAG.getConstant(Mask, DL, VT));
4685       }
4686     }
4687   }
4688 
4689   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4690   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
4691       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
4692     unsigned BitSize = VT.getScalarSizeInBits();
4693     SDLoc DL(N);
4694     SDValue AllBits = DAG.getConstant(APInt::getAllOnesValue(BitSize), DL, VT);
4695     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
4696     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
4697   }
4698 
4699   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4700   // Variant of version done on multiply, except mul by a power of 2 is turned
4701   // into a shift.
4702   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4703       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
4704       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
4705     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4706     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4707     AddToWorklist(Shl0.getNode());
4708     AddToWorklist(Shl1.getNode());
4709     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4710   }
4711 
4712   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4713   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
4714       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
4715       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
4716     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4717     if (isConstantOrConstantVector(Shl))
4718       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
4719   }
4720 
4721   if (N1C && !N1C->isOpaque())
4722     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4723       return NewSHL;
4724 
4725   return SDValue();
4726 }
4727 
4728 SDValue DAGCombiner::visitSRA(SDNode *N) {
4729   SDValue N0 = N->getOperand(0);
4730   SDValue N1 = N->getOperand(1);
4731   EVT VT = N0.getValueType();
4732   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4733 
4734   // Arithmetic shifting an all-sign-bit value is a no-op.
4735   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
4736     return N0;
4737 
4738   // fold vector ops
4739   if (VT.isVector())
4740     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4741       return FoldedVOp;
4742 
4743   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4744 
4745   // fold (sra c1, c2) -> (sra c1, c2)
4746   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4747   if (N0C && N1C && !N1C->isOpaque())
4748     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4749   // fold (sra 0, x) -> 0
4750   if (isNullConstant(N0))
4751     return N0;
4752   // fold (sra -1, x) -> -1
4753   if (isAllOnesConstant(N0))
4754     return N0;
4755   // fold (sra x, c >= size(x)) -> undef
4756   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4757     return DAG.getUNDEF(VT);
4758   // fold (sra x, 0) -> x
4759   if (N1C && N1C->isNullValue())
4760     return N0;
4761   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4762   // sext_inreg.
4763   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4764     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4765     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4766     if (VT.isVector())
4767       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4768                                ExtVT, VT.getVectorNumElements());
4769     if ((!LegalOperations ||
4770          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4771       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4772                          N0.getOperand(0), DAG.getValueType(ExtVT));
4773   }
4774 
4775   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4776   if (N1C && N0.getOpcode() == ISD::SRA) {
4777     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4778       SDLoc DL(N);
4779       APInt c1 = N0C1->getAPIntValue();
4780       APInt c2 = N1C->getAPIntValue();
4781       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4782 
4783       APInt Sum = c1 + c2;
4784       if (Sum.uge(OpSizeInBits))
4785         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
4786 
4787       return DAG.getNode(
4788           ISD::SRA, DL, VT, N0.getOperand(0),
4789           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4790     }
4791   }
4792 
4793   // fold (sra (shl X, m), (sub result_size, n))
4794   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4795   // result_size - n != m.
4796   // If truncate is free for the target sext(shl) is likely to result in better
4797   // code.
4798   if (N0.getOpcode() == ISD::SHL && N1C) {
4799     // Get the two constanst of the shifts, CN0 = m, CN = n.
4800     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4801     if (N01C) {
4802       LLVMContext &Ctx = *DAG.getContext();
4803       // Determine what the truncate's result bitsize and type would be.
4804       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4805 
4806       if (VT.isVector())
4807         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4808 
4809       // Determine the residual right-shift amount.
4810       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4811 
4812       // If the shift is not a no-op (in which case this should be just a sign
4813       // extend already), the truncated to type is legal, sign_extend is legal
4814       // on that type, and the truncate to that type is both legal and free,
4815       // perform the transform.
4816       if ((ShiftAmt > 0) &&
4817           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4818           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4819           TLI.isTruncateFree(VT, TruncVT)) {
4820 
4821         SDLoc DL(N);
4822         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4823             getShiftAmountTy(N0.getOperand(0).getValueType()));
4824         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4825                                     N0.getOperand(0), Amt);
4826         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4827                                     Shift);
4828         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4829                            N->getValueType(0), Trunc);
4830       }
4831     }
4832   }
4833 
4834   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4835   if (N1.getOpcode() == ISD::TRUNCATE &&
4836       N1.getOperand(0).getOpcode() == ISD::AND) {
4837     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4838       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4839   }
4840 
4841   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4842   //      if c1 is equal to the number of bits the trunc removes
4843   if (N0.getOpcode() == ISD::TRUNCATE &&
4844       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4845        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4846       N0.getOperand(0).hasOneUse() &&
4847       N0.getOperand(0).getOperand(1).hasOneUse() &&
4848       N1C) {
4849     SDValue N0Op0 = N0.getOperand(0);
4850     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4851       unsigned LargeShiftVal = LargeShift->getZExtValue();
4852       EVT LargeVT = N0Op0.getValueType();
4853 
4854       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4855         SDLoc DL(N);
4856         SDValue Amt =
4857           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4858                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4859         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4860                                   N0Op0.getOperand(0), Amt);
4861         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4862       }
4863     }
4864   }
4865 
4866   // Simplify, based on bits shifted out of the LHS.
4867   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4868     return SDValue(N, 0);
4869 
4870 
4871   // If the sign bit is known to be zero, switch this to a SRL.
4872   if (DAG.SignBitIsZero(N0))
4873     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4874 
4875   if (N1C && !N1C->isOpaque())
4876     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4877       return NewSRA;
4878 
4879   return SDValue();
4880 }
4881 
4882 SDValue DAGCombiner::visitSRL(SDNode *N) {
4883   SDValue N0 = N->getOperand(0);
4884   SDValue N1 = N->getOperand(1);
4885   EVT VT = N0.getValueType();
4886   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4887 
4888   // fold vector ops
4889   if (VT.isVector())
4890     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4891       return FoldedVOp;
4892 
4893   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4894 
4895   // fold (srl c1, c2) -> c1 >>u c2
4896   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4897   if (N0C && N1C && !N1C->isOpaque())
4898     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4899   // fold (srl 0, x) -> 0
4900   if (isNullConstant(N0))
4901     return N0;
4902   // fold (srl x, c >= size(x)) -> undef
4903   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4904     return DAG.getUNDEF(VT);
4905   // fold (srl x, 0) -> x
4906   if (N1C && N1C->isNullValue())
4907     return N0;
4908   // if (srl x, c) is known to be zero, return 0
4909   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4910                                    APInt::getAllOnesValue(OpSizeInBits)))
4911     return DAG.getConstant(0, SDLoc(N), VT);
4912 
4913   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4914   if (N1C && N0.getOpcode() == ISD::SRL) {
4915     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4916       SDLoc DL(N);
4917       APInt c1 = N0C1->getAPIntValue();
4918       APInt c2 = N1C->getAPIntValue();
4919       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4920 
4921       APInt Sum = c1 + c2;
4922       if (Sum.uge(OpSizeInBits))
4923         return DAG.getConstant(0, DL, VT);
4924 
4925       return DAG.getNode(
4926           ISD::SRL, DL, VT, N0.getOperand(0),
4927           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4928     }
4929   }
4930 
4931   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4932   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4933       N0.getOperand(0).getOpcode() == ISD::SRL &&
4934       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4935     uint64_t c1 =
4936       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4937     uint64_t c2 = N1C->getZExtValue();
4938     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4939     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4940     uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4941     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4942     if (c1 + OpSizeInBits == InnerShiftSize) {
4943       SDLoc DL(N0);
4944       if (c1 + c2 >= InnerShiftSize)
4945         return DAG.getConstant(0, DL, VT);
4946       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4947                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4948                                      N0.getOperand(0)->getOperand(0),
4949                                      DAG.getConstant(c1 + c2, DL,
4950                                                      ShiftCountVT)));
4951     }
4952   }
4953 
4954   // fold (srl (shl x, c), c) -> (and x, cst2)
4955   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4956       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
4957     SDLoc DL(N);
4958     APInt AllBits = APInt::getAllOnesValue(N0.getScalarValueSizeInBits());
4959     SDValue Mask =
4960         DAG.getNode(ISD::SRL, DL, VT, DAG.getConstant(AllBits, DL, VT), N1);
4961     AddToWorklist(Mask.getNode());
4962     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
4963   }
4964 
4965   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4966   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4967     // Shifting in all undef bits?
4968     EVT SmallVT = N0.getOperand(0).getValueType();
4969     unsigned BitSize = SmallVT.getScalarSizeInBits();
4970     if (N1C->getZExtValue() >= BitSize)
4971       return DAG.getUNDEF(VT);
4972 
4973     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4974       uint64_t ShiftAmt = N1C->getZExtValue();
4975       SDLoc DL0(N0);
4976       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4977                                        N0.getOperand(0),
4978                           DAG.getConstant(ShiftAmt, DL0,
4979                                           getShiftAmountTy(SmallVT)));
4980       AddToWorklist(SmallShift.getNode());
4981       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4982       SDLoc DL(N);
4983       return DAG.getNode(ISD::AND, DL, VT,
4984                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4985                          DAG.getConstant(Mask, DL, VT));
4986     }
4987   }
4988 
4989   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4990   // bit, which is unmodified by sra.
4991   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4992     if (N0.getOpcode() == ISD::SRA)
4993       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4994   }
4995 
4996   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4997   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4998       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4999     APInt KnownZero, KnownOne;
5000     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
5001 
5002     // If any of the input bits are KnownOne, then the input couldn't be all
5003     // zeros, thus the result of the srl will always be zero.
5004     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5005 
5006     // If all of the bits input the to ctlz node are known to be zero, then
5007     // the result of the ctlz is "32" and the result of the shift is one.
5008     APInt UnknownBits = ~KnownZero;
5009     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5010 
5011     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5012     if ((UnknownBits & (UnknownBits - 1)) == 0) {
5013       // Okay, we know that only that the single bit specified by UnknownBits
5014       // could be set on input to the CTLZ node. If this bit is set, the SRL
5015       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5016       // to an SRL/XOR pair, which is likely to simplify more.
5017       unsigned ShAmt = UnknownBits.countTrailingZeros();
5018       SDValue Op = N0.getOperand(0);
5019 
5020       if (ShAmt) {
5021         SDLoc DL(N0);
5022         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5023                   DAG.getConstant(ShAmt, DL,
5024                                   getShiftAmountTy(Op.getValueType())));
5025         AddToWorklist(Op.getNode());
5026       }
5027 
5028       SDLoc DL(N);
5029       return DAG.getNode(ISD::XOR, DL, VT,
5030                          Op, DAG.getConstant(1, DL, VT));
5031     }
5032   }
5033 
5034   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5035   if (N1.getOpcode() == ISD::TRUNCATE &&
5036       N1.getOperand(0).getOpcode() == ISD::AND) {
5037     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5038       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5039   }
5040 
5041   // fold operands of srl based on knowledge that the low bits are not
5042   // demanded.
5043   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5044     return SDValue(N, 0);
5045 
5046   if (N1C && !N1C->isOpaque())
5047     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5048       return NewSRL;
5049 
5050   // Attempt to convert a srl of a load into a narrower zero-extending load.
5051   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5052     return NarrowLoad;
5053 
5054   // Here is a common situation. We want to optimize:
5055   //
5056   //   %a = ...
5057   //   %b = and i32 %a, 2
5058   //   %c = srl i32 %b, 1
5059   //   brcond i32 %c ...
5060   //
5061   // into
5062   //
5063   //   %a = ...
5064   //   %b = and %a, 2
5065   //   %c = setcc eq %b, 0
5066   //   brcond %c ...
5067   //
5068   // However when after the source operand of SRL is optimized into AND, the SRL
5069   // itself may not be optimized further. Look for it and add the BRCOND into
5070   // the worklist.
5071   if (N->hasOneUse()) {
5072     SDNode *Use = *N->use_begin();
5073     if (Use->getOpcode() == ISD::BRCOND)
5074       AddToWorklist(Use);
5075     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5076       // Also look pass the truncate.
5077       Use = *Use->use_begin();
5078       if (Use->getOpcode() == ISD::BRCOND)
5079         AddToWorklist(Use);
5080     }
5081   }
5082 
5083   return SDValue();
5084 }
5085 
5086 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5087   SDValue N0 = N->getOperand(0);
5088   EVT VT = N->getValueType(0);
5089 
5090   // fold (bswap c1) -> c2
5091   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5092     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5093   // fold (bswap (bswap x)) -> x
5094   if (N0.getOpcode() == ISD::BSWAP)
5095     return N0->getOperand(0);
5096   return SDValue();
5097 }
5098 
5099 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5100   SDValue N0 = N->getOperand(0);
5101 
5102   // fold (bitreverse (bitreverse x)) -> x
5103   if (N0.getOpcode() == ISD::BITREVERSE)
5104     return N0.getOperand(0);
5105   return SDValue();
5106 }
5107 
5108 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5109   SDValue N0 = N->getOperand(0);
5110   EVT VT = N->getValueType(0);
5111 
5112   // fold (ctlz c1) -> c2
5113   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5114     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5115   return SDValue();
5116 }
5117 
5118 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5119   SDValue N0 = N->getOperand(0);
5120   EVT VT = N->getValueType(0);
5121 
5122   // fold (ctlz_zero_undef c1) -> c2
5123   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5124     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5125   return SDValue();
5126 }
5127 
5128 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5129   SDValue N0 = N->getOperand(0);
5130   EVT VT = N->getValueType(0);
5131 
5132   // fold (cttz c1) -> c2
5133   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5134     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5135   return SDValue();
5136 }
5137 
5138 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5139   SDValue N0 = N->getOperand(0);
5140   EVT VT = N->getValueType(0);
5141 
5142   // fold (cttz_zero_undef c1) -> c2
5143   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5144     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5145   return SDValue();
5146 }
5147 
5148 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5149   SDValue N0 = N->getOperand(0);
5150   EVT VT = N->getValueType(0);
5151 
5152   // fold (ctpop c1) -> c2
5153   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5154     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5155   return SDValue();
5156 }
5157 
5158 
5159 /// \brief Generate Min/Max node
5160 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5161                                    SDValue RHS, SDValue True, SDValue False,
5162                                    ISD::CondCode CC, const TargetLowering &TLI,
5163                                    SelectionDAG &DAG) {
5164   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5165     return SDValue();
5166 
5167   switch (CC) {
5168   case ISD::SETOLT:
5169   case ISD::SETOLE:
5170   case ISD::SETLT:
5171   case ISD::SETLE:
5172   case ISD::SETULT:
5173   case ISD::SETULE: {
5174     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5175     if (TLI.isOperationLegal(Opcode, VT))
5176       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5177     return SDValue();
5178   }
5179   case ISD::SETOGT:
5180   case ISD::SETOGE:
5181   case ISD::SETGT:
5182   case ISD::SETGE:
5183   case ISD::SETUGT:
5184   case ISD::SETUGE: {
5185     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5186     if (TLI.isOperationLegal(Opcode, VT))
5187       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5188     return SDValue();
5189   }
5190   default:
5191     return SDValue();
5192   }
5193 }
5194 
5195 // TODO: We should handle other cases of selecting between {-1,0,1} here.
5196 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5197   SDValue Cond = N->getOperand(0);
5198   SDValue N1 = N->getOperand(1);
5199   SDValue N2 = N->getOperand(2);
5200   EVT VT = N->getValueType(0);
5201   EVT CondVT = Cond.getValueType();
5202   SDLoc DL(N);
5203 
5204   // fold (select Cond, 0, 1) -> (xor Cond, 1)
5205   // We can't do this reliably if integer based booleans have different contents
5206   // to floating point based booleans. This is because we can't tell whether we
5207   // have an integer-based boolean or a floating-point-based boolean unless we
5208   // can find the SETCC that produced it and inspect its operands. This is
5209   // fairly easy if C is the SETCC node, but it can potentially be
5210   // undiscoverable (or not reasonably discoverable). For example, it could be
5211   // in another basic block or it could require searching a complicated
5212   // expression.
5213   if (VT.isInteger() &&
5214       (CondVT == MVT::i1 || (CondVT.isInteger() &&
5215                              TLI.getBooleanContents(false, true) ==
5216                                  TargetLowering::ZeroOrOneBooleanContent &&
5217                              TLI.getBooleanContents(false, false) ==
5218                                  TargetLowering::ZeroOrOneBooleanContent)) &&
5219       isNullConstant(N1) && isOneConstant(N2)) {
5220     SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
5221                                   DAG.getConstant(1, DL, CondVT));
5222     if (VT.bitsEq(CondVT))
5223       return NotCond;
5224     return DAG.getZExtOrTrunc(NotCond, DL, VT);
5225   }
5226 
5227   return SDValue();
5228 }
5229 
5230 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5231   SDValue N0 = N->getOperand(0);
5232   SDValue N1 = N->getOperand(1);
5233   SDValue N2 = N->getOperand(2);
5234   EVT VT = N->getValueType(0);
5235   EVT VT0 = N0.getValueType();
5236 
5237   // fold (select C, X, X) -> X
5238   if (N1 == N2)
5239     return N1;
5240   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5241     // fold (select true, X, Y) -> X
5242     // fold (select false, X, Y) -> Y
5243     return !N0C->isNullValue() ? N1 : N2;
5244   }
5245   // fold (select C, 1, X) -> (or C, X)
5246   if (VT == MVT::i1 && isOneConstant(N1))
5247     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5248 
5249   if (SDValue V = foldSelectOfConstants(N))
5250     return V;
5251 
5252   // fold (select C, 0, X) -> (and (not C), X)
5253   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5254     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5255     AddToWorklist(NOTNode.getNode());
5256     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5257   }
5258   // fold (select C, X, 1) -> (or (not C), X)
5259   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5260     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5261     AddToWorklist(NOTNode.getNode());
5262     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5263   }
5264   // fold (select C, X, 0) -> (and C, X)
5265   if (VT == MVT::i1 && isNullConstant(N2))
5266     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5267   // fold (select X, X, Y) -> (or X, Y)
5268   // fold (select X, 1, Y) -> (or X, Y)
5269   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5270     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5271   // fold (select X, Y, X) -> (and X, Y)
5272   // fold (select X, Y, 0) -> (and X, Y)
5273   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5274     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5275 
5276   // If we can fold this based on the true/false value, do so.
5277   if (SimplifySelectOps(N, N1, N2))
5278     return SDValue(N, 0);  // Don't revisit N.
5279 
5280   if (VT0 == MVT::i1) {
5281     // The code in this block deals with the following 2 equivalences:
5282     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5283     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5284     // The target can specify its preferred form with the
5285     // shouldNormalizeToSelectSequence() callback. However we always transform
5286     // to the right anyway if we find the inner select exists in the DAG anyway
5287     // and we always transform to the left side if we know that we can further
5288     // optimize the combination of the conditions.
5289     bool normalizeToSequence
5290       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5291     // select (and Cond0, Cond1), X, Y
5292     //   -> select Cond0, (select Cond1, X, Y), Y
5293     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5294       SDValue Cond0 = N0->getOperand(0);
5295       SDValue Cond1 = N0->getOperand(1);
5296       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5297                                         N1.getValueType(), Cond1, N1, N2);
5298       if (normalizeToSequence || !InnerSelect.use_empty())
5299         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5300                            InnerSelect, N2);
5301     }
5302     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5303     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5304       SDValue Cond0 = N0->getOperand(0);
5305       SDValue Cond1 = N0->getOperand(1);
5306       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5307                                         N1.getValueType(), Cond1, N1, N2);
5308       if (normalizeToSequence || !InnerSelect.use_empty())
5309         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5310                            InnerSelect);
5311     }
5312 
5313     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5314     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5315       SDValue N1_0 = N1->getOperand(0);
5316       SDValue N1_1 = N1->getOperand(1);
5317       SDValue N1_2 = N1->getOperand(2);
5318       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5319         // Create the actual and node if we can generate good code for it.
5320         if (!normalizeToSequence) {
5321           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5322                                     N0, N1_0);
5323           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5324                              N1_1, N2);
5325         }
5326         // Otherwise see if we can optimize the "and" to a better pattern.
5327         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5328           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5329                              N1_1, N2);
5330       }
5331     }
5332     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5333     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5334       SDValue N2_0 = N2->getOperand(0);
5335       SDValue N2_1 = N2->getOperand(1);
5336       SDValue N2_2 = N2->getOperand(2);
5337       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5338         // Create the actual or node if we can generate good code for it.
5339         if (!normalizeToSequence) {
5340           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5341                                    N0, N2_0);
5342           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5343                              N1, N2_2);
5344         }
5345         // Otherwise see if we can optimize to a better pattern.
5346         if (SDValue Combined = visitORLike(N0, N2_0, N))
5347           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5348                              N1, N2_2);
5349       }
5350     }
5351   }
5352 
5353   // select (xor Cond, 1), X, Y -> select Cond, Y, X
5354   // select (xor Cond, 0), X, Y -> selext Cond, X, Y
5355   if (VT0 == MVT::i1) {
5356     if (N0->getOpcode() == ISD::XOR) {
5357       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
5358         SDValue Cond0 = N0->getOperand(0);
5359         if (C->isOne())
5360           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5361                              Cond0, N2, N1);
5362         else
5363           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5364                              Cond0, N1, N2);
5365       }
5366     }
5367   }
5368 
5369   // fold selects based on a setcc into other things, such as min/max/abs
5370   if (N0.getOpcode() == ISD::SETCC) {
5371     // select x, y (fcmp lt x, y) -> fminnum x, y
5372     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5373     //
5374     // This is OK if we don't care about what happens if either operand is a
5375     // NaN.
5376     //
5377 
5378     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5379     // no signed zeros as well as no nans.
5380     const TargetOptions &Options = DAG.getTarget().Options;
5381     if (Options.UnsafeFPMath &&
5382         VT.isFloatingPoint() && N0.hasOneUse() &&
5383         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5384       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5385 
5386       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5387                                                 N0.getOperand(1), N1, N2, CC,
5388                                                 TLI, DAG))
5389         return FMinMax;
5390     }
5391 
5392     if ((!LegalOperations &&
5393          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5394         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5395       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5396                          N0.getOperand(0), N0.getOperand(1),
5397                          N1, N2, N0.getOperand(2));
5398     return SimplifySelect(SDLoc(N), N0, N1, N2);
5399   }
5400 
5401   return SDValue();
5402 }
5403 
5404 static
5405 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5406   SDLoc DL(N);
5407   EVT LoVT, HiVT;
5408   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5409 
5410   // Split the inputs.
5411   SDValue Lo, Hi, LL, LH, RL, RH;
5412   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5413   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5414 
5415   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5416   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5417 
5418   return std::make_pair(Lo, Hi);
5419 }
5420 
5421 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5422 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5423 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5424   SDLoc DL(N);
5425   SDValue Cond = N->getOperand(0);
5426   SDValue LHS = N->getOperand(1);
5427   SDValue RHS = N->getOperand(2);
5428   EVT VT = N->getValueType(0);
5429   int NumElems = VT.getVectorNumElements();
5430   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5431          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5432          Cond.getOpcode() == ISD::BUILD_VECTOR);
5433 
5434   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5435   // binary ones here.
5436   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5437     return SDValue();
5438 
5439   // We're sure we have an even number of elements due to the
5440   // concat_vectors we have as arguments to vselect.
5441   // Skip BV elements until we find one that's not an UNDEF
5442   // After we find an UNDEF element, keep looping until we get to half the
5443   // length of the BV and see if all the non-undef nodes are the same.
5444   ConstantSDNode *BottomHalf = nullptr;
5445   for (int i = 0; i < NumElems / 2; ++i) {
5446     if (Cond->getOperand(i)->isUndef())
5447       continue;
5448 
5449     if (BottomHalf == nullptr)
5450       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5451     else if (Cond->getOperand(i).getNode() != BottomHalf)
5452       return SDValue();
5453   }
5454 
5455   // Do the same for the second half of the BuildVector
5456   ConstantSDNode *TopHalf = nullptr;
5457   for (int i = NumElems / 2; i < NumElems; ++i) {
5458     if (Cond->getOperand(i)->isUndef())
5459       continue;
5460 
5461     if (TopHalf == nullptr)
5462       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5463     else if (Cond->getOperand(i).getNode() != TopHalf)
5464       return SDValue();
5465   }
5466 
5467   assert(TopHalf && BottomHalf &&
5468          "One half of the selector was all UNDEFs and the other was all the "
5469          "same value. This should have been addressed before this function.");
5470   return DAG.getNode(
5471       ISD::CONCAT_VECTORS, DL, VT,
5472       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5473       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5474 }
5475 
5476 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5477 
5478   if (Level >= AfterLegalizeTypes)
5479     return SDValue();
5480 
5481   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5482   SDValue Mask = MSC->getMask();
5483   SDValue Data  = MSC->getValue();
5484   SDLoc DL(N);
5485 
5486   // If the MSCATTER data type requires splitting and the mask is provided by a
5487   // SETCC, then split both nodes and its operands before legalization. This
5488   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5489   // and enables future optimizations (e.g. min/max pattern matching on X86).
5490   if (Mask.getOpcode() != ISD::SETCC)
5491     return SDValue();
5492 
5493   // Check if any splitting is required.
5494   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5495       TargetLowering::TypeSplitVector)
5496     return SDValue();
5497   SDValue MaskLo, MaskHi, Lo, Hi;
5498   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5499 
5500   EVT LoVT, HiVT;
5501   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5502 
5503   SDValue Chain = MSC->getChain();
5504 
5505   EVT MemoryVT = MSC->getMemoryVT();
5506   unsigned Alignment = MSC->getOriginalAlignment();
5507 
5508   EVT LoMemVT, HiMemVT;
5509   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5510 
5511   SDValue DataLo, DataHi;
5512   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5513 
5514   SDValue BasePtr = MSC->getBasePtr();
5515   SDValue IndexLo, IndexHi;
5516   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5517 
5518   MachineMemOperand *MMO = DAG.getMachineFunction().
5519     getMachineMemOperand(MSC->getPointerInfo(),
5520                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5521                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5522 
5523   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5524   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5525                             DL, OpsLo, MMO);
5526 
5527   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5528   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5529                             DL, OpsHi, MMO);
5530 
5531   AddToWorklist(Lo.getNode());
5532   AddToWorklist(Hi.getNode());
5533 
5534   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5535 }
5536 
5537 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5538 
5539   if (Level >= AfterLegalizeTypes)
5540     return SDValue();
5541 
5542   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5543   SDValue Mask = MST->getMask();
5544   SDValue Data  = MST->getValue();
5545   EVT VT = Data.getValueType();
5546   SDLoc DL(N);
5547 
5548   // If the MSTORE data type requires splitting and the mask is provided by a
5549   // SETCC, then split both nodes and its operands before legalization. This
5550   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5551   // and enables future optimizations (e.g. min/max pattern matching on X86).
5552   if (Mask.getOpcode() == ISD::SETCC) {
5553 
5554     // Check if any splitting is required.
5555     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5556         TargetLowering::TypeSplitVector)
5557       return SDValue();
5558 
5559     SDValue MaskLo, MaskHi, Lo, Hi;
5560     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5561 
5562     SDValue Chain = MST->getChain();
5563     SDValue Ptr   = MST->getBasePtr();
5564 
5565     EVT MemoryVT = MST->getMemoryVT();
5566     unsigned Alignment = MST->getOriginalAlignment();
5567 
5568     // if Alignment is equal to the vector size,
5569     // take the half of it for the second part
5570     unsigned SecondHalfAlignment =
5571       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
5572 
5573     EVT LoMemVT, HiMemVT;
5574     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5575 
5576     SDValue DataLo, DataHi;
5577     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5578 
5579     MachineMemOperand *MMO = DAG.getMachineFunction().
5580       getMachineMemOperand(MST->getPointerInfo(),
5581                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5582                            Alignment, MST->getAAInfo(), MST->getRanges());
5583 
5584     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5585                             MST->isTruncatingStore(),
5586                             MST->isCompressingStore());
5587 
5588     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
5589                                      MST->isCompressingStore());
5590 
5591     MMO = DAG.getMachineFunction().
5592       getMachineMemOperand(MST->getPointerInfo(),
5593                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5594                            SecondHalfAlignment, MST->getAAInfo(),
5595                            MST->getRanges());
5596 
5597     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5598                             MST->isTruncatingStore(),
5599                             MST->isCompressingStore());
5600 
5601     AddToWorklist(Lo.getNode());
5602     AddToWorklist(Hi.getNode());
5603 
5604     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5605   }
5606   return SDValue();
5607 }
5608 
5609 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5610 
5611   if (Level >= AfterLegalizeTypes)
5612     return SDValue();
5613 
5614   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5615   SDValue Mask = MGT->getMask();
5616   SDLoc DL(N);
5617 
5618   // If the MGATHER result requires splitting and the mask is provided by a
5619   // SETCC, then split both nodes and its operands before legalization. This
5620   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5621   // and enables future optimizations (e.g. min/max pattern matching on X86).
5622 
5623   if (Mask.getOpcode() != ISD::SETCC)
5624     return SDValue();
5625 
5626   EVT VT = N->getValueType(0);
5627 
5628   // Check if any splitting is required.
5629   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5630       TargetLowering::TypeSplitVector)
5631     return SDValue();
5632 
5633   SDValue MaskLo, MaskHi, Lo, Hi;
5634   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5635 
5636   SDValue Src0 = MGT->getValue();
5637   SDValue Src0Lo, Src0Hi;
5638   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5639 
5640   EVT LoVT, HiVT;
5641   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5642 
5643   SDValue Chain = MGT->getChain();
5644   EVT MemoryVT = MGT->getMemoryVT();
5645   unsigned Alignment = MGT->getOriginalAlignment();
5646 
5647   EVT LoMemVT, HiMemVT;
5648   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5649 
5650   SDValue BasePtr = MGT->getBasePtr();
5651   SDValue Index = MGT->getIndex();
5652   SDValue IndexLo, IndexHi;
5653   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5654 
5655   MachineMemOperand *MMO = DAG.getMachineFunction().
5656     getMachineMemOperand(MGT->getPointerInfo(),
5657                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5658                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5659 
5660   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5661   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5662                             MMO);
5663 
5664   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5665   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5666                             MMO);
5667 
5668   AddToWorklist(Lo.getNode());
5669   AddToWorklist(Hi.getNode());
5670 
5671   // Build a factor node to remember that this load is independent of the
5672   // other one.
5673   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5674                       Hi.getValue(1));
5675 
5676   // Legalized the chain result - switch anything that used the old chain to
5677   // use the new one.
5678   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5679 
5680   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5681 
5682   SDValue RetOps[] = { GatherRes, Chain };
5683   return DAG.getMergeValues(RetOps, DL);
5684 }
5685 
5686 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5687 
5688   if (Level >= AfterLegalizeTypes)
5689     return SDValue();
5690 
5691   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5692   SDValue Mask = MLD->getMask();
5693   SDLoc DL(N);
5694 
5695   // If the MLOAD result requires splitting and the mask is provided by a
5696   // SETCC, then split both nodes and its operands before legalization. This
5697   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5698   // and enables future optimizations (e.g. min/max pattern matching on X86).
5699 
5700   if (Mask.getOpcode() == ISD::SETCC) {
5701     EVT VT = N->getValueType(0);
5702 
5703     // Check if any splitting is required.
5704     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5705         TargetLowering::TypeSplitVector)
5706       return SDValue();
5707 
5708     SDValue MaskLo, MaskHi, Lo, Hi;
5709     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5710 
5711     SDValue Src0 = MLD->getSrc0();
5712     SDValue Src0Lo, Src0Hi;
5713     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5714 
5715     EVT LoVT, HiVT;
5716     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5717 
5718     SDValue Chain = MLD->getChain();
5719     SDValue Ptr   = MLD->getBasePtr();
5720     EVT MemoryVT = MLD->getMemoryVT();
5721     unsigned Alignment = MLD->getOriginalAlignment();
5722 
5723     // if Alignment is equal to the vector size,
5724     // take the half of it for the second part
5725     unsigned SecondHalfAlignment =
5726       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5727          Alignment/2 : Alignment;
5728 
5729     EVT LoMemVT, HiMemVT;
5730     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5731 
5732     MachineMemOperand *MMO = DAG.getMachineFunction().
5733     getMachineMemOperand(MLD->getPointerInfo(),
5734                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5735                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5736 
5737     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5738                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
5739 
5740     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
5741                                      MLD->isExpandingLoad());
5742 
5743     MMO = DAG.getMachineFunction().
5744     getMachineMemOperand(MLD->getPointerInfo(),
5745                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5746                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5747 
5748     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5749                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
5750 
5751     AddToWorklist(Lo.getNode());
5752     AddToWorklist(Hi.getNode());
5753 
5754     // Build a factor node to remember that this load is independent of the
5755     // other one.
5756     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5757                         Hi.getValue(1));
5758 
5759     // Legalized the chain result - switch anything that used the old chain to
5760     // use the new one.
5761     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5762 
5763     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5764 
5765     SDValue RetOps[] = { LoadRes, Chain };
5766     return DAG.getMergeValues(RetOps, DL);
5767   }
5768   return SDValue();
5769 }
5770 
5771 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5772   SDValue N0 = N->getOperand(0);
5773   SDValue N1 = N->getOperand(1);
5774   SDValue N2 = N->getOperand(2);
5775   SDLoc DL(N);
5776 
5777   // Canonicalize integer abs.
5778   // vselect (setg[te] X,  0),  X, -X ->
5779   // vselect (setgt    X, -1),  X, -X ->
5780   // vselect (setl[te] X,  0), -X,  X ->
5781   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5782   if (N0.getOpcode() == ISD::SETCC) {
5783     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5784     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5785     bool isAbs = false;
5786     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5787 
5788     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5789          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5790         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5791       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5792     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5793              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5794       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5795 
5796     if (isAbs) {
5797       EVT VT = LHS.getValueType();
5798       SDValue Shift = DAG.getNode(
5799           ISD::SRA, DL, VT, LHS,
5800           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
5801       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5802       AddToWorklist(Shift.getNode());
5803       AddToWorklist(Add.getNode());
5804       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5805     }
5806   }
5807 
5808   if (SimplifySelectOps(N, N1, N2))
5809     return SDValue(N, 0);  // Don't revisit N.
5810 
5811   // If the VSELECT result requires splitting and the mask is provided by a
5812   // SETCC, then split both nodes and its operands before legalization. This
5813   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5814   // and enables future optimizations (e.g. min/max pattern matching on X86).
5815   if (N0.getOpcode() == ISD::SETCC) {
5816     EVT VT = N->getValueType(0);
5817 
5818     // Check if any splitting is required.
5819     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5820         TargetLowering::TypeSplitVector)
5821       return SDValue();
5822 
5823     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5824     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5825     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5826     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5827 
5828     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5829     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5830 
5831     // Add the new VSELECT nodes to the work list in case they need to be split
5832     // again.
5833     AddToWorklist(Lo.getNode());
5834     AddToWorklist(Hi.getNode());
5835 
5836     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5837   }
5838 
5839   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5840   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5841     return N1;
5842   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5843   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5844     return N2;
5845 
5846   // The ConvertSelectToConcatVector function is assuming both the above
5847   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5848   // and addressed.
5849   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5850       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5851       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5852     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5853       return CV;
5854   }
5855 
5856   return SDValue();
5857 }
5858 
5859 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5860   SDValue N0 = N->getOperand(0);
5861   SDValue N1 = N->getOperand(1);
5862   SDValue N2 = N->getOperand(2);
5863   SDValue N3 = N->getOperand(3);
5864   SDValue N4 = N->getOperand(4);
5865   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5866 
5867   // fold select_cc lhs, rhs, x, x, cc -> x
5868   if (N2 == N3)
5869     return N2;
5870 
5871   // Determine if the condition we're dealing with is constant
5872   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5873                                   CC, SDLoc(N), false)) {
5874     AddToWorklist(SCC.getNode());
5875 
5876     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5877       if (!SCCC->isNullValue())
5878         return N2;    // cond always true -> true val
5879       else
5880         return N3;    // cond always false -> false val
5881     } else if (SCC->isUndef()) {
5882       // When the condition is UNDEF, just return the first operand. This is
5883       // coherent the DAG creation, no setcc node is created in this case
5884       return N2;
5885     } else if (SCC.getOpcode() == ISD::SETCC) {
5886       // Fold to a simpler select_cc
5887       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5888                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5889                          SCC.getOperand(2));
5890     }
5891   }
5892 
5893   // If we can fold this based on the true/false value, do so.
5894   if (SimplifySelectOps(N, N2, N3))
5895     return SDValue(N, 0);  // Don't revisit N.
5896 
5897   // fold select_cc into other things, such as min/max/abs
5898   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5899 }
5900 
5901 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5902   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5903                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5904                        SDLoc(N));
5905 }
5906 
5907 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5908   SDValue LHS = N->getOperand(0);
5909   SDValue RHS = N->getOperand(1);
5910   SDValue Carry = N->getOperand(2);
5911   SDValue Cond = N->getOperand(3);
5912 
5913   // If Carry is false, fold to a regular SETCC.
5914   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5915     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5916 
5917   return SDValue();
5918 }
5919 
5920 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5921 /// a build_vector of constants.
5922 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5923 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5924 /// Vector extends are not folded if operations are legal; this is to
5925 /// avoid introducing illegal build_vector dag nodes.
5926 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5927                                          SelectionDAG &DAG, bool LegalTypes,
5928                                          bool LegalOperations) {
5929   unsigned Opcode = N->getOpcode();
5930   SDValue N0 = N->getOperand(0);
5931   EVT VT = N->getValueType(0);
5932 
5933   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5934          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5935          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5936          && "Expected EXTEND dag node in input!");
5937 
5938   // fold (sext c1) -> c1
5939   // fold (zext c1) -> c1
5940   // fold (aext c1) -> c1
5941   if (isa<ConstantSDNode>(N0))
5942     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5943 
5944   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5945   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5946   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5947   EVT SVT = VT.getScalarType();
5948   if (!(VT.isVector() &&
5949       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5950       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5951     return nullptr;
5952 
5953   // We can fold this node into a build_vector.
5954   unsigned VTBits = SVT.getSizeInBits();
5955   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
5956   SmallVector<SDValue, 8> Elts;
5957   unsigned NumElts = VT.getVectorNumElements();
5958   SDLoc DL(N);
5959 
5960   for (unsigned i=0; i != NumElts; ++i) {
5961     SDValue Op = N0->getOperand(i);
5962     if (Op->isUndef()) {
5963       Elts.push_back(DAG.getUNDEF(SVT));
5964       continue;
5965     }
5966 
5967     SDLoc DL(Op);
5968     // Get the constant value and if needed trunc it to the size of the type.
5969     // Nodes like build_vector might have constants wider than the scalar type.
5970     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5971     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5972       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5973     else
5974       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5975   }
5976 
5977   return DAG.getBuildVector(VT, DL, Elts).getNode();
5978 }
5979 
5980 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5981 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5982 // transformation. Returns true if extension are possible and the above
5983 // mentioned transformation is profitable.
5984 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5985                                     unsigned ExtOpc,
5986                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5987                                     const TargetLowering &TLI) {
5988   bool HasCopyToRegUses = false;
5989   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5990   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5991                             UE = N0.getNode()->use_end();
5992        UI != UE; ++UI) {
5993     SDNode *User = *UI;
5994     if (User == N)
5995       continue;
5996     if (UI.getUse().getResNo() != N0.getResNo())
5997       continue;
5998     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5999     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6000       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6001       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6002         // Sign bits will be lost after a zext.
6003         return false;
6004       bool Add = false;
6005       for (unsigned i = 0; i != 2; ++i) {
6006         SDValue UseOp = User->getOperand(i);
6007         if (UseOp == N0)
6008           continue;
6009         if (!isa<ConstantSDNode>(UseOp))
6010           return false;
6011         Add = true;
6012       }
6013       if (Add)
6014         ExtendNodes.push_back(User);
6015       continue;
6016     }
6017     // If truncates aren't free and there are users we can't
6018     // extend, it isn't worthwhile.
6019     if (!isTruncFree)
6020       return false;
6021     // Remember if this value is live-out.
6022     if (User->getOpcode() == ISD::CopyToReg)
6023       HasCopyToRegUses = true;
6024   }
6025 
6026   if (HasCopyToRegUses) {
6027     bool BothLiveOut = false;
6028     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6029          UI != UE; ++UI) {
6030       SDUse &Use = UI.getUse();
6031       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6032         BothLiveOut = true;
6033         break;
6034       }
6035     }
6036     if (BothLiveOut)
6037       // Both unextended and extended values are live out. There had better be
6038       // a good reason for the transformation.
6039       return ExtendNodes.size();
6040   }
6041   return true;
6042 }
6043 
6044 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6045                                   SDValue Trunc, SDValue ExtLoad,
6046                                   const SDLoc &DL, ISD::NodeType ExtType) {
6047   // Extend SetCC uses if necessary.
6048   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6049     SDNode *SetCC = SetCCs[i];
6050     SmallVector<SDValue, 4> Ops;
6051 
6052     for (unsigned j = 0; j != 2; ++j) {
6053       SDValue SOp = SetCC->getOperand(j);
6054       if (SOp == Trunc)
6055         Ops.push_back(ExtLoad);
6056       else
6057         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6058     }
6059 
6060     Ops.push_back(SetCC->getOperand(2));
6061     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6062   }
6063 }
6064 
6065 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6066 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6067   SDValue N0 = N->getOperand(0);
6068   EVT DstVT = N->getValueType(0);
6069   EVT SrcVT = N0.getValueType();
6070 
6071   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6072           N->getOpcode() == ISD::ZERO_EXTEND) &&
6073          "Unexpected node type (not an extend)!");
6074 
6075   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6076   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6077   //   (v8i32 (sext (v8i16 (load x))))
6078   // into:
6079   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6080   //                          (v4i32 (sextload (x + 16)))))
6081   // Where uses of the original load, i.e.:
6082   //   (v8i16 (load x))
6083   // are replaced with:
6084   //   (v8i16 (truncate
6085   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6086   //                            (v4i32 (sextload (x + 16)))))))
6087   //
6088   // This combine is only applicable to illegal, but splittable, vectors.
6089   // All legal types, and illegal non-vector types, are handled elsewhere.
6090   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6091   //
6092   if (N0->getOpcode() != ISD::LOAD)
6093     return SDValue();
6094 
6095   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6096 
6097   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6098       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6099       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6100     return SDValue();
6101 
6102   SmallVector<SDNode *, 4> SetCCs;
6103   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6104     return SDValue();
6105 
6106   ISD::LoadExtType ExtType =
6107       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6108 
6109   // Try to split the vector types to get down to legal types.
6110   EVT SplitSrcVT = SrcVT;
6111   EVT SplitDstVT = DstVT;
6112   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6113          SplitSrcVT.getVectorNumElements() > 1) {
6114     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6115     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6116   }
6117 
6118   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6119     return SDValue();
6120 
6121   SDLoc DL(N);
6122   const unsigned NumSplits =
6123       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6124   const unsigned Stride = SplitSrcVT.getStoreSize();
6125   SmallVector<SDValue, 4> Loads;
6126   SmallVector<SDValue, 4> Chains;
6127 
6128   SDValue BasePtr = LN0->getBasePtr();
6129   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6130     const unsigned Offset = Idx * Stride;
6131     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6132 
6133     SDValue SplitLoad = DAG.getExtLoad(
6134         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6135         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6136         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6137 
6138     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6139                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6140 
6141     Loads.push_back(SplitLoad.getValue(0));
6142     Chains.push_back(SplitLoad.getValue(1));
6143   }
6144 
6145   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6146   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6147 
6148   CombineTo(N, NewValue);
6149 
6150   // Replace uses of the original load (before extension)
6151   // with a truncate of the concatenated sextloaded vectors.
6152   SDValue Trunc =
6153       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6154   CombineTo(N0.getNode(), Trunc, NewChain);
6155   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6156                   (ISD::NodeType)N->getOpcode());
6157   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6158 }
6159 
6160 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6161   SDValue N0 = N->getOperand(0);
6162   EVT VT = N->getValueType(0);
6163 
6164   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6165                                               LegalOperations))
6166     return SDValue(Res, 0);
6167 
6168   // fold (sext (sext x)) -> (sext x)
6169   // fold (sext (aext x)) -> (sext x)
6170   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6171     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6172                        N0.getOperand(0));
6173 
6174   if (N0.getOpcode() == ISD::TRUNCATE) {
6175     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6176     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6177     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6178       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6179       if (NarrowLoad.getNode() != N0.getNode()) {
6180         CombineTo(N0.getNode(), NarrowLoad);
6181         // CombineTo deleted the truncate, if needed, but not what's under it.
6182         AddToWorklist(oye);
6183       }
6184       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6185     }
6186 
6187     // See if the value being truncated is already sign extended.  If so, just
6188     // eliminate the trunc/sext pair.
6189     SDValue Op = N0.getOperand(0);
6190     unsigned OpBits   = Op.getScalarValueSizeInBits();
6191     unsigned MidBits  = N0.getScalarValueSizeInBits();
6192     unsigned DestBits = VT.getScalarSizeInBits();
6193     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6194 
6195     if (OpBits == DestBits) {
6196       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6197       // bits, it is already ready.
6198       if (NumSignBits > DestBits-MidBits)
6199         return Op;
6200     } else if (OpBits < DestBits) {
6201       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6202       // bits, just sext from i32.
6203       if (NumSignBits > OpBits-MidBits)
6204         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6205     } else {
6206       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6207       // bits, just truncate to i32.
6208       if (NumSignBits > OpBits-MidBits)
6209         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6210     }
6211 
6212     // fold (sext (truncate x)) -> (sextinreg x).
6213     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6214                                                  N0.getValueType())) {
6215       if (OpBits < DestBits)
6216         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6217       else if (OpBits > DestBits)
6218         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6219       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6220                          DAG.getValueType(N0.getValueType()));
6221     }
6222   }
6223 
6224   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6225   // Only generate vector extloads when 1) they're legal, and 2) they are
6226   // deemed desirable by the target.
6227   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6228       ((!LegalOperations && !VT.isVector() &&
6229         !cast<LoadSDNode>(N0)->isVolatile()) ||
6230        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6231     bool DoXform = true;
6232     SmallVector<SDNode*, 4> SetCCs;
6233     if (!N0.hasOneUse())
6234       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6235     if (VT.isVector())
6236       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6237     if (DoXform) {
6238       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6239       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6240                                        LN0->getChain(),
6241                                        LN0->getBasePtr(), N0.getValueType(),
6242                                        LN0->getMemOperand());
6243       CombineTo(N, ExtLoad);
6244       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6245                                   N0.getValueType(), ExtLoad);
6246       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6247       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6248                       ISD::SIGN_EXTEND);
6249       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6250     }
6251   }
6252 
6253   // fold (sext (load x)) to multiple smaller sextloads.
6254   // Only on illegal but splittable vectors.
6255   if (SDValue ExtLoad = CombineExtLoad(N))
6256     return ExtLoad;
6257 
6258   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6259   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6260   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6261       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6262     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6263     EVT MemVT = LN0->getMemoryVT();
6264     if ((!LegalOperations && !LN0->isVolatile()) ||
6265         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6266       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6267                                        LN0->getChain(),
6268                                        LN0->getBasePtr(), MemVT,
6269                                        LN0->getMemOperand());
6270       CombineTo(N, ExtLoad);
6271       CombineTo(N0.getNode(),
6272                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6273                             N0.getValueType(), ExtLoad),
6274                 ExtLoad.getValue(1));
6275       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6276     }
6277   }
6278 
6279   // fold (sext (and/or/xor (load x), cst)) ->
6280   //      (and/or/xor (sextload x), (sext cst))
6281   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6282        N0.getOpcode() == ISD::XOR) &&
6283       isa<LoadSDNode>(N0.getOperand(0)) &&
6284       N0.getOperand(1).getOpcode() == ISD::Constant &&
6285       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6286       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6287     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6288     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6289       bool DoXform = true;
6290       SmallVector<SDNode*, 4> SetCCs;
6291       if (!N0.hasOneUse())
6292         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6293                                           SetCCs, TLI);
6294       if (DoXform) {
6295         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6296                                          LN0->getChain(), LN0->getBasePtr(),
6297                                          LN0->getMemoryVT(),
6298                                          LN0->getMemOperand());
6299         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6300         Mask = Mask.sext(VT.getSizeInBits());
6301         SDLoc DL(N);
6302         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6303                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6304         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6305                                     SDLoc(N0.getOperand(0)),
6306                                     N0.getOperand(0).getValueType(), ExtLoad);
6307         CombineTo(N, And);
6308         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6309         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6310                         ISD::SIGN_EXTEND);
6311         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6312       }
6313     }
6314   }
6315 
6316   if (N0.getOpcode() == ISD::SETCC) {
6317     EVT N0VT = N0.getOperand(0).getValueType();
6318     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6319     // Only do this before legalize for now.
6320     if (VT.isVector() && !LegalOperations &&
6321         TLI.getBooleanContents(N0VT) ==
6322             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6323       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6324       // of the same size as the compared operands. Only optimize sext(setcc())
6325       // if this is the case.
6326       EVT SVT = getSetCCResultType(N0VT);
6327 
6328       // We know that the # elements of the results is the same as the
6329       // # elements of the compare (and the # elements of the compare result
6330       // for that matter).  Check to see that they are the same size.  If so,
6331       // we know that the element size of the sext'd result matches the
6332       // element size of the compare operands.
6333       if (VT.getSizeInBits() == SVT.getSizeInBits())
6334         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6335                              N0.getOperand(1),
6336                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6337 
6338       // If the desired elements are smaller or larger than the source
6339       // elements we can use a matching integer vector type and then
6340       // truncate/sign extend
6341       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6342       if (SVT == MatchingVectorType) {
6343         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6344                                N0.getOperand(0), N0.getOperand(1),
6345                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6346         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6347       }
6348     }
6349 
6350     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6351     // Here, T can be 1 or -1, depending on the type of the setcc and
6352     // getBooleanContents().
6353     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
6354 
6355     SDLoc DL(N);
6356     // To determine the "true" side of the select, we need to know the high bit
6357     // of the value returned by the setcc if it evaluates to true.
6358     // If the type of the setcc is i1, then the true case of the select is just
6359     // sext(i1 1), that is, -1.
6360     // If the type of the setcc is larger (say, i8) then the value of the high
6361     // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6362     // of the appropriate width.
6363     SDValue ExtTrueVal =
6364         (SetCCWidth == 1)
6365             ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6366                               DL, VT)
6367             : TLI.getConstTrueVal(DAG, VT, DL);
6368 
6369     if (SDValue SCC = SimplifySelectCC(
6370             DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6371             DAG.getConstant(0, DL, VT),
6372             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6373       return SCC;
6374 
6375     if (!VT.isVector()) {
6376       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6377       if (!LegalOperations ||
6378           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6379         SDLoc DL(N);
6380         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6381         SDValue SetCC =
6382             DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6383         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6384                              DAG.getConstant(0, DL, VT));
6385       }
6386     }
6387   }
6388 
6389   // fold (sext x) -> (zext x) if the sign bit is known zero.
6390   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6391       DAG.SignBitIsZero(N0))
6392     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6393 
6394   return SDValue();
6395 }
6396 
6397 // isTruncateOf - If N is a truncate of some other value, return true, record
6398 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6399 // This function computes KnownZero to avoid a duplicated call to
6400 // computeKnownBits in the caller.
6401 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6402                          APInt &KnownZero) {
6403   APInt KnownOne;
6404   if (N->getOpcode() == ISD::TRUNCATE) {
6405     Op = N->getOperand(0);
6406     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6407     return true;
6408   }
6409 
6410   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6411       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6412     return false;
6413 
6414   SDValue Op0 = N->getOperand(0);
6415   SDValue Op1 = N->getOperand(1);
6416   assert(Op0.getValueType() == Op1.getValueType());
6417 
6418   if (isNullConstant(Op0))
6419     Op = Op1;
6420   else if (isNullConstant(Op1))
6421     Op = Op0;
6422   else
6423     return false;
6424 
6425   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6426 
6427   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6428     return false;
6429 
6430   return true;
6431 }
6432 
6433 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6434   SDValue N0 = N->getOperand(0);
6435   EVT VT = N->getValueType(0);
6436 
6437   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6438                                               LegalOperations))
6439     return SDValue(Res, 0);
6440 
6441   // fold (zext (zext x)) -> (zext x)
6442   // fold (zext (aext x)) -> (zext x)
6443   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6444     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6445                        N0.getOperand(0));
6446 
6447   // fold (zext (truncate x)) -> (zext x) or
6448   //      (zext (truncate x)) -> (truncate x)
6449   // This is valid when the truncated bits of x are already zero.
6450   // FIXME: We should extend this to work for vectors too.
6451   SDValue Op;
6452   APInt KnownZero;
6453   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6454     APInt TruncatedBits =
6455       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6456       APInt(Op.getValueSizeInBits(), 0) :
6457       APInt::getBitsSet(Op.getValueSizeInBits(),
6458                         N0.getValueSizeInBits(),
6459                         std::min(Op.getValueSizeInBits(),
6460                                  VT.getSizeInBits()));
6461     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6462       if (VT.bitsGT(Op.getValueType()))
6463         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6464       if (VT.bitsLT(Op.getValueType()))
6465         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6466 
6467       return Op;
6468     }
6469   }
6470 
6471   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6472   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6473   if (N0.getOpcode() == ISD::TRUNCATE) {
6474     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6475       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6476       if (NarrowLoad.getNode() != N0.getNode()) {
6477         CombineTo(N0.getNode(), NarrowLoad);
6478         // CombineTo deleted the truncate, if needed, but not what's under it.
6479         AddToWorklist(oye);
6480       }
6481       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6482     }
6483   }
6484 
6485   // fold (zext (truncate x)) -> (and x, mask)
6486   if (N0.getOpcode() == ISD::TRUNCATE) {
6487     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6488     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6489     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6490       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6491       if (NarrowLoad.getNode() != N0.getNode()) {
6492         CombineTo(N0.getNode(), NarrowLoad);
6493         // CombineTo deleted the truncate, if needed, but not what's under it.
6494         AddToWorklist(oye);
6495       }
6496       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6497     }
6498 
6499     EVT SrcVT = N0.getOperand(0).getValueType();
6500     EVT MinVT = N0.getValueType();
6501 
6502     // Try to mask before the extension to avoid having to generate a larger mask,
6503     // possibly over several sub-vectors.
6504     if (SrcVT.bitsLT(VT)) {
6505       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6506                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6507         SDValue Op = N0.getOperand(0);
6508         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6509         AddToWorklist(Op.getNode());
6510         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6511       }
6512     }
6513 
6514     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6515       SDValue Op = N0.getOperand(0);
6516       if (SrcVT.bitsLT(VT)) {
6517         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6518         AddToWorklist(Op.getNode());
6519       } else if (SrcVT.bitsGT(VT)) {
6520         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6521         AddToWorklist(Op.getNode());
6522       }
6523       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6524     }
6525   }
6526 
6527   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6528   // if either of the casts is not free.
6529   if (N0.getOpcode() == ISD::AND &&
6530       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6531       N0.getOperand(1).getOpcode() == ISD::Constant &&
6532       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6533                            N0.getValueType()) ||
6534        !TLI.isZExtFree(N0.getValueType(), VT))) {
6535     SDValue X = N0.getOperand(0).getOperand(0);
6536     if (X.getValueType().bitsLT(VT)) {
6537       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6538     } else if (X.getValueType().bitsGT(VT)) {
6539       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6540     }
6541     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6542     Mask = Mask.zext(VT.getSizeInBits());
6543     SDLoc DL(N);
6544     return DAG.getNode(ISD::AND, DL, VT,
6545                        X, DAG.getConstant(Mask, DL, VT));
6546   }
6547 
6548   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6549   // Only generate vector extloads when 1) they're legal, and 2) they are
6550   // deemed desirable by the target.
6551   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6552       ((!LegalOperations && !VT.isVector() &&
6553         !cast<LoadSDNode>(N0)->isVolatile()) ||
6554        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6555     bool DoXform = true;
6556     SmallVector<SDNode*, 4> SetCCs;
6557     if (!N0.hasOneUse())
6558       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6559     if (VT.isVector())
6560       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6561     if (DoXform) {
6562       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6563       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6564                                        LN0->getChain(),
6565                                        LN0->getBasePtr(), N0.getValueType(),
6566                                        LN0->getMemOperand());
6567       CombineTo(N, ExtLoad);
6568       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6569                                   N0.getValueType(), ExtLoad);
6570       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6571 
6572       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6573                       ISD::ZERO_EXTEND);
6574       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6575     }
6576   }
6577 
6578   // fold (zext (load x)) to multiple smaller zextloads.
6579   // Only on illegal but splittable vectors.
6580   if (SDValue ExtLoad = CombineExtLoad(N))
6581     return ExtLoad;
6582 
6583   // fold (zext (and/or/xor (load x), cst)) ->
6584   //      (and/or/xor (zextload x), (zext cst))
6585   // Unless (and (load x) cst) will match as a zextload already and has
6586   // additional users.
6587   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6588        N0.getOpcode() == ISD::XOR) &&
6589       isa<LoadSDNode>(N0.getOperand(0)) &&
6590       N0.getOperand(1).getOpcode() == ISD::Constant &&
6591       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6592       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6593     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6594     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6595       bool DoXform = true;
6596       SmallVector<SDNode*, 4> SetCCs;
6597       if (!N0.hasOneUse()) {
6598         if (N0.getOpcode() == ISD::AND) {
6599           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6600           auto NarrowLoad = false;
6601           EVT LoadResultTy = AndC->getValueType(0);
6602           EVT ExtVT, LoadedVT;
6603           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6604                                NarrowLoad))
6605             DoXform = false;
6606         }
6607         if (DoXform)
6608           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6609                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6610       }
6611       if (DoXform) {
6612         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6613                                          LN0->getChain(), LN0->getBasePtr(),
6614                                          LN0->getMemoryVT(),
6615                                          LN0->getMemOperand());
6616         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6617         Mask = Mask.zext(VT.getSizeInBits());
6618         SDLoc DL(N);
6619         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6620                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6621         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6622                                     SDLoc(N0.getOperand(0)),
6623                                     N0.getOperand(0).getValueType(), ExtLoad);
6624         CombineTo(N, And);
6625         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6626         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6627                         ISD::ZERO_EXTEND);
6628         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6629       }
6630     }
6631   }
6632 
6633   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6634   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6635   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6636       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6637     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6638     EVT MemVT = LN0->getMemoryVT();
6639     if ((!LegalOperations && !LN0->isVolatile()) ||
6640         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6641       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6642                                        LN0->getChain(),
6643                                        LN0->getBasePtr(), MemVT,
6644                                        LN0->getMemOperand());
6645       CombineTo(N, ExtLoad);
6646       CombineTo(N0.getNode(),
6647                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6648                             ExtLoad),
6649                 ExtLoad.getValue(1));
6650       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6651     }
6652   }
6653 
6654   if (N0.getOpcode() == ISD::SETCC) {
6655     // Only do this before legalize for now.
6656     if (!LegalOperations && VT.isVector() &&
6657         N0.getValueType().getVectorElementType() == MVT::i1) {
6658       EVT N00VT = N0.getOperand(0).getValueType();
6659       if (getSetCCResultType(N00VT) == N0.getValueType())
6660         return SDValue();
6661 
6662       // We know that the # elements of the results is the same as the #
6663       // elements of the compare (and the # elements of the compare result for
6664       // that matter). Check to see that they are the same size. If so, we know
6665       // that the element size of the sext'd result matches the element size of
6666       // the compare operands.
6667       SDLoc DL(N);
6668       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6669       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
6670         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6671         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
6672                                      N0.getOperand(1), N0.getOperand(2));
6673         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
6674       }
6675 
6676       // If the desired elements are smaller or larger than the source
6677       // elements we can use a matching integer vector type and then
6678       // truncate/sign extend.
6679       EVT MatchingElementType = EVT::getIntegerVT(
6680           *DAG.getContext(), N00VT.getScalarSizeInBits());
6681       EVT MatchingVectorType = EVT::getVectorVT(
6682           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
6683       SDValue VsetCC =
6684           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
6685                       N0.getOperand(1), N0.getOperand(2));
6686       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
6687                          VecOnes);
6688     }
6689 
6690     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6691     SDLoc DL(N);
6692     if (SDValue SCC = SimplifySelectCC(
6693             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6694             DAG.getConstant(0, DL, VT),
6695             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6696       return SCC;
6697   }
6698 
6699   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6700   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6701       isa<ConstantSDNode>(N0.getOperand(1)) &&
6702       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6703       N0.hasOneUse()) {
6704     SDValue ShAmt = N0.getOperand(1);
6705     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6706     if (N0.getOpcode() == ISD::SHL) {
6707       SDValue InnerZExt = N0.getOperand(0);
6708       // If the original shl may be shifting out bits, do not perform this
6709       // transformation.
6710       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
6711         InnerZExt.getOperand(0).getValueSizeInBits();
6712       if (ShAmtVal > KnownZeroBits)
6713         return SDValue();
6714     }
6715 
6716     SDLoc DL(N);
6717 
6718     // Ensure that the shift amount is wide enough for the shifted value.
6719     if (VT.getSizeInBits() >= 256)
6720       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6721 
6722     return DAG.getNode(N0.getOpcode(), DL, VT,
6723                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6724                        ShAmt);
6725   }
6726 
6727   return SDValue();
6728 }
6729 
6730 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6731   SDValue N0 = N->getOperand(0);
6732   EVT VT = N->getValueType(0);
6733 
6734   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6735                                               LegalOperations))
6736     return SDValue(Res, 0);
6737 
6738   // fold (aext (aext x)) -> (aext x)
6739   // fold (aext (zext x)) -> (zext x)
6740   // fold (aext (sext x)) -> (sext x)
6741   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6742       N0.getOpcode() == ISD::ZERO_EXTEND ||
6743       N0.getOpcode() == ISD::SIGN_EXTEND)
6744     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6745 
6746   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6747   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6748   if (N0.getOpcode() == ISD::TRUNCATE) {
6749     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6750       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6751       if (NarrowLoad.getNode() != N0.getNode()) {
6752         CombineTo(N0.getNode(), NarrowLoad);
6753         // CombineTo deleted the truncate, if needed, but not what's under it.
6754         AddToWorklist(oye);
6755       }
6756       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6757     }
6758   }
6759 
6760   // fold (aext (truncate x))
6761   if (N0.getOpcode() == ISD::TRUNCATE) {
6762     SDValue TruncOp = N0.getOperand(0);
6763     if (TruncOp.getValueType() == VT)
6764       return TruncOp; // x iff x size == zext size.
6765     if (TruncOp.getValueType().bitsGT(VT))
6766       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6767     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6768   }
6769 
6770   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6771   // if the trunc is not free.
6772   if (N0.getOpcode() == ISD::AND &&
6773       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6774       N0.getOperand(1).getOpcode() == ISD::Constant &&
6775       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6776                           N0.getValueType())) {
6777     SDLoc DL(N);
6778     SDValue X = N0.getOperand(0).getOperand(0);
6779     if (X.getValueType().bitsLT(VT)) {
6780       X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
6781     } else if (X.getValueType().bitsGT(VT)) {
6782       X = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
6783     }
6784     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6785     Mask = Mask.zext(VT.getSizeInBits());
6786     return DAG.getNode(ISD::AND, DL, VT,
6787                        X, DAG.getConstant(Mask, DL, VT));
6788   }
6789 
6790   // fold (aext (load x)) -> (aext (truncate (extload x)))
6791   // None of the supported targets knows how to perform load and any_ext
6792   // on vectors in one instruction.  We only perform this transformation on
6793   // scalars.
6794   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6795       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6796       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6797     bool DoXform = true;
6798     SmallVector<SDNode*, 4> SetCCs;
6799     if (!N0.hasOneUse())
6800       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6801     if (DoXform) {
6802       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6803       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6804                                        LN0->getChain(),
6805                                        LN0->getBasePtr(), N0.getValueType(),
6806                                        LN0->getMemOperand());
6807       CombineTo(N, ExtLoad);
6808       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6809                                   N0.getValueType(), ExtLoad);
6810       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6811       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6812                       ISD::ANY_EXTEND);
6813       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6814     }
6815   }
6816 
6817   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6818   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6819   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6820   if (N0.getOpcode() == ISD::LOAD &&
6821       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6822       N0.hasOneUse()) {
6823     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6824     ISD::LoadExtType ExtType = LN0->getExtensionType();
6825     EVT MemVT = LN0->getMemoryVT();
6826     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6827       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6828                                        VT, LN0->getChain(), LN0->getBasePtr(),
6829                                        MemVT, LN0->getMemOperand());
6830       CombineTo(N, ExtLoad);
6831       CombineTo(N0.getNode(),
6832                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6833                             N0.getValueType(), ExtLoad),
6834                 ExtLoad.getValue(1));
6835       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6836     }
6837   }
6838 
6839   if (N0.getOpcode() == ISD::SETCC) {
6840     // For vectors:
6841     // aext(setcc) -> vsetcc
6842     // aext(setcc) -> truncate(vsetcc)
6843     // aext(setcc) -> aext(vsetcc)
6844     // Only do this before legalize for now.
6845     if (VT.isVector() && !LegalOperations) {
6846       EVT N0VT = N0.getOperand(0).getValueType();
6847         // We know that the # elements of the results is the same as the
6848         // # elements of the compare (and the # elements of the compare result
6849         // for that matter).  Check to see that they are the same size.  If so,
6850         // we know that the element size of the sext'd result matches the
6851         // element size of the compare operands.
6852       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6853         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6854                              N0.getOperand(1),
6855                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6856       // If the desired elements are smaller or larger than the source
6857       // elements we can use a matching integer vector type and then
6858       // truncate/any extend
6859       else {
6860         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6861         SDValue VsetCC =
6862           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6863                         N0.getOperand(1),
6864                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6865         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6866       }
6867     }
6868 
6869     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6870     SDLoc DL(N);
6871     if (SDValue SCC = SimplifySelectCC(
6872             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6873             DAG.getConstant(0, DL, VT),
6874             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6875       return SCC;
6876   }
6877 
6878   return SDValue();
6879 }
6880 
6881 /// See if the specified operand can be simplified with the knowledge that only
6882 /// the bits specified by Mask are used.  If so, return the simpler operand,
6883 /// otherwise return a null SDValue.
6884 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6885   switch (V.getOpcode()) {
6886   default: break;
6887   case ISD::Constant: {
6888     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6889     assert(CV && "Const value should be ConstSDNode.");
6890     const APInt &CVal = CV->getAPIntValue();
6891     APInt NewVal = CVal & Mask;
6892     if (NewVal != CVal)
6893       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6894     break;
6895   }
6896   case ISD::OR:
6897   case ISD::XOR:
6898     // If the LHS or RHS don't contribute bits to the or, drop them.
6899     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6900       return V.getOperand(1);
6901     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6902       return V.getOperand(0);
6903     break;
6904   case ISD::SRL:
6905     // Only look at single-use SRLs.
6906     if (!V.getNode()->hasOneUse())
6907       break;
6908     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6909       // See if we can recursively simplify the LHS.
6910       unsigned Amt = RHSC->getZExtValue();
6911 
6912       // Watch out for shift count overflow though.
6913       if (Amt >= Mask.getBitWidth()) break;
6914       APInt NewMask = Mask << Amt;
6915       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6916         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6917                            SimplifyLHS, V.getOperand(1));
6918     }
6919   }
6920   return SDValue();
6921 }
6922 
6923 /// If the result of a wider load is shifted to right of N  bits and then
6924 /// truncated to a narrower type and where N is a multiple of number of bits of
6925 /// the narrower type, transform it to a narrower load from address + N / num of
6926 /// bits of new type. If the result is to be extended, also fold the extension
6927 /// to form a extending load.
6928 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6929   unsigned Opc = N->getOpcode();
6930 
6931   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6932   SDValue N0 = N->getOperand(0);
6933   EVT VT = N->getValueType(0);
6934   EVT ExtVT = VT;
6935 
6936   // This transformation isn't valid for vector loads.
6937   if (VT.isVector())
6938     return SDValue();
6939 
6940   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6941   // extended to VT.
6942   if (Opc == ISD::SIGN_EXTEND_INREG) {
6943     ExtType = ISD::SEXTLOAD;
6944     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6945   } else if (Opc == ISD::SRL) {
6946     // Another special-case: SRL is basically zero-extending a narrower value.
6947     ExtType = ISD::ZEXTLOAD;
6948     N0 = SDValue(N, 0);
6949     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6950     if (!N01) return SDValue();
6951     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6952                               VT.getSizeInBits() - N01->getZExtValue());
6953   }
6954   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6955     return SDValue();
6956 
6957   unsigned EVTBits = ExtVT.getSizeInBits();
6958 
6959   // Do not generate loads of non-round integer types since these can
6960   // be expensive (and would be wrong if the type is not byte sized).
6961   if (!ExtVT.isRound())
6962     return SDValue();
6963 
6964   unsigned ShAmt = 0;
6965   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6966     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6967       ShAmt = N01->getZExtValue();
6968       // Is the shift amount a multiple of size of VT?
6969       if ((ShAmt & (EVTBits-1)) == 0) {
6970         N0 = N0.getOperand(0);
6971         // Is the load width a multiple of size of VT?
6972         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
6973           return SDValue();
6974       }
6975 
6976       // At this point, we must have a load or else we can't do the transform.
6977       if (!isa<LoadSDNode>(N0)) return SDValue();
6978 
6979       // Because a SRL must be assumed to *need* to zero-extend the high bits
6980       // (as opposed to anyext the high bits), we can't combine the zextload
6981       // lowering of SRL and an sextload.
6982       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6983         return SDValue();
6984 
6985       // If the shift amount is larger than the input type then we're not
6986       // accessing any of the loaded bytes.  If the load was a zextload/extload
6987       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6988       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6989         return SDValue();
6990     }
6991   }
6992 
6993   // If the load is shifted left (and the result isn't shifted back right),
6994   // we can fold the truncate through the shift.
6995   unsigned ShLeftAmt = 0;
6996   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6997       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6998     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6999       ShLeftAmt = N01->getZExtValue();
7000       N0 = N0.getOperand(0);
7001     }
7002   }
7003 
7004   // If we haven't found a load, we can't narrow it.  Don't transform one with
7005   // multiple uses, this would require adding a new load.
7006   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7007     return SDValue();
7008 
7009   // Don't change the width of a volatile load.
7010   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7011   if (LN0->isVolatile())
7012     return SDValue();
7013 
7014   // Verify that we are actually reducing a load width here.
7015   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7016     return SDValue();
7017 
7018   // For the transform to be legal, the load must produce only two values
7019   // (the value loaded and the chain).  Don't transform a pre-increment
7020   // load, for example, which produces an extra value.  Otherwise the
7021   // transformation is not equivalent, and the downstream logic to replace
7022   // uses gets things wrong.
7023   if (LN0->getNumValues() > 2)
7024     return SDValue();
7025 
7026   // If the load that we're shrinking is an extload and we're not just
7027   // discarding the extension we can't simply shrink the load. Bail.
7028   // TODO: It would be possible to merge the extensions in some cases.
7029   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7030       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7031     return SDValue();
7032 
7033   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7034     return SDValue();
7035 
7036   EVT PtrType = N0.getOperand(1).getValueType();
7037 
7038   if (PtrType == MVT::Untyped || PtrType.isExtended())
7039     // It's not possible to generate a constant of extended or untyped type.
7040     return SDValue();
7041 
7042   // For big endian targets, we need to adjust the offset to the pointer to
7043   // load the correct bytes.
7044   if (DAG.getDataLayout().isBigEndian()) {
7045     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7046     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7047     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7048   }
7049 
7050   uint64_t PtrOff = ShAmt / 8;
7051   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7052   SDLoc DL(LN0);
7053   // The original load itself didn't wrap, so an offset within it doesn't.
7054   SDNodeFlags Flags;
7055   Flags.setNoUnsignedWrap(true);
7056   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7057                                PtrType, LN0->getBasePtr(),
7058                                DAG.getConstant(PtrOff, DL, PtrType),
7059                                &Flags);
7060   AddToWorklist(NewPtr.getNode());
7061 
7062   SDValue Load;
7063   if (ExtType == ISD::NON_EXTLOAD)
7064     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7065                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7066                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7067   else
7068     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7069                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7070                           NewAlign, LN0->getMemOperand()->getFlags(),
7071                           LN0->getAAInfo());
7072 
7073   // Replace the old load's chain with the new load's chain.
7074   WorklistRemover DeadNodes(*this);
7075   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7076 
7077   // Shift the result left, if we've swallowed a left shift.
7078   SDValue Result = Load;
7079   if (ShLeftAmt != 0) {
7080     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7081     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7082       ShImmTy = VT;
7083     // If the shift amount is as large as the result size (but, presumably,
7084     // no larger than the source) then the useful bits of the result are
7085     // zero; we can't simply return the shortened shift, because the result
7086     // of that operation is undefined.
7087     SDLoc DL(N0);
7088     if (ShLeftAmt >= VT.getSizeInBits())
7089       Result = DAG.getConstant(0, DL, VT);
7090     else
7091       Result = DAG.getNode(ISD::SHL, DL, VT,
7092                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7093   }
7094 
7095   // Return the new loaded value.
7096   return Result;
7097 }
7098 
7099 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7100   SDValue N0 = N->getOperand(0);
7101   SDValue N1 = N->getOperand(1);
7102   EVT VT = N->getValueType(0);
7103   EVT EVT = cast<VTSDNode>(N1)->getVT();
7104   unsigned VTBits = VT.getScalarSizeInBits();
7105   unsigned EVTBits = EVT.getScalarSizeInBits();
7106 
7107   if (N0.isUndef())
7108     return DAG.getUNDEF(VT);
7109 
7110   // fold (sext_in_reg c1) -> c1
7111   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7112     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7113 
7114   // If the input is already sign extended, just drop the extension.
7115   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7116     return N0;
7117 
7118   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7119   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7120       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7121     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7122                        N0.getOperand(0), N1);
7123 
7124   // fold (sext_in_reg (sext x)) -> (sext x)
7125   // fold (sext_in_reg (aext x)) -> (sext x)
7126   // if x is small enough.
7127   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7128     SDValue N00 = N0.getOperand(0);
7129     if (N00.getScalarValueSizeInBits() <= EVTBits &&
7130         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7131       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7132   }
7133 
7134   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7135   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7136     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7137 
7138   // fold operands of sext_in_reg based on knowledge that the top bits are not
7139   // demanded.
7140   if (SimplifyDemandedBits(SDValue(N, 0)))
7141     return SDValue(N, 0);
7142 
7143   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7144   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7145   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7146     return NarrowLoad;
7147 
7148   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7149   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7150   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7151   if (N0.getOpcode() == ISD::SRL) {
7152     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7153       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7154         // We can turn this into an SRA iff the input to the SRL is already sign
7155         // extended enough.
7156         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7157         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7158           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7159                              N0.getOperand(0), N0.getOperand(1));
7160       }
7161   }
7162 
7163   // fold (sext_inreg (extload x)) -> (sextload x)
7164   if (ISD::isEXTLoad(N0.getNode()) &&
7165       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7166       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7167       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7168        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7169     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7170     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7171                                      LN0->getChain(),
7172                                      LN0->getBasePtr(), EVT,
7173                                      LN0->getMemOperand());
7174     CombineTo(N, ExtLoad);
7175     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7176     AddToWorklist(ExtLoad.getNode());
7177     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7178   }
7179   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7180   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7181       N0.hasOneUse() &&
7182       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7183       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7184        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7185     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7186     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7187                                      LN0->getChain(),
7188                                      LN0->getBasePtr(), EVT,
7189                                      LN0->getMemOperand());
7190     CombineTo(N, ExtLoad);
7191     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7192     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7193   }
7194 
7195   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7196   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7197     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7198                                            N0.getOperand(1), false))
7199       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7200                          BSwap, N1);
7201   }
7202 
7203   return SDValue();
7204 }
7205 
7206 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7207   SDValue N0 = N->getOperand(0);
7208   EVT VT = N->getValueType(0);
7209 
7210   if (N0.isUndef())
7211     return DAG.getUNDEF(VT);
7212 
7213   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7214                                               LegalOperations))
7215     return SDValue(Res, 0);
7216 
7217   return SDValue();
7218 }
7219 
7220 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7221   SDValue N0 = N->getOperand(0);
7222   EVT VT = N->getValueType(0);
7223 
7224   if (N0.isUndef())
7225     return DAG.getUNDEF(VT);
7226 
7227   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7228                                               LegalOperations))
7229     return SDValue(Res, 0);
7230 
7231   return SDValue();
7232 }
7233 
7234 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7235   SDValue N0 = N->getOperand(0);
7236   EVT VT = N->getValueType(0);
7237   bool isLE = DAG.getDataLayout().isLittleEndian();
7238 
7239   // noop truncate
7240   if (N0.getValueType() == N->getValueType(0))
7241     return N0;
7242   // fold (truncate c1) -> c1
7243   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7244     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7245   // fold (truncate (truncate x)) -> (truncate x)
7246   if (N0.getOpcode() == ISD::TRUNCATE)
7247     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7248   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7249   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7250       N0.getOpcode() == ISD::SIGN_EXTEND ||
7251       N0.getOpcode() == ISD::ANY_EXTEND) {
7252     // if the source is smaller than the dest, we still need an extend.
7253     if (N0.getOperand(0).getValueType().bitsLT(VT))
7254       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7255     // if the source is larger than the dest, than we just need the truncate.
7256     if (N0.getOperand(0).getValueType().bitsGT(VT))
7257       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7258     // if the source and dest are the same type, we can drop both the extend
7259     // and the truncate.
7260     return N0.getOperand(0);
7261   }
7262 
7263   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
7264   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
7265     return SDValue();
7266 
7267   // Fold extract-and-trunc into a narrow extract. For example:
7268   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7269   //   i32 y = TRUNCATE(i64 x)
7270   //        -- becomes --
7271   //   v16i8 b = BITCAST (v2i64 val)
7272   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7273   //
7274   // Note: We only run this optimization after type legalization (which often
7275   // creates this pattern) and before operation legalization after which
7276   // we need to be more careful about the vector instructions that we generate.
7277   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7278       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7279 
7280     EVT VecTy = N0.getOperand(0).getValueType();
7281     EVT ExTy = N0.getValueType();
7282     EVT TrTy = N->getValueType(0);
7283 
7284     unsigned NumElem = VecTy.getVectorNumElements();
7285     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7286 
7287     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7288     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7289 
7290     SDValue EltNo = N0->getOperand(1);
7291     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7292       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7293       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7294       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7295 
7296       SDLoc DL(N);
7297       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7298                          DAG.getBitcast(NVT, N0.getOperand(0)),
7299                          DAG.getConstant(Index, DL, IndexTy));
7300     }
7301   }
7302 
7303   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7304   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
7305     EVT SrcVT = N0.getValueType();
7306     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7307         TLI.isTruncateFree(SrcVT, VT)) {
7308       SDLoc SL(N0);
7309       SDValue Cond = N0.getOperand(0);
7310       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7311       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7312       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7313     }
7314   }
7315 
7316   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
7317   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7318       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7319       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7320     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7321       uint64_t Amt = CAmt->getZExtValue();
7322       unsigned Size = VT.getScalarSizeInBits();
7323 
7324       if (Amt < Size) {
7325         SDLoc SL(N);
7326         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7327 
7328         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7329         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7330                            DAG.getConstant(Amt, SL, AmtVT));
7331       }
7332     }
7333   }
7334 
7335   // Fold a series of buildvector, bitcast, and truncate if possible.
7336   // For example fold
7337   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7338   //   (2xi32 (buildvector x, y)).
7339   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7340       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7341       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7342       N0.getOperand(0).hasOneUse()) {
7343 
7344     SDValue BuildVect = N0.getOperand(0);
7345     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7346     EVT TruncVecEltTy = VT.getVectorElementType();
7347 
7348     // Check that the element types match.
7349     if (BuildVectEltTy == TruncVecEltTy) {
7350       // Now we only need to compute the offset of the truncated elements.
7351       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7352       unsigned TruncVecNumElts = VT.getVectorNumElements();
7353       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7354 
7355       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7356              "Invalid number of elements");
7357 
7358       SmallVector<SDValue, 8> Opnds;
7359       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7360         Opnds.push_back(BuildVect.getOperand(i));
7361 
7362       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7363     }
7364   }
7365 
7366   // See if we can simplify the input to this truncate through knowledge that
7367   // only the low bits are being used.
7368   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7369   // Currently we only perform this optimization on scalars because vectors
7370   // may have different active low bits.
7371   if (!VT.isVector()) {
7372     if (SDValue Shorter =
7373             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7374                                                      VT.getSizeInBits())))
7375       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7376   }
7377   // fold (truncate (load x)) -> (smaller load x)
7378   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7379   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7380     if (SDValue Reduced = ReduceLoadWidth(N))
7381       return Reduced;
7382 
7383     // Handle the case where the load remains an extending load even
7384     // after truncation.
7385     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7386       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7387       if (!LN0->isVolatile() &&
7388           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7389         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7390                                          VT, LN0->getChain(), LN0->getBasePtr(),
7391                                          LN0->getMemoryVT(),
7392                                          LN0->getMemOperand());
7393         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7394         return NewLoad;
7395       }
7396     }
7397   }
7398   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7399   // where ... are all 'undef'.
7400   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7401     SmallVector<EVT, 8> VTs;
7402     SDValue V;
7403     unsigned Idx = 0;
7404     unsigned NumDefs = 0;
7405 
7406     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7407       SDValue X = N0.getOperand(i);
7408       if (!X.isUndef()) {
7409         V = X;
7410         Idx = i;
7411         NumDefs++;
7412       }
7413       // Stop if more than one members are non-undef.
7414       if (NumDefs > 1)
7415         break;
7416       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7417                                      VT.getVectorElementType(),
7418                                      X.getValueType().getVectorNumElements()));
7419     }
7420 
7421     if (NumDefs == 0)
7422       return DAG.getUNDEF(VT);
7423 
7424     if (NumDefs == 1) {
7425       assert(V.getNode() && "The single defined operand is empty!");
7426       SmallVector<SDValue, 8> Opnds;
7427       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7428         if (i != Idx) {
7429           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7430           continue;
7431         }
7432         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7433         AddToWorklist(NV.getNode());
7434         Opnds.push_back(NV);
7435       }
7436       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7437     }
7438   }
7439 
7440   // Fold truncate of a bitcast of a vector to an extract of the low vector
7441   // element.
7442   //
7443   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7444   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7445     SDValue VecSrc = N0.getOperand(0);
7446     EVT SrcVT = VecSrc.getValueType();
7447     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7448         (!LegalOperations ||
7449          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7450       SDLoc SL(N);
7451 
7452       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7453       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7454                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7455     }
7456   }
7457 
7458   // Simplify the operands using demanded-bits information.
7459   if (!VT.isVector() &&
7460       SimplifyDemandedBits(SDValue(N, 0)))
7461     return SDValue(N, 0);
7462 
7463   return SDValue();
7464 }
7465 
7466 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7467   SDValue Elt = N->getOperand(i);
7468   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7469     return Elt.getNode();
7470   return Elt.getOperand(Elt.getResNo()).getNode();
7471 }
7472 
7473 /// build_pair (load, load) -> load
7474 /// if load locations are consecutive.
7475 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7476   assert(N->getOpcode() == ISD::BUILD_PAIR);
7477 
7478   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7479   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7480   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7481       LD1->getAddressSpace() != LD2->getAddressSpace())
7482     return SDValue();
7483   EVT LD1VT = LD1->getValueType(0);
7484   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7485   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7486       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7487     unsigned Align = LD1->getAlignment();
7488     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7489         VT.getTypeForEVT(*DAG.getContext()));
7490 
7491     if (NewAlign <= Align &&
7492         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7493       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
7494                          LD1->getPointerInfo(), Align);
7495   }
7496 
7497   return SDValue();
7498 }
7499 
7500 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7501   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7502   // and Lo parts; on big-endian machines it doesn't.
7503   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7504 }
7505 
7506 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7507                                     const TargetLowering &TLI) {
7508   // If this is not a bitcast to an FP type or if the target doesn't have
7509   // IEEE754-compliant FP logic, we're done.
7510   EVT VT = N->getValueType(0);
7511   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7512     return SDValue();
7513 
7514   // TODO: Use splat values for the constant-checking below and remove this
7515   // restriction.
7516   SDValue N0 = N->getOperand(0);
7517   EVT SourceVT = N0.getValueType();
7518   if (SourceVT.isVector())
7519     return SDValue();
7520 
7521   unsigned FPOpcode;
7522   APInt SignMask;
7523   switch (N0.getOpcode()) {
7524   case ISD::AND:
7525     FPOpcode = ISD::FABS;
7526     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7527     break;
7528   case ISD::XOR:
7529     FPOpcode = ISD::FNEG;
7530     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7531     break;
7532   // TODO: ISD::OR --> ISD::FNABS?
7533   default:
7534     return SDValue();
7535   }
7536 
7537   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7538   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7539   SDValue LogicOp0 = N0.getOperand(0);
7540   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7541   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7542       LogicOp0.getOpcode() == ISD::BITCAST &&
7543       LogicOp0->getOperand(0).getValueType() == VT)
7544     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7545 
7546   return SDValue();
7547 }
7548 
7549 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7550   SDValue N0 = N->getOperand(0);
7551   EVT VT = N->getValueType(0);
7552 
7553   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7554   // Only do this before legalize, since afterward the target may be depending
7555   // on the bitconvert.
7556   // First check to see if this is all constant.
7557   if (!LegalTypes &&
7558       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7559       VT.isVector()) {
7560     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7561 
7562     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7563     assert(!DestEltVT.isVector() &&
7564            "Element type of vector ValueType must not be vector!");
7565     if (isSimple)
7566       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7567   }
7568 
7569   // If the input is a constant, let getNode fold it.
7570   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7571     // If we can't allow illegal operations, we need to check that this is just
7572     // a fp -> int or int -> conversion and that the resulting operation will
7573     // be legal.
7574     if (!LegalOperations ||
7575         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7576          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7577         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7578          TLI.isOperationLegal(ISD::Constant, VT)))
7579       return DAG.getBitcast(VT, N0);
7580   }
7581 
7582   // (conv (conv x, t1), t2) -> (conv x, t2)
7583   if (N0.getOpcode() == ISD::BITCAST)
7584     return DAG.getBitcast(VT, N0.getOperand(0));
7585 
7586   // fold (conv (load x)) -> (load (conv*)x)
7587   // If the resultant load doesn't need a higher alignment than the original!
7588   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7589       // Do not change the width of a volatile load.
7590       !cast<LoadSDNode>(N0)->isVolatile() &&
7591       // Do not remove the cast if the types differ in endian layout.
7592       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7593           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7594       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7595       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7596     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7597     unsigned OrigAlign = LN0->getAlignment();
7598 
7599     bool Fast = false;
7600     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7601                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7602         Fast) {
7603       SDValue Load =
7604           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7605                       LN0->getPointerInfo(), OrigAlign,
7606                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7607       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7608       return Load;
7609     }
7610   }
7611 
7612   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7613     return V;
7614 
7615   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7616   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7617   //
7618   // For ppc_fp128:
7619   // fold (bitcast (fneg x)) ->
7620   //     flipbit = signbit
7621   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7622   //
7623   // fold (bitcast (fabs x)) ->
7624   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7625   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7626   // This often reduces constant pool loads.
7627   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7628        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7629       N0.getNode()->hasOneUse() && VT.isInteger() &&
7630       !VT.isVector() && !N0.getValueType().isVector()) {
7631     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7632     AddToWorklist(NewConv.getNode());
7633 
7634     SDLoc DL(N);
7635     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7636       assert(VT.getSizeInBits() == 128);
7637       SDValue SignBit = DAG.getConstant(
7638           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7639       SDValue FlipBit;
7640       if (N0.getOpcode() == ISD::FNEG) {
7641         FlipBit = SignBit;
7642         AddToWorklist(FlipBit.getNode());
7643       } else {
7644         assert(N0.getOpcode() == ISD::FABS);
7645         SDValue Hi =
7646             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7647                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7648                                               SDLoc(NewConv)));
7649         AddToWorklist(Hi.getNode());
7650         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7651         AddToWorklist(FlipBit.getNode());
7652       }
7653       SDValue FlipBits =
7654           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7655       AddToWorklist(FlipBits.getNode());
7656       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7657     }
7658     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7659     if (N0.getOpcode() == ISD::FNEG)
7660       return DAG.getNode(ISD::XOR, DL, VT,
7661                          NewConv, DAG.getConstant(SignBit, DL, VT));
7662     assert(N0.getOpcode() == ISD::FABS);
7663     return DAG.getNode(ISD::AND, DL, VT,
7664                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7665   }
7666 
7667   // fold (bitconvert (fcopysign cst, x)) ->
7668   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7669   // Note that we don't handle (copysign x, cst) because this can always be
7670   // folded to an fneg or fabs.
7671   //
7672   // For ppc_fp128:
7673   // fold (bitcast (fcopysign cst, x)) ->
7674   //     flipbit = (and (extract_element
7675   //                     (xor (bitcast cst), (bitcast x)), 0),
7676   //                    signbit)
7677   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7678   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7679       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7680       VT.isInteger() && !VT.isVector()) {
7681     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
7682     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7683     if (isTypeLegal(IntXVT)) {
7684       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7685       AddToWorklist(X.getNode());
7686 
7687       // If X has a different width than the result/lhs, sext it or truncate it.
7688       unsigned VTWidth = VT.getSizeInBits();
7689       if (OrigXWidth < VTWidth) {
7690         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7691         AddToWorklist(X.getNode());
7692       } else if (OrigXWidth > VTWidth) {
7693         // To get the sign bit in the right place, we have to shift it right
7694         // before truncating.
7695         SDLoc DL(X);
7696         X = DAG.getNode(ISD::SRL, DL,
7697                         X.getValueType(), X,
7698                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7699                                         X.getValueType()));
7700         AddToWorklist(X.getNode());
7701         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7702         AddToWorklist(X.getNode());
7703       }
7704 
7705       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7706         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7707         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7708         AddToWorklist(Cst.getNode());
7709         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7710         AddToWorklist(X.getNode());
7711         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7712         AddToWorklist(XorResult.getNode());
7713         SDValue XorResult64 = DAG.getNode(
7714             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7715             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7716                                   SDLoc(XorResult)));
7717         AddToWorklist(XorResult64.getNode());
7718         SDValue FlipBit =
7719             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7720                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7721         AddToWorklist(FlipBit.getNode());
7722         SDValue FlipBits =
7723             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7724         AddToWorklist(FlipBits.getNode());
7725         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7726       }
7727       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7728       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7729                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7730       AddToWorklist(X.getNode());
7731 
7732       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7733       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7734                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7735       AddToWorklist(Cst.getNode());
7736 
7737       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7738     }
7739   }
7740 
7741   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7742   if (N0.getOpcode() == ISD::BUILD_PAIR)
7743     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7744       return CombineLD;
7745 
7746   // Remove double bitcasts from shuffles - this is often a legacy of
7747   // XformToShuffleWithZero being used to combine bitmaskings (of
7748   // float vectors bitcast to integer vectors) into shuffles.
7749   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7750   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7751       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7752       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7753       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7754     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7755 
7756     // If operands are a bitcast, peek through if it casts the original VT.
7757     // If operands are a constant, just bitcast back to original VT.
7758     auto PeekThroughBitcast = [&](SDValue Op) {
7759       if (Op.getOpcode() == ISD::BITCAST &&
7760           Op.getOperand(0).getValueType() == VT)
7761         return SDValue(Op.getOperand(0));
7762       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7763           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7764         return DAG.getBitcast(VT, Op);
7765       return SDValue();
7766     };
7767 
7768     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7769     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7770     if (!(SV0 && SV1))
7771       return SDValue();
7772 
7773     int MaskScale =
7774         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7775     SmallVector<int, 8> NewMask;
7776     for (int M : SVN->getMask())
7777       for (int i = 0; i != MaskScale; ++i)
7778         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7779 
7780     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7781     if (!LegalMask) {
7782       std::swap(SV0, SV1);
7783       ShuffleVectorSDNode::commuteMask(NewMask);
7784       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7785     }
7786 
7787     if (LegalMask)
7788       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7789   }
7790 
7791   return SDValue();
7792 }
7793 
7794 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7795   EVT VT = N->getValueType(0);
7796   return CombineConsecutiveLoads(N, VT);
7797 }
7798 
7799 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7800 /// operands. DstEltVT indicates the destination element value type.
7801 SDValue DAGCombiner::
7802 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7803   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7804 
7805   // If this is already the right type, we're done.
7806   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7807 
7808   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7809   unsigned DstBitSize = DstEltVT.getSizeInBits();
7810 
7811   // If this is a conversion of N elements of one type to N elements of another
7812   // type, convert each element.  This handles FP<->INT cases.
7813   if (SrcBitSize == DstBitSize) {
7814     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7815                               BV->getValueType(0).getVectorNumElements());
7816 
7817     // Due to the FP element handling below calling this routine recursively,
7818     // we can end up with a scalar-to-vector node here.
7819     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7820       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7821                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7822 
7823     SmallVector<SDValue, 8> Ops;
7824     for (SDValue Op : BV->op_values()) {
7825       // If the vector element type is not legal, the BUILD_VECTOR operands
7826       // are promoted and implicitly truncated.  Make that explicit here.
7827       if (Op.getValueType() != SrcEltVT)
7828         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7829       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7830       AddToWorklist(Ops.back().getNode());
7831     }
7832     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7833   }
7834 
7835   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7836   // handle annoying details of growing/shrinking FP values, we convert them to
7837   // int first.
7838   if (SrcEltVT.isFloatingPoint()) {
7839     // Convert the input float vector to a int vector where the elements are the
7840     // same sizes.
7841     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7842     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7843     SrcEltVT = IntVT;
7844   }
7845 
7846   // Now we know the input is an integer vector.  If the output is a FP type,
7847   // convert to integer first, then to FP of the right size.
7848   if (DstEltVT.isFloatingPoint()) {
7849     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7850     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7851 
7852     // Next, convert to FP elements of the same size.
7853     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7854   }
7855 
7856   SDLoc DL(BV);
7857 
7858   // Okay, we know the src/dst types are both integers of differing types.
7859   // Handling growing first.
7860   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7861   if (SrcBitSize < DstBitSize) {
7862     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7863 
7864     SmallVector<SDValue, 8> Ops;
7865     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7866          i += NumInputsPerOutput) {
7867       bool isLE = DAG.getDataLayout().isLittleEndian();
7868       APInt NewBits = APInt(DstBitSize, 0);
7869       bool EltIsUndef = true;
7870       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7871         // Shift the previously computed bits over.
7872         NewBits <<= SrcBitSize;
7873         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7874         if (Op.isUndef()) continue;
7875         EltIsUndef = false;
7876 
7877         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7878                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7879       }
7880 
7881       if (EltIsUndef)
7882         Ops.push_back(DAG.getUNDEF(DstEltVT));
7883       else
7884         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7885     }
7886 
7887     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7888     return DAG.getBuildVector(VT, DL, Ops);
7889   }
7890 
7891   // Finally, this must be the case where we are shrinking elements: each input
7892   // turns into multiple outputs.
7893   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7894   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7895                             NumOutputsPerInput*BV->getNumOperands());
7896   SmallVector<SDValue, 8> Ops;
7897 
7898   for (const SDValue &Op : BV->op_values()) {
7899     if (Op.isUndef()) {
7900       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7901       continue;
7902     }
7903 
7904     APInt OpVal = cast<ConstantSDNode>(Op)->
7905                   getAPIntValue().zextOrTrunc(SrcBitSize);
7906 
7907     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7908       APInt ThisVal = OpVal.trunc(DstBitSize);
7909       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7910       OpVal = OpVal.lshr(DstBitSize);
7911     }
7912 
7913     // For big endian targets, swap the order of the pieces of each element.
7914     if (DAG.getDataLayout().isBigEndian())
7915       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7916   }
7917 
7918   return DAG.getBuildVector(VT, DL, Ops);
7919 }
7920 
7921 /// Try to perform FMA combining on a given FADD node.
7922 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7923   SDValue N0 = N->getOperand(0);
7924   SDValue N1 = N->getOperand(1);
7925   EVT VT = N->getValueType(0);
7926   SDLoc SL(N);
7927 
7928   const TargetOptions &Options = DAG.getTarget().Options;
7929   bool AllowFusion =
7930       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7931 
7932   // Floating-point multiply-add with intermediate rounding.
7933   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7934 
7935   // Floating-point multiply-add without intermediate rounding.
7936   bool HasFMA =
7937       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7938       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7939 
7940   // No valid opcode, do not combine.
7941   if (!HasFMAD && !HasFMA)
7942     return SDValue();
7943 
7944   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7945   ;
7946   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7947     return SDValue();
7948 
7949   // Always prefer FMAD to FMA for precision.
7950   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7951   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7952   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7953 
7954   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7955   // prefer to fold the multiply with fewer uses.
7956   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7957       N1.getOpcode() == ISD::FMUL) {
7958     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7959       std::swap(N0, N1);
7960   }
7961 
7962   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7963   if (N0.getOpcode() == ISD::FMUL &&
7964       (Aggressive || N0->hasOneUse())) {
7965     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7966                        N0.getOperand(0), N0.getOperand(1), N1);
7967   }
7968 
7969   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7970   // Note: Commutes FADD operands.
7971   if (N1.getOpcode() == ISD::FMUL &&
7972       (Aggressive || N1->hasOneUse())) {
7973     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7974                        N1.getOperand(0), N1.getOperand(1), N0);
7975   }
7976 
7977   // Look through FP_EXTEND nodes to do more combining.
7978   if (AllowFusion && LookThroughFPExt) {
7979     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7980     if (N0.getOpcode() == ISD::FP_EXTEND) {
7981       SDValue N00 = N0.getOperand(0);
7982       if (N00.getOpcode() == ISD::FMUL)
7983         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7984                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7985                                        N00.getOperand(0)),
7986                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7987                                        N00.getOperand(1)), N1);
7988     }
7989 
7990     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7991     // Note: Commutes FADD operands.
7992     if (N1.getOpcode() == ISD::FP_EXTEND) {
7993       SDValue N10 = N1.getOperand(0);
7994       if (N10.getOpcode() == ISD::FMUL)
7995         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7996                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7997                                        N10.getOperand(0)),
7998                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7999                                        N10.getOperand(1)), N0);
8000     }
8001   }
8002 
8003   // More folding opportunities when target permits.
8004   if ((AllowFusion || HasFMAD)  && Aggressive) {
8005     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8006     if (N0.getOpcode() == PreferredFusedOpcode &&
8007         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8008       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8009                          N0.getOperand(0), N0.getOperand(1),
8010                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8011                                      N0.getOperand(2).getOperand(0),
8012                                      N0.getOperand(2).getOperand(1),
8013                                      N1));
8014     }
8015 
8016     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8017     if (N1->getOpcode() == PreferredFusedOpcode &&
8018         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8019       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8020                          N1.getOperand(0), N1.getOperand(1),
8021                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8022                                      N1.getOperand(2).getOperand(0),
8023                                      N1.getOperand(2).getOperand(1),
8024                                      N0));
8025     }
8026 
8027     if (AllowFusion && LookThroughFPExt) {
8028       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8029       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8030       auto FoldFAddFMAFPExtFMul = [&] (
8031           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8032         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8033                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8034                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8035                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8036                                        Z));
8037       };
8038       if (N0.getOpcode() == PreferredFusedOpcode) {
8039         SDValue N02 = N0.getOperand(2);
8040         if (N02.getOpcode() == ISD::FP_EXTEND) {
8041           SDValue N020 = N02.getOperand(0);
8042           if (N020.getOpcode() == ISD::FMUL)
8043             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8044                                         N020.getOperand(0), N020.getOperand(1),
8045                                         N1);
8046         }
8047       }
8048 
8049       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8050       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8051       // FIXME: This turns two single-precision and one double-precision
8052       // operation into two double-precision operations, which might not be
8053       // interesting for all targets, especially GPUs.
8054       auto FoldFAddFPExtFMAFMul = [&] (
8055           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8056         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8057                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8058                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8059                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8060                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8061                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8062                                        Z));
8063       };
8064       if (N0.getOpcode() == ISD::FP_EXTEND) {
8065         SDValue N00 = N0.getOperand(0);
8066         if (N00.getOpcode() == PreferredFusedOpcode) {
8067           SDValue N002 = N00.getOperand(2);
8068           if (N002.getOpcode() == ISD::FMUL)
8069             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8070                                         N002.getOperand(0), N002.getOperand(1),
8071                                         N1);
8072         }
8073       }
8074 
8075       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8076       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
8077       if (N1.getOpcode() == PreferredFusedOpcode) {
8078         SDValue N12 = N1.getOperand(2);
8079         if (N12.getOpcode() == ISD::FP_EXTEND) {
8080           SDValue N120 = N12.getOperand(0);
8081           if (N120.getOpcode() == ISD::FMUL)
8082             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8083                                         N120.getOperand(0), N120.getOperand(1),
8084                                         N0);
8085         }
8086       }
8087 
8088       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8089       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8090       // FIXME: This turns two single-precision and one double-precision
8091       // operation into two double-precision operations, which might not be
8092       // interesting for all targets, especially GPUs.
8093       if (N1.getOpcode() == ISD::FP_EXTEND) {
8094         SDValue N10 = N1.getOperand(0);
8095         if (N10.getOpcode() == PreferredFusedOpcode) {
8096           SDValue N102 = N10.getOperand(2);
8097           if (N102.getOpcode() == ISD::FMUL)
8098             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8099                                         N102.getOperand(0), N102.getOperand(1),
8100                                         N0);
8101         }
8102       }
8103     }
8104   }
8105 
8106   return SDValue();
8107 }
8108 
8109 /// Try to perform FMA combining on a given FSUB node.
8110 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8111   SDValue N0 = N->getOperand(0);
8112   SDValue N1 = N->getOperand(1);
8113   EVT VT = N->getValueType(0);
8114   SDLoc SL(N);
8115 
8116   const TargetOptions &Options = DAG.getTarget().Options;
8117   bool AllowFusion =
8118       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8119 
8120   // Floating-point multiply-add with intermediate rounding.
8121   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8122 
8123   // Floating-point multiply-add without intermediate rounding.
8124   bool HasFMA =
8125       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8126       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8127 
8128   // No valid opcode, do not combine.
8129   if (!HasFMAD && !HasFMA)
8130     return SDValue();
8131 
8132   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8133   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8134     return SDValue();
8135 
8136   // Always prefer FMAD to FMA for precision.
8137   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8138   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8139   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8140 
8141   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8142   if (N0.getOpcode() == ISD::FMUL &&
8143       (Aggressive || N0->hasOneUse())) {
8144     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8145                        N0.getOperand(0), N0.getOperand(1),
8146                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8147   }
8148 
8149   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8150   // Note: Commutes FSUB operands.
8151   if (N1.getOpcode() == ISD::FMUL &&
8152       (Aggressive || N1->hasOneUse()))
8153     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8154                        DAG.getNode(ISD::FNEG, SL, VT,
8155                                    N1.getOperand(0)),
8156                        N1.getOperand(1), N0);
8157 
8158   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8159   if (N0.getOpcode() == ISD::FNEG &&
8160       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8161       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8162     SDValue N00 = N0.getOperand(0).getOperand(0);
8163     SDValue N01 = N0.getOperand(0).getOperand(1);
8164     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8165                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8166                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8167   }
8168 
8169   // Look through FP_EXTEND nodes to do more combining.
8170   if (AllowFusion && LookThroughFPExt) {
8171     // fold (fsub (fpext (fmul x, y)), z)
8172     //   -> (fma (fpext x), (fpext y), (fneg z))
8173     if (N0.getOpcode() == ISD::FP_EXTEND) {
8174       SDValue N00 = N0.getOperand(0);
8175       if (N00.getOpcode() == ISD::FMUL)
8176         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8177                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8178                                        N00.getOperand(0)),
8179                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8180                                        N00.getOperand(1)),
8181                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8182     }
8183 
8184     // fold (fsub x, (fpext (fmul y, z)))
8185     //   -> (fma (fneg (fpext y)), (fpext z), x)
8186     // Note: Commutes FSUB operands.
8187     if (N1.getOpcode() == ISD::FP_EXTEND) {
8188       SDValue N10 = N1.getOperand(0);
8189       if (N10.getOpcode() == ISD::FMUL)
8190         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8191                            DAG.getNode(ISD::FNEG, SL, VT,
8192                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8193                                                    N10.getOperand(0))),
8194                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8195                                        N10.getOperand(1)),
8196                            N0);
8197     }
8198 
8199     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8200     //   -> (fneg (fma (fpext x), (fpext y), z))
8201     // Note: This could be removed with appropriate canonicalization of the
8202     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8203     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8204     // from implementing the canonicalization in visitFSUB.
8205     if (N0.getOpcode() == ISD::FP_EXTEND) {
8206       SDValue N00 = N0.getOperand(0);
8207       if (N00.getOpcode() == ISD::FNEG) {
8208         SDValue N000 = N00.getOperand(0);
8209         if (N000.getOpcode() == ISD::FMUL) {
8210           return DAG.getNode(ISD::FNEG, SL, VT,
8211                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8212                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8213                                                      N000.getOperand(0)),
8214                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8215                                                      N000.getOperand(1)),
8216                                          N1));
8217         }
8218       }
8219     }
8220 
8221     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8222     //   -> (fneg (fma (fpext x)), (fpext y), z)
8223     // Note: This could be removed with appropriate canonicalization of the
8224     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8225     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8226     // from implementing the canonicalization in visitFSUB.
8227     if (N0.getOpcode() == ISD::FNEG) {
8228       SDValue N00 = N0.getOperand(0);
8229       if (N00.getOpcode() == ISD::FP_EXTEND) {
8230         SDValue N000 = N00.getOperand(0);
8231         if (N000.getOpcode() == ISD::FMUL) {
8232           return DAG.getNode(ISD::FNEG, SL, VT,
8233                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8234                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8235                                                      N000.getOperand(0)),
8236                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8237                                                      N000.getOperand(1)),
8238                                          N1));
8239         }
8240       }
8241     }
8242 
8243   }
8244 
8245   // More folding opportunities when target permits.
8246   if ((AllowFusion || HasFMAD) && Aggressive) {
8247     // fold (fsub (fma x, y, (fmul u, v)), z)
8248     //   -> (fma x, y (fma u, v, (fneg z)))
8249     if (N0.getOpcode() == PreferredFusedOpcode &&
8250         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8251       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8252                          N0.getOperand(0), N0.getOperand(1),
8253                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8254                                      N0.getOperand(2).getOperand(0),
8255                                      N0.getOperand(2).getOperand(1),
8256                                      DAG.getNode(ISD::FNEG, SL, VT,
8257                                                  N1)));
8258     }
8259 
8260     // fold (fsub x, (fma y, z, (fmul u, v)))
8261     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8262     if (N1.getOpcode() == PreferredFusedOpcode &&
8263         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8264       SDValue N20 = N1.getOperand(2).getOperand(0);
8265       SDValue N21 = N1.getOperand(2).getOperand(1);
8266       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8267                          DAG.getNode(ISD::FNEG, SL, VT,
8268                                      N1.getOperand(0)),
8269                          N1.getOperand(1),
8270                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8271                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8272 
8273                                      N21, N0));
8274     }
8275 
8276     if (AllowFusion && LookThroughFPExt) {
8277       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8278       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8279       if (N0.getOpcode() == PreferredFusedOpcode) {
8280         SDValue N02 = N0.getOperand(2);
8281         if (N02.getOpcode() == ISD::FP_EXTEND) {
8282           SDValue N020 = N02.getOperand(0);
8283           if (N020.getOpcode() == ISD::FMUL)
8284             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8285                                N0.getOperand(0), N0.getOperand(1),
8286                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8287                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8288                                                        N020.getOperand(0)),
8289                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8290                                                        N020.getOperand(1)),
8291                                            DAG.getNode(ISD::FNEG, SL, VT,
8292                                                        N1)));
8293         }
8294       }
8295 
8296       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8297       //   -> (fma (fpext x), (fpext y),
8298       //           (fma (fpext u), (fpext v), (fneg z)))
8299       // FIXME: This turns two single-precision and one double-precision
8300       // operation into two double-precision operations, which might not be
8301       // interesting for all targets, especially GPUs.
8302       if (N0.getOpcode() == ISD::FP_EXTEND) {
8303         SDValue N00 = N0.getOperand(0);
8304         if (N00.getOpcode() == PreferredFusedOpcode) {
8305           SDValue N002 = N00.getOperand(2);
8306           if (N002.getOpcode() == ISD::FMUL)
8307             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8308                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8309                                            N00.getOperand(0)),
8310                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8311                                            N00.getOperand(1)),
8312                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8313                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8314                                                        N002.getOperand(0)),
8315                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8316                                                        N002.getOperand(1)),
8317                                            DAG.getNode(ISD::FNEG, SL, VT,
8318                                                        N1)));
8319         }
8320       }
8321 
8322       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8323       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8324       if (N1.getOpcode() == PreferredFusedOpcode &&
8325         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8326         SDValue N120 = N1.getOperand(2).getOperand(0);
8327         if (N120.getOpcode() == ISD::FMUL) {
8328           SDValue N1200 = N120.getOperand(0);
8329           SDValue N1201 = N120.getOperand(1);
8330           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8331                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8332                              N1.getOperand(1),
8333                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8334                                          DAG.getNode(ISD::FNEG, SL, VT,
8335                                              DAG.getNode(ISD::FP_EXTEND, SL,
8336                                                          VT, N1200)),
8337                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8338                                                      N1201),
8339                                          N0));
8340         }
8341       }
8342 
8343       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8344       //   -> (fma (fneg (fpext y)), (fpext z),
8345       //           (fma (fneg (fpext u)), (fpext v), x))
8346       // FIXME: This turns two single-precision and one double-precision
8347       // operation into two double-precision operations, which might not be
8348       // interesting for all targets, especially GPUs.
8349       if (N1.getOpcode() == ISD::FP_EXTEND &&
8350         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8351         SDValue N100 = N1.getOperand(0).getOperand(0);
8352         SDValue N101 = N1.getOperand(0).getOperand(1);
8353         SDValue N102 = N1.getOperand(0).getOperand(2);
8354         if (N102.getOpcode() == ISD::FMUL) {
8355           SDValue N1020 = N102.getOperand(0);
8356           SDValue N1021 = N102.getOperand(1);
8357           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8358                              DAG.getNode(ISD::FNEG, SL, VT,
8359                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8360                                                      N100)),
8361                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8362                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8363                                          DAG.getNode(ISD::FNEG, SL, VT,
8364                                              DAG.getNode(ISD::FP_EXTEND, SL,
8365                                                          VT, N1020)),
8366                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8367                                                      N1021),
8368                                          N0));
8369         }
8370       }
8371     }
8372   }
8373 
8374   return SDValue();
8375 }
8376 
8377 /// Try to perform FMA combining on a given FMUL node.
8378 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8379   SDValue N0 = N->getOperand(0);
8380   SDValue N1 = N->getOperand(1);
8381   EVT VT = N->getValueType(0);
8382   SDLoc SL(N);
8383 
8384   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8385 
8386   const TargetOptions &Options = DAG.getTarget().Options;
8387   bool AllowFusion =
8388       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8389 
8390   // Floating-point multiply-add with intermediate rounding.
8391   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8392 
8393   // Floating-point multiply-add without intermediate rounding.
8394   bool HasFMA =
8395       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8396       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8397 
8398   // No valid opcode, do not combine.
8399   if (!HasFMAD && !HasFMA)
8400     return SDValue();
8401 
8402   // Always prefer FMAD to FMA for precision.
8403   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8404   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8405 
8406   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8407   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8408   auto FuseFADD = [&](SDValue X, SDValue Y) {
8409     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8410       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8411       if (XC1 && XC1->isExactlyValue(+1.0))
8412         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8413       if (XC1 && XC1->isExactlyValue(-1.0))
8414         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8415                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8416     }
8417     return SDValue();
8418   };
8419 
8420   if (SDValue FMA = FuseFADD(N0, N1))
8421     return FMA;
8422   if (SDValue FMA = FuseFADD(N1, N0))
8423     return FMA;
8424 
8425   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8426   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8427   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8428   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8429   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8430     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8431       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8432       if (XC0 && XC0->isExactlyValue(+1.0))
8433         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8434                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8435                            Y);
8436       if (XC0 && XC0->isExactlyValue(-1.0))
8437         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8438                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8439                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8440 
8441       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8442       if (XC1 && XC1->isExactlyValue(+1.0))
8443         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8444                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8445       if (XC1 && XC1->isExactlyValue(-1.0))
8446         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8447     }
8448     return SDValue();
8449   };
8450 
8451   if (SDValue FMA = FuseFSUB(N0, N1))
8452     return FMA;
8453   if (SDValue FMA = FuseFSUB(N1, N0))
8454     return FMA;
8455 
8456   return SDValue();
8457 }
8458 
8459 SDValue DAGCombiner::visitFADD(SDNode *N) {
8460   SDValue N0 = N->getOperand(0);
8461   SDValue N1 = N->getOperand(1);
8462   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8463   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8464   EVT VT = N->getValueType(0);
8465   SDLoc DL(N);
8466   const TargetOptions &Options = DAG.getTarget().Options;
8467   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8468 
8469   // fold vector ops
8470   if (VT.isVector())
8471     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8472       return FoldedVOp;
8473 
8474   // fold (fadd c1, c2) -> c1 + c2
8475   if (N0CFP && N1CFP)
8476     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8477 
8478   // canonicalize constant to RHS
8479   if (N0CFP && !N1CFP)
8480     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8481 
8482   // fold (fadd A, (fneg B)) -> (fsub A, B)
8483   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8484       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8485     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8486                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8487 
8488   // fold (fadd (fneg A), B) -> (fsub B, A)
8489   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8490       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8491     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8492                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8493 
8494   // FIXME: Auto-upgrade the target/function-level option.
8495   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8496     // fold (fadd A, 0) -> A
8497     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8498       if (N1C->isZero())
8499         return N0;
8500   }
8501 
8502   // If 'unsafe math' is enabled, fold lots of things.
8503   if (Options.UnsafeFPMath) {
8504     // No FP constant should be created after legalization as Instruction
8505     // Selection pass has a hard time dealing with FP constants.
8506     bool AllowNewConst = (Level < AfterLegalizeDAG);
8507 
8508     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8509     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8510         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8511       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8512                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8513                                      Flags),
8514                          Flags);
8515 
8516     // If allowed, fold (fadd (fneg x), x) -> 0.0
8517     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8518       return DAG.getConstantFP(0.0, DL, VT);
8519 
8520     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8521     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8522       return DAG.getConstantFP(0.0, DL, VT);
8523 
8524     // We can fold chains of FADD's of the same value into multiplications.
8525     // This transform is not safe in general because we are reducing the number
8526     // of rounding steps.
8527     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8528       if (N0.getOpcode() == ISD::FMUL) {
8529         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8530         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8531 
8532         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8533         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8534           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8535                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8536           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8537         }
8538 
8539         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8540         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8541             N1.getOperand(0) == N1.getOperand(1) &&
8542             N0.getOperand(0) == N1.getOperand(0)) {
8543           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8544                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8545           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8546         }
8547       }
8548 
8549       if (N1.getOpcode() == ISD::FMUL) {
8550         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8551         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8552 
8553         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8554         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8555           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8556                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8557           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8558         }
8559 
8560         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8561         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8562             N0.getOperand(0) == N0.getOperand(1) &&
8563             N1.getOperand(0) == N0.getOperand(0)) {
8564           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8565                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8566           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8567         }
8568       }
8569 
8570       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8571         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8572         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8573         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8574             (N0.getOperand(0) == N1)) {
8575           return DAG.getNode(ISD::FMUL, DL, VT,
8576                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8577         }
8578       }
8579 
8580       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8581         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8582         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8583         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8584             N1.getOperand(0) == N0) {
8585           return DAG.getNode(ISD::FMUL, DL, VT,
8586                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8587         }
8588       }
8589 
8590       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8591       if (AllowNewConst &&
8592           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8593           N0.getOperand(0) == N0.getOperand(1) &&
8594           N1.getOperand(0) == N1.getOperand(1) &&
8595           N0.getOperand(0) == N1.getOperand(0)) {
8596         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8597                            DAG.getConstantFP(4.0, DL, VT), Flags);
8598       }
8599     }
8600   } // enable-unsafe-fp-math
8601 
8602   // FADD -> FMA combines:
8603   if (SDValue Fused = visitFADDForFMACombine(N)) {
8604     AddToWorklist(Fused.getNode());
8605     return Fused;
8606   }
8607   return SDValue();
8608 }
8609 
8610 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8611   SDValue N0 = N->getOperand(0);
8612   SDValue N1 = N->getOperand(1);
8613   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8614   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8615   EVT VT = N->getValueType(0);
8616   SDLoc DL(N);
8617   const TargetOptions &Options = DAG.getTarget().Options;
8618   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8619 
8620   // fold vector ops
8621   if (VT.isVector())
8622     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8623       return FoldedVOp;
8624 
8625   // fold (fsub c1, c2) -> c1-c2
8626   if (N0CFP && N1CFP)
8627     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
8628 
8629   // fold (fsub A, (fneg B)) -> (fadd A, B)
8630   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8631     return DAG.getNode(ISD::FADD, DL, VT, N0,
8632                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8633 
8634   // FIXME: Auto-upgrade the target/function-level option.
8635   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8636     // (fsub 0, B) -> -B
8637     if (N0CFP && N0CFP->isZero()) {
8638       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8639         return GetNegatedExpression(N1, DAG, LegalOperations);
8640       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8641         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
8642     }
8643   }
8644 
8645   // If 'unsafe math' is enabled, fold lots of things.
8646   if (Options.UnsafeFPMath) {
8647     // (fsub A, 0) -> A
8648     if (N1CFP && N1CFP->isZero())
8649       return N0;
8650 
8651     // (fsub x, x) -> 0.0
8652     if (N0 == N1)
8653       return DAG.getConstantFP(0.0f, DL, VT);
8654 
8655     // (fsub x, (fadd x, y)) -> (fneg y)
8656     // (fsub x, (fadd y, x)) -> (fneg y)
8657     if (N1.getOpcode() == ISD::FADD) {
8658       SDValue N10 = N1->getOperand(0);
8659       SDValue N11 = N1->getOperand(1);
8660 
8661       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8662         return GetNegatedExpression(N11, DAG, LegalOperations);
8663 
8664       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8665         return GetNegatedExpression(N10, DAG, LegalOperations);
8666     }
8667   }
8668 
8669   // FSUB -> FMA combines:
8670   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8671     AddToWorklist(Fused.getNode());
8672     return Fused;
8673   }
8674 
8675   return SDValue();
8676 }
8677 
8678 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8679   SDValue N0 = N->getOperand(0);
8680   SDValue N1 = N->getOperand(1);
8681   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8682   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8683   EVT VT = N->getValueType(0);
8684   SDLoc DL(N);
8685   const TargetOptions &Options = DAG.getTarget().Options;
8686   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8687 
8688   // fold vector ops
8689   if (VT.isVector()) {
8690     // This just handles C1 * C2 for vectors. Other vector folds are below.
8691     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8692       return FoldedVOp;
8693   }
8694 
8695   // fold (fmul c1, c2) -> c1*c2
8696   if (N0CFP && N1CFP)
8697     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8698 
8699   // canonicalize constant to RHS
8700   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8701      !isConstantFPBuildVectorOrConstantFP(N1))
8702     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8703 
8704   // fold (fmul A, 1.0) -> A
8705   if (N1CFP && N1CFP->isExactlyValue(1.0))
8706     return N0;
8707 
8708   if (Options.UnsafeFPMath) {
8709     // fold (fmul A, 0) -> 0
8710     if (N1CFP && N1CFP->isZero())
8711       return N1;
8712 
8713     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8714     if (N0.getOpcode() == ISD::FMUL) {
8715       // Fold scalars or any vector constants (not just splats).
8716       // This fold is done in general by InstCombine, but extra fmul insts
8717       // may have been generated during lowering.
8718       SDValue N00 = N0.getOperand(0);
8719       SDValue N01 = N0.getOperand(1);
8720       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8721       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8722       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8723 
8724       // Check 1: Make sure that the first operand of the inner multiply is NOT
8725       // a constant. Otherwise, we may induce infinite looping.
8726       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8727         // Check 2: Make sure that the second operand of the inner multiply and
8728         // the second operand of the outer multiply are constants.
8729         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8730             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8731           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8732           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8733         }
8734       }
8735     }
8736 
8737     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8738     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8739     // during an early run of DAGCombiner can prevent folding with fmuls
8740     // inserted during lowering.
8741     if (N0.getOpcode() == ISD::FADD &&
8742         (N0.getOperand(0) == N0.getOperand(1)) &&
8743         N0.hasOneUse()) {
8744       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8745       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8746       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8747     }
8748   }
8749 
8750   // fold (fmul X, 2.0) -> (fadd X, X)
8751   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8752     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8753 
8754   // fold (fmul X, -1.0) -> (fneg X)
8755   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8756     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8757       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8758 
8759   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8760   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8761     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8762       // Both can be negated for free, check to see if at least one is cheaper
8763       // negated.
8764       if (LHSNeg == 2 || RHSNeg == 2)
8765         return DAG.getNode(ISD::FMUL, DL, VT,
8766                            GetNegatedExpression(N0, DAG, LegalOperations),
8767                            GetNegatedExpression(N1, DAG, LegalOperations),
8768                            Flags);
8769     }
8770   }
8771 
8772   // FMUL -> FMA combines:
8773   if (SDValue Fused = visitFMULForFMACombine(N)) {
8774     AddToWorklist(Fused.getNode());
8775     return Fused;
8776   }
8777 
8778   return SDValue();
8779 }
8780 
8781 SDValue DAGCombiner::visitFMA(SDNode *N) {
8782   SDValue N0 = N->getOperand(0);
8783   SDValue N1 = N->getOperand(1);
8784   SDValue N2 = N->getOperand(2);
8785   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8786   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8787   EVT VT = N->getValueType(0);
8788   SDLoc DL(N);
8789   const TargetOptions &Options = DAG.getTarget().Options;
8790 
8791   // Constant fold FMA.
8792   if (isa<ConstantFPSDNode>(N0) &&
8793       isa<ConstantFPSDNode>(N1) &&
8794       isa<ConstantFPSDNode>(N2)) {
8795     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
8796   }
8797 
8798   if (Options.UnsafeFPMath) {
8799     if (N0CFP && N0CFP->isZero())
8800       return N2;
8801     if (N1CFP && N1CFP->isZero())
8802       return N2;
8803   }
8804   // TODO: The FMA node should have flags that propagate to these nodes.
8805   if (N0CFP && N0CFP->isExactlyValue(1.0))
8806     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8807   if (N1CFP && N1CFP->isExactlyValue(1.0))
8808     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8809 
8810   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8811   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8812      !isConstantFPBuildVectorOrConstantFP(N1))
8813     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8814 
8815   // TODO: FMA nodes should have flags that propagate to the created nodes.
8816   // For now, create a Flags object for use with all unsafe math transforms.
8817   SDNodeFlags Flags;
8818   Flags.setUnsafeAlgebra(true);
8819 
8820   if (Options.UnsafeFPMath) {
8821     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8822     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8823         isConstantFPBuildVectorOrConstantFP(N1) &&
8824         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8825       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8826                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
8827                                      &Flags), &Flags);
8828     }
8829 
8830     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8831     if (N0.getOpcode() == ISD::FMUL &&
8832         isConstantFPBuildVectorOrConstantFP(N1) &&
8833         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8834       return DAG.getNode(ISD::FMA, DL, VT,
8835                          N0.getOperand(0),
8836                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
8837                                      &Flags),
8838                          N2);
8839     }
8840   }
8841 
8842   // (fma x, 1, y) -> (fadd x, y)
8843   // (fma x, -1, y) -> (fadd (fneg x), y)
8844   if (N1CFP) {
8845     if (N1CFP->isExactlyValue(1.0))
8846       // TODO: The FMA node should have flags that propagate to this node.
8847       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
8848 
8849     if (N1CFP->isExactlyValue(-1.0) &&
8850         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8851       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
8852       AddToWorklist(RHSNeg.getNode());
8853       // TODO: The FMA node should have flags that propagate to this node.
8854       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
8855     }
8856   }
8857 
8858   if (Options.UnsafeFPMath) {
8859     // (fma x, c, x) -> (fmul x, (c+1))
8860     if (N1CFP && N0 == N2) {
8861       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8862                          DAG.getNode(ISD::FADD, DL, VT, N1,
8863                                      DAG.getConstantFP(1.0, DL, VT), &Flags),
8864                          &Flags);
8865     }
8866 
8867     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8868     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8869       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8870                          DAG.getNode(ISD::FADD, DL, VT, N1,
8871                                      DAG.getConstantFP(-1.0, DL, VT), &Flags),
8872                          &Flags);
8873     }
8874   }
8875 
8876   return SDValue();
8877 }
8878 
8879 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8880 // reciprocal.
8881 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8882 // Notice that this is not always beneficial. One reason is different target
8883 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8884 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8885 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8886 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8887   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8888   const SDNodeFlags *Flags = N->getFlags();
8889   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8890     return SDValue();
8891 
8892   // Skip if current node is a reciprocal.
8893   SDValue N0 = N->getOperand(0);
8894   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8895   if (N0CFP && N0CFP->isExactlyValue(1.0))
8896     return SDValue();
8897 
8898   // Exit early if the target does not want this transform or if there can't
8899   // possibly be enough uses of the divisor to make the transform worthwhile.
8900   SDValue N1 = N->getOperand(1);
8901   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8902   if (!MinUses || N1->use_size() < MinUses)
8903     return SDValue();
8904 
8905   // Find all FDIV users of the same divisor.
8906   // Use a set because duplicates may be present in the user list.
8907   SetVector<SDNode *> Users;
8908   for (auto *U : N1->uses()) {
8909     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8910       // This division is eligible for optimization only if global unsafe math
8911       // is enabled or if this division allows reciprocal formation.
8912       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8913         Users.insert(U);
8914     }
8915   }
8916 
8917   // Now that we have the actual number of divisor uses, make sure it meets
8918   // the minimum threshold specified by the target.
8919   if (Users.size() < MinUses)
8920     return SDValue();
8921 
8922   EVT VT = N->getValueType(0);
8923   SDLoc DL(N);
8924   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8925   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8926 
8927   // Dividend / Divisor -> Dividend * Reciprocal
8928   for (auto *U : Users) {
8929     SDValue Dividend = U->getOperand(0);
8930     if (Dividend != FPOne) {
8931       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8932                                     Reciprocal, Flags);
8933       CombineTo(U, NewNode);
8934     } else if (U != Reciprocal.getNode()) {
8935       // In the absence of fast-math-flags, this user node is always the
8936       // same node as Reciprocal, but with FMF they may be different nodes.
8937       CombineTo(U, Reciprocal);
8938     }
8939   }
8940   return SDValue(N, 0);  // N was replaced.
8941 }
8942 
8943 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8944   SDValue N0 = N->getOperand(0);
8945   SDValue N1 = N->getOperand(1);
8946   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8947   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8948   EVT VT = N->getValueType(0);
8949   SDLoc DL(N);
8950   const TargetOptions &Options = DAG.getTarget().Options;
8951   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8952 
8953   // fold vector ops
8954   if (VT.isVector())
8955     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8956       return FoldedVOp;
8957 
8958   // fold (fdiv c1, c2) -> c1/c2
8959   if (N0CFP && N1CFP)
8960     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8961 
8962   if (Options.UnsafeFPMath) {
8963     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8964     if (N1CFP) {
8965       // Compute the reciprocal 1.0 / c2.
8966       const APFloat &N1APF = N1CFP->getValueAPF();
8967       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8968       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8969       // Only do the transform if the reciprocal is a legal fp immediate that
8970       // isn't too nasty (eg NaN, denormal, ...).
8971       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8972           (!LegalOperations ||
8973            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8974            // backend)... we should handle this gracefully after Legalize.
8975            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8976            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8977            TLI.isFPImmLegal(Recip, VT)))
8978         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8979                            DAG.getConstantFP(Recip, DL, VT), Flags);
8980     }
8981 
8982     // If this FDIV is part of a reciprocal square root, it may be folded
8983     // into a target-specific square root estimate instruction.
8984     if (N1.getOpcode() == ISD::FSQRT) {
8985       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
8986         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8987       }
8988     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8989                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8990       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8991                                           Flags)) {
8992         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8993         AddToWorklist(RV.getNode());
8994         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8995       }
8996     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8997                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8998       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8999                                           Flags)) {
9000         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9001         AddToWorklist(RV.getNode());
9002         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9003       }
9004     } else if (N1.getOpcode() == ISD::FMUL) {
9005       // Look through an FMUL. Even though this won't remove the FDIV directly,
9006       // it's still worthwhile to get rid of the FSQRT if possible.
9007       SDValue SqrtOp;
9008       SDValue OtherOp;
9009       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9010         SqrtOp = N1.getOperand(0);
9011         OtherOp = N1.getOperand(1);
9012       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9013         SqrtOp = N1.getOperand(1);
9014         OtherOp = N1.getOperand(0);
9015       }
9016       if (SqrtOp.getNode()) {
9017         // We found a FSQRT, so try to make this fold:
9018         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9019         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9020           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9021           AddToWorklist(RV.getNode());
9022           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9023         }
9024       }
9025     }
9026 
9027     // Fold into a reciprocal estimate and multiply instead of a real divide.
9028     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9029       AddToWorklist(RV.getNode());
9030       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9031     }
9032   }
9033 
9034   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9035   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9036     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9037       // Both can be negated for free, check to see if at least one is cheaper
9038       // negated.
9039       if (LHSNeg == 2 || RHSNeg == 2)
9040         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9041                            GetNegatedExpression(N0, DAG, LegalOperations),
9042                            GetNegatedExpression(N1, DAG, LegalOperations),
9043                            Flags);
9044     }
9045   }
9046 
9047   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9048     return CombineRepeatedDivisors;
9049 
9050   return SDValue();
9051 }
9052 
9053 SDValue DAGCombiner::visitFREM(SDNode *N) {
9054   SDValue N0 = N->getOperand(0);
9055   SDValue N1 = N->getOperand(1);
9056   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9057   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9058   EVT VT = N->getValueType(0);
9059 
9060   // fold (frem c1, c2) -> fmod(c1,c2)
9061   if (N0CFP && N1CFP)
9062     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9063                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
9064 
9065   return SDValue();
9066 }
9067 
9068 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9069   if (!DAG.getTarget().Options.UnsafeFPMath)
9070     return SDValue();
9071 
9072   SDValue N0 = N->getOperand(0);
9073   if (TLI.isFsqrtCheap(N0, DAG))
9074     return SDValue();
9075 
9076   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9077   // For now, create a Flags object for use with all unsafe math transforms.
9078   SDNodeFlags Flags;
9079   Flags.setUnsafeAlgebra(true);
9080   return buildSqrtEstimate(N0, &Flags);
9081 }
9082 
9083 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9084 /// copysign(x, fp_round(y)) -> copysign(x, y)
9085 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9086   SDValue N1 = N->getOperand(1);
9087   if ((N1.getOpcode() == ISD::FP_EXTEND ||
9088        N1.getOpcode() == ISD::FP_ROUND)) {
9089     // Do not optimize out type conversion of f128 type yet.
9090     // For some targets like x86_64, configuration is changed to keep one f128
9091     // value in one SSE register, but instruction selection cannot handle
9092     // FCOPYSIGN on SSE registers yet.
9093     EVT N1VT = N1->getValueType(0);
9094     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9095     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9096   }
9097   return false;
9098 }
9099 
9100 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9101   SDValue N0 = N->getOperand(0);
9102   SDValue N1 = N->getOperand(1);
9103   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9104   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9105   EVT VT = N->getValueType(0);
9106 
9107   if (N0CFP && N1CFP) // Constant fold
9108     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9109 
9110   if (N1CFP) {
9111     const APFloat &V = N1CFP->getValueAPF();
9112     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
9113     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9114     if (!V.isNegative()) {
9115       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9116         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9117     } else {
9118       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9119         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9120                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9121     }
9122   }
9123 
9124   // copysign(fabs(x), y) -> copysign(x, y)
9125   // copysign(fneg(x), y) -> copysign(x, y)
9126   // copysign(copysign(x,z), y) -> copysign(x, y)
9127   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9128       N0.getOpcode() == ISD::FCOPYSIGN)
9129     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9130 
9131   // copysign(x, abs(y)) -> abs(x)
9132   if (N1.getOpcode() == ISD::FABS)
9133     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9134 
9135   // copysign(x, copysign(y,z)) -> copysign(x, z)
9136   if (N1.getOpcode() == ISD::FCOPYSIGN)
9137     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9138 
9139   // copysign(x, fp_extend(y)) -> copysign(x, y)
9140   // copysign(x, fp_round(y)) -> copysign(x, y)
9141   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9142     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9143 
9144   return SDValue();
9145 }
9146 
9147 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9148   SDValue N0 = N->getOperand(0);
9149   EVT VT = N->getValueType(0);
9150   EVT OpVT = N0.getValueType();
9151 
9152   // fold (sint_to_fp c1) -> c1fp
9153   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9154       // ...but only if the target supports immediate floating-point values
9155       (!LegalOperations ||
9156        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9157     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9158 
9159   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9160   // but UINT_TO_FP is legal on this target, try to convert.
9161   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9162       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9163     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9164     if (DAG.SignBitIsZero(N0))
9165       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9166   }
9167 
9168   // The next optimizations are desirable only if SELECT_CC can be lowered.
9169   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9170     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9171     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9172         !VT.isVector() &&
9173         (!LegalOperations ||
9174          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9175       SDLoc DL(N);
9176       SDValue Ops[] =
9177         { N0.getOperand(0), N0.getOperand(1),
9178           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9179           N0.getOperand(2) };
9180       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9181     }
9182 
9183     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9184     //      (select_cc x, y, 1.0, 0.0,, cc)
9185     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9186         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9187         (!LegalOperations ||
9188          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9189       SDLoc DL(N);
9190       SDValue Ops[] =
9191         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9192           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9193           N0.getOperand(0).getOperand(2) };
9194       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9195     }
9196   }
9197 
9198   return SDValue();
9199 }
9200 
9201 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9202   SDValue N0 = N->getOperand(0);
9203   EVT VT = N->getValueType(0);
9204   EVT OpVT = N0.getValueType();
9205 
9206   // fold (uint_to_fp c1) -> c1fp
9207   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9208       // ...but only if the target supports immediate floating-point values
9209       (!LegalOperations ||
9210        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9211     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9212 
9213   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9214   // but SINT_TO_FP is legal on this target, try to convert.
9215   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9216       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9217     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9218     if (DAG.SignBitIsZero(N0))
9219       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9220   }
9221 
9222   // The next optimizations are desirable only if SELECT_CC can be lowered.
9223   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9224     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9225 
9226     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9227         (!LegalOperations ||
9228          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9229       SDLoc DL(N);
9230       SDValue Ops[] =
9231         { N0.getOperand(0), N0.getOperand(1),
9232           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9233           N0.getOperand(2) };
9234       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9235     }
9236   }
9237 
9238   return SDValue();
9239 }
9240 
9241 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9242 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9243   SDValue N0 = N->getOperand(0);
9244   EVT VT = N->getValueType(0);
9245 
9246   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9247     return SDValue();
9248 
9249   SDValue Src = N0.getOperand(0);
9250   EVT SrcVT = Src.getValueType();
9251   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9252   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9253 
9254   // We can safely assume the conversion won't overflow the output range,
9255   // because (for example) (uint8_t)18293.f is undefined behavior.
9256 
9257   // Since we can assume the conversion won't overflow, our decision as to
9258   // whether the input will fit in the float should depend on the minimum
9259   // of the input range and output range.
9260 
9261   // This means this is also safe for a signed input and unsigned output, since
9262   // a negative input would lead to undefined behavior.
9263   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9264   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9265   unsigned ActualSize = std::min(InputSize, OutputSize);
9266   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9267 
9268   // We can only fold away the float conversion if the input range can be
9269   // represented exactly in the float range.
9270   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9271     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9272       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9273                                                        : ISD::ZERO_EXTEND;
9274       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9275     }
9276     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9277       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9278     return DAG.getBitcast(VT, Src);
9279   }
9280   return SDValue();
9281 }
9282 
9283 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9284   SDValue N0 = N->getOperand(0);
9285   EVT VT = N->getValueType(0);
9286 
9287   // fold (fp_to_sint c1fp) -> c1
9288   if (isConstantFPBuildVectorOrConstantFP(N0))
9289     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9290 
9291   return FoldIntToFPToInt(N, DAG);
9292 }
9293 
9294 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9295   SDValue N0 = N->getOperand(0);
9296   EVT VT = N->getValueType(0);
9297 
9298   // fold (fp_to_uint c1fp) -> c1
9299   if (isConstantFPBuildVectorOrConstantFP(N0))
9300     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9301 
9302   return FoldIntToFPToInt(N, DAG);
9303 }
9304 
9305 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9306   SDValue N0 = N->getOperand(0);
9307   SDValue N1 = N->getOperand(1);
9308   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9309   EVT VT = N->getValueType(0);
9310 
9311   // fold (fp_round c1fp) -> c1fp
9312   if (N0CFP)
9313     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9314 
9315   // fold (fp_round (fp_extend x)) -> x
9316   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9317     return N0.getOperand(0);
9318 
9319   // fold (fp_round (fp_round x)) -> (fp_round x)
9320   if (N0.getOpcode() == ISD::FP_ROUND) {
9321     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9322     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9323 
9324     // Skip this folding if it results in an fp_round from f80 to f16.
9325     //
9326     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9327     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9328     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9329     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9330     // x86.
9331     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9332       return SDValue();
9333 
9334     // If the first fp_round isn't a value preserving truncation, it might
9335     // introduce a tie in the second fp_round, that wouldn't occur in the
9336     // single-step fp_round we want to fold to.
9337     // In other words, double rounding isn't the same as rounding.
9338     // Also, this is a value preserving truncation iff both fp_round's are.
9339     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9340       SDLoc DL(N);
9341       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9342                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9343     }
9344   }
9345 
9346   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9347   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9348     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9349                               N0.getOperand(0), N1);
9350     AddToWorklist(Tmp.getNode());
9351     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9352                        Tmp, N0.getOperand(1));
9353   }
9354 
9355   return SDValue();
9356 }
9357 
9358 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9359   SDValue N0 = N->getOperand(0);
9360   EVT VT = N->getValueType(0);
9361   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9362   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9363 
9364   // fold (fp_round_inreg c1fp) -> c1fp
9365   if (N0CFP && isTypeLegal(EVT)) {
9366     SDLoc DL(N);
9367     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9368     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9369   }
9370 
9371   return SDValue();
9372 }
9373 
9374 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9375   SDValue N0 = N->getOperand(0);
9376   EVT VT = N->getValueType(0);
9377 
9378   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9379   if (N->hasOneUse() &&
9380       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9381     return SDValue();
9382 
9383   // fold (fp_extend c1fp) -> c1fp
9384   if (isConstantFPBuildVectorOrConstantFP(N0))
9385     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9386 
9387   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9388   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9389       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9390     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9391 
9392   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9393   // value of X.
9394   if (N0.getOpcode() == ISD::FP_ROUND
9395       && N0.getNode()->getConstantOperandVal(1) == 1) {
9396     SDValue In = N0.getOperand(0);
9397     if (In.getValueType() == VT) return In;
9398     if (VT.bitsLT(In.getValueType()))
9399       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9400                          In, N0.getOperand(1));
9401     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9402   }
9403 
9404   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9405   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9406        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9407     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9408     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9409                                      LN0->getChain(),
9410                                      LN0->getBasePtr(), N0.getValueType(),
9411                                      LN0->getMemOperand());
9412     CombineTo(N, ExtLoad);
9413     CombineTo(N0.getNode(),
9414               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9415                           N0.getValueType(), ExtLoad,
9416                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9417               ExtLoad.getValue(1));
9418     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9419   }
9420 
9421   return SDValue();
9422 }
9423 
9424 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9425   SDValue N0 = N->getOperand(0);
9426   EVT VT = N->getValueType(0);
9427 
9428   // fold (fceil c1) -> fceil(c1)
9429   if (isConstantFPBuildVectorOrConstantFP(N0))
9430     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9431 
9432   return SDValue();
9433 }
9434 
9435 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9436   SDValue N0 = N->getOperand(0);
9437   EVT VT = N->getValueType(0);
9438 
9439   // fold (ftrunc c1) -> ftrunc(c1)
9440   if (isConstantFPBuildVectorOrConstantFP(N0))
9441     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9442 
9443   return SDValue();
9444 }
9445 
9446 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9447   SDValue N0 = N->getOperand(0);
9448   EVT VT = N->getValueType(0);
9449 
9450   // fold (ffloor c1) -> ffloor(c1)
9451   if (isConstantFPBuildVectorOrConstantFP(N0))
9452     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9453 
9454   return SDValue();
9455 }
9456 
9457 // FIXME: FNEG and FABS have a lot in common; refactor.
9458 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9459   SDValue N0 = N->getOperand(0);
9460   EVT VT = N->getValueType(0);
9461 
9462   // Constant fold FNEG.
9463   if (isConstantFPBuildVectorOrConstantFP(N0))
9464     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9465 
9466   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9467                          &DAG.getTarget().Options))
9468     return GetNegatedExpression(N0, DAG, LegalOperations);
9469 
9470   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9471   // constant pool values.
9472   if (!TLI.isFNegFree(VT) &&
9473       N0.getOpcode() == ISD::BITCAST &&
9474       N0.getNode()->hasOneUse()) {
9475     SDValue Int = N0.getOperand(0);
9476     EVT IntVT = Int.getValueType();
9477     if (IntVT.isInteger() && !IntVT.isVector()) {
9478       APInt SignMask;
9479       if (N0.getValueType().isVector()) {
9480         // For a vector, get a mask such as 0x80... per scalar element
9481         // and splat it.
9482         SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits());
9483         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9484       } else {
9485         // For a scalar, just generate 0x80...
9486         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9487       }
9488       SDLoc DL0(N0);
9489       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9490                         DAG.getConstant(SignMask, DL0, IntVT));
9491       AddToWorklist(Int.getNode());
9492       return DAG.getBitcast(VT, Int);
9493     }
9494   }
9495 
9496   // (fneg (fmul c, x)) -> (fmul -c, x)
9497   if (N0.getOpcode() == ISD::FMUL &&
9498       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9499     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9500     if (CFP1) {
9501       APFloat CVal = CFP1->getValueAPF();
9502       CVal.changeSign();
9503       if (Level >= AfterLegalizeDAG &&
9504           (TLI.isFPImmLegal(CVal, VT) ||
9505            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9506         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9507                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9508                                        N0.getOperand(1)),
9509                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9510     }
9511   }
9512 
9513   return SDValue();
9514 }
9515 
9516 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9517   SDValue N0 = N->getOperand(0);
9518   SDValue N1 = N->getOperand(1);
9519   EVT VT = N->getValueType(0);
9520   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9521   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9522 
9523   if (N0CFP && N1CFP) {
9524     const APFloat &C0 = N0CFP->getValueAPF();
9525     const APFloat &C1 = N1CFP->getValueAPF();
9526     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9527   }
9528 
9529   // Canonicalize to constant on RHS.
9530   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9531      !isConstantFPBuildVectorOrConstantFP(N1))
9532     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9533 
9534   return SDValue();
9535 }
9536 
9537 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9538   SDValue N0 = N->getOperand(0);
9539   SDValue N1 = N->getOperand(1);
9540   EVT VT = N->getValueType(0);
9541   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9542   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9543 
9544   if (N0CFP && N1CFP) {
9545     const APFloat &C0 = N0CFP->getValueAPF();
9546     const APFloat &C1 = N1CFP->getValueAPF();
9547     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9548   }
9549 
9550   // Canonicalize to constant on RHS.
9551   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9552      !isConstantFPBuildVectorOrConstantFP(N1))
9553     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9554 
9555   return SDValue();
9556 }
9557 
9558 SDValue DAGCombiner::visitFABS(SDNode *N) {
9559   SDValue N0 = N->getOperand(0);
9560   EVT VT = N->getValueType(0);
9561 
9562   // fold (fabs c1) -> fabs(c1)
9563   if (isConstantFPBuildVectorOrConstantFP(N0))
9564     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9565 
9566   // fold (fabs (fabs x)) -> (fabs x)
9567   if (N0.getOpcode() == ISD::FABS)
9568     return N->getOperand(0);
9569 
9570   // fold (fabs (fneg x)) -> (fabs x)
9571   // fold (fabs (fcopysign x, y)) -> (fabs x)
9572   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9573     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9574 
9575   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9576   // constant pool values.
9577   if (!TLI.isFAbsFree(VT) &&
9578       N0.getOpcode() == ISD::BITCAST &&
9579       N0.getNode()->hasOneUse()) {
9580     SDValue Int = N0.getOperand(0);
9581     EVT IntVT = Int.getValueType();
9582     if (IntVT.isInteger() && !IntVT.isVector()) {
9583       APInt SignMask;
9584       if (N0.getValueType().isVector()) {
9585         // For a vector, get a mask such as 0x7f... per scalar element
9586         // and splat it.
9587         SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits());
9588         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9589       } else {
9590         // For a scalar, just generate 0x7f...
9591         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9592       }
9593       SDLoc DL(N0);
9594       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9595                         DAG.getConstant(SignMask, DL, IntVT));
9596       AddToWorklist(Int.getNode());
9597       return DAG.getBitcast(N->getValueType(0), Int);
9598     }
9599   }
9600 
9601   return SDValue();
9602 }
9603 
9604 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9605   SDValue Chain = N->getOperand(0);
9606   SDValue N1 = N->getOperand(1);
9607   SDValue N2 = N->getOperand(2);
9608 
9609   // If N is a constant we could fold this into a fallthrough or unconditional
9610   // branch. However that doesn't happen very often in normal code, because
9611   // Instcombine/SimplifyCFG should have handled the available opportunities.
9612   // If we did this folding here, it would be necessary to update the
9613   // MachineBasicBlock CFG, which is awkward.
9614 
9615   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9616   // on the target.
9617   if (N1.getOpcode() == ISD::SETCC &&
9618       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9619                                    N1.getOperand(0).getValueType())) {
9620     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9621                        Chain, N1.getOperand(2),
9622                        N1.getOperand(0), N1.getOperand(1), N2);
9623   }
9624 
9625   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9626       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9627        (N1.getOperand(0).hasOneUse() &&
9628         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9629     SDNode *Trunc = nullptr;
9630     if (N1.getOpcode() == ISD::TRUNCATE) {
9631       // Look pass the truncate.
9632       Trunc = N1.getNode();
9633       N1 = N1.getOperand(0);
9634     }
9635 
9636     // Match this pattern so that we can generate simpler code:
9637     //
9638     //   %a = ...
9639     //   %b = and i32 %a, 2
9640     //   %c = srl i32 %b, 1
9641     //   brcond i32 %c ...
9642     //
9643     // into
9644     //
9645     //   %a = ...
9646     //   %b = and i32 %a, 2
9647     //   %c = setcc eq %b, 0
9648     //   brcond %c ...
9649     //
9650     // This applies only when the AND constant value has one bit set and the
9651     // SRL constant is equal to the log2 of the AND constant. The back-end is
9652     // smart enough to convert the result into a TEST/JMP sequence.
9653     SDValue Op0 = N1.getOperand(0);
9654     SDValue Op1 = N1.getOperand(1);
9655 
9656     if (Op0.getOpcode() == ISD::AND &&
9657         Op1.getOpcode() == ISD::Constant) {
9658       SDValue AndOp1 = Op0.getOperand(1);
9659 
9660       if (AndOp1.getOpcode() == ISD::Constant) {
9661         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9662 
9663         if (AndConst.isPowerOf2() &&
9664             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9665           SDLoc DL(N);
9666           SDValue SetCC =
9667             DAG.getSetCC(DL,
9668                          getSetCCResultType(Op0.getValueType()),
9669                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9670                          ISD::SETNE);
9671 
9672           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9673                                           MVT::Other, Chain, SetCC, N2);
9674           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9675           // will convert it back to (X & C1) >> C2.
9676           CombineTo(N, NewBRCond, false);
9677           // Truncate is dead.
9678           if (Trunc)
9679             deleteAndRecombine(Trunc);
9680           // Replace the uses of SRL with SETCC
9681           WorklistRemover DeadNodes(*this);
9682           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9683           deleteAndRecombine(N1.getNode());
9684           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9685         }
9686       }
9687     }
9688 
9689     if (Trunc)
9690       // Restore N1 if the above transformation doesn't match.
9691       N1 = N->getOperand(1);
9692   }
9693 
9694   // Transform br(xor(x, y)) -> br(x != y)
9695   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9696   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9697     SDNode *TheXor = N1.getNode();
9698     SDValue Op0 = TheXor->getOperand(0);
9699     SDValue Op1 = TheXor->getOperand(1);
9700     if (Op0.getOpcode() == Op1.getOpcode()) {
9701       // Avoid missing important xor optimizations.
9702       if (SDValue Tmp = visitXOR(TheXor)) {
9703         if (Tmp.getNode() != TheXor) {
9704           DEBUG(dbgs() << "\nReplacing.8 ";
9705                 TheXor->dump(&DAG);
9706                 dbgs() << "\nWith: ";
9707                 Tmp.getNode()->dump(&DAG);
9708                 dbgs() << '\n');
9709           WorklistRemover DeadNodes(*this);
9710           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9711           deleteAndRecombine(TheXor);
9712           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9713                              MVT::Other, Chain, Tmp, N2);
9714         }
9715 
9716         // visitXOR has changed XOR's operands or replaced the XOR completely,
9717         // bail out.
9718         return SDValue(N, 0);
9719       }
9720     }
9721 
9722     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9723       bool Equal = false;
9724       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9725           Op0.getOpcode() == ISD::XOR) {
9726         TheXor = Op0.getNode();
9727         Equal = true;
9728       }
9729 
9730       EVT SetCCVT = N1.getValueType();
9731       if (LegalTypes)
9732         SetCCVT = getSetCCResultType(SetCCVT);
9733       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9734                                    SetCCVT,
9735                                    Op0, Op1,
9736                                    Equal ? ISD::SETEQ : ISD::SETNE);
9737       // Replace the uses of XOR with SETCC
9738       WorklistRemover DeadNodes(*this);
9739       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9740       deleteAndRecombine(N1.getNode());
9741       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9742                          MVT::Other, Chain, SetCC, N2);
9743     }
9744   }
9745 
9746   return SDValue();
9747 }
9748 
9749 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9750 //
9751 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9752   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9753   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9754 
9755   // If N is a constant we could fold this into a fallthrough or unconditional
9756   // branch. However that doesn't happen very often in normal code, because
9757   // Instcombine/SimplifyCFG should have handled the available opportunities.
9758   // If we did this folding here, it would be necessary to update the
9759   // MachineBasicBlock CFG, which is awkward.
9760 
9761   // Use SimplifySetCC to simplify SETCC's.
9762   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9763                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9764                                false);
9765   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9766 
9767   // fold to a simpler setcc
9768   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9769     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9770                        N->getOperand(0), Simp.getOperand(2),
9771                        Simp.getOperand(0), Simp.getOperand(1),
9772                        N->getOperand(4));
9773 
9774   return SDValue();
9775 }
9776 
9777 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9778 /// and that N may be folded in the load / store addressing mode.
9779 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9780                                     SelectionDAG &DAG,
9781                                     const TargetLowering &TLI) {
9782   EVT VT;
9783   unsigned AS;
9784 
9785   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9786     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9787       return false;
9788     VT = LD->getMemoryVT();
9789     AS = LD->getAddressSpace();
9790   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9791     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9792       return false;
9793     VT = ST->getMemoryVT();
9794     AS = ST->getAddressSpace();
9795   } else
9796     return false;
9797 
9798   TargetLowering::AddrMode AM;
9799   if (N->getOpcode() == ISD::ADD) {
9800     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9801     if (Offset)
9802       // [reg +/- imm]
9803       AM.BaseOffs = Offset->getSExtValue();
9804     else
9805       // [reg +/- reg]
9806       AM.Scale = 1;
9807   } else if (N->getOpcode() == ISD::SUB) {
9808     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9809     if (Offset)
9810       // [reg +/- imm]
9811       AM.BaseOffs = -Offset->getSExtValue();
9812     else
9813       // [reg +/- reg]
9814       AM.Scale = 1;
9815   } else
9816     return false;
9817 
9818   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9819                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9820 }
9821 
9822 /// Try turning a load/store into a pre-indexed load/store when the base
9823 /// pointer is an add or subtract and it has other uses besides the load/store.
9824 /// After the transformation, the new indexed load/store has effectively folded
9825 /// the add/subtract in and all of its other uses are redirected to the
9826 /// new load/store.
9827 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9828   if (Level < AfterLegalizeDAG)
9829     return false;
9830 
9831   bool isLoad = true;
9832   SDValue Ptr;
9833   EVT VT;
9834   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9835     if (LD->isIndexed())
9836       return false;
9837     VT = LD->getMemoryVT();
9838     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9839         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9840       return false;
9841     Ptr = LD->getBasePtr();
9842   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9843     if (ST->isIndexed())
9844       return false;
9845     VT = ST->getMemoryVT();
9846     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9847         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9848       return false;
9849     Ptr = ST->getBasePtr();
9850     isLoad = false;
9851   } else {
9852     return false;
9853   }
9854 
9855   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9856   // out.  There is no reason to make this a preinc/predec.
9857   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9858       Ptr.getNode()->hasOneUse())
9859     return false;
9860 
9861   // Ask the target to do addressing mode selection.
9862   SDValue BasePtr;
9863   SDValue Offset;
9864   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9865   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9866     return false;
9867 
9868   // Backends without true r+i pre-indexed forms may need to pass a
9869   // constant base with a variable offset so that constant coercion
9870   // will work with the patterns in canonical form.
9871   bool Swapped = false;
9872   if (isa<ConstantSDNode>(BasePtr)) {
9873     std::swap(BasePtr, Offset);
9874     Swapped = true;
9875   }
9876 
9877   // Don't create a indexed load / store with zero offset.
9878   if (isNullConstant(Offset))
9879     return false;
9880 
9881   // Try turning it into a pre-indexed load / store except when:
9882   // 1) The new base ptr is a frame index.
9883   // 2) If N is a store and the new base ptr is either the same as or is a
9884   //    predecessor of the value being stored.
9885   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9886   //    that would create a cycle.
9887   // 4) All uses are load / store ops that use it as old base ptr.
9888 
9889   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9890   // (plus the implicit offset) to a register to preinc anyway.
9891   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9892     return false;
9893 
9894   // Check #2.
9895   if (!isLoad) {
9896     SDValue Val = cast<StoreSDNode>(N)->getValue();
9897     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9898       return false;
9899   }
9900 
9901   // Caches for hasPredecessorHelper.
9902   SmallPtrSet<const SDNode *, 32> Visited;
9903   SmallVector<const SDNode *, 16> Worklist;
9904   Worklist.push_back(N);
9905 
9906   // If the offset is a constant, there may be other adds of constants that
9907   // can be folded with this one. We should do this to avoid having to keep
9908   // a copy of the original base pointer.
9909   SmallVector<SDNode *, 16> OtherUses;
9910   if (isa<ConstantSDNode>(Offset))
9911     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9912                               UE = BasePtr.getNode()->use_end();
9913          UI != UE; ++UI) {
9914       SDUse &Use = UI.getUse();
9915       // Skip the use that is Ptr and uses of other results from BasePtr's
9916       // node (important for nodes that return multiple results).
9917       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9918         continue;
9919 
9920       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9921         continue;
9922 
9923       if (Use.getUser()->getOpcode() != ISD::ADD &&
9924           Use.getUser()->getOpcode() != ISD::SUB) {
9925         OtherUses.clear();
9926         break;
9927       }
9928 
9929       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9930       if (!isa<ConstantSDNode>(Op1)) {
9931         OtherUses.clear();
9932         break;
9933       }
9934 
9935       // FIXME: In some cases, we can be smarter about this.
9936       if (Op1.getValueType() != Offset.getValueType()) {
9937         OtherUses.clear();
9938         break;
9939       }
9940 
9941       OtherUses.push_back(Use.getUser());
9942     }
9943 
9944   if (Swapped)
9945     std::swap(BasePtr, Offset);
9946 
9947   // Now check for #3 and #4.
9948   bool RealUse = false;
9949 
9950   for (SDNode *Use : Ptr.getNode()->uses()) {
9951     if (Use == N)
9952       continue;
9953     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9954       return false;
9955 
9956     // If Ptr may be folded in addressing mode of other use, then it's
9957     // not profitable to do this transformation.
9958     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9959       RealUse = true;
9960   }
9961 
9962   if (!RealUse)
9963     return false;
9964 
9965   SDValue Result;
9966   if (isLoad)
9967     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9968                                 BasePtr, Offset, AM);
9969   else
9970     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9971                                  BasePtr, Offset, AM);
9972   ++PreIndexedNodes;
9973   ++NodesCombined;
9974   DEBUG(dbgs() << "\nReplacing.4 ";
9975         N->dump(&DAG);
9976         dbgs() << "\nWith: ";
9977         Result.getNode()->dump(&DAG);
9978         dbgs() << '\n');
9979   WorklistRemover DeadNodes(*this);
9980   if (isLoad) {
9981     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9982     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9983   } else {
9984     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9985   }
9986 
9987   // Finally, since the node is now dead, remove it from the graph.
9988   deleteAndRecombine(N);
9989 
9990   if (Swapped)
9991     std::swap(BasePtr, Offset);
9992 
9993   // Replace other uses of BasePtr that can be updated to use Ptr
9994   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9995     unsigned OffsetIdx = 1;
9996     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9997       OffsetIdx = 0;
9998     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9999            BasePtr.getNode() && "Expected BasePtr operand");
10000 
10001     // We need to replace ptr0 in the following expression:
10002     //   x0 * offset0 + y0 * ptr0 = t0
10003     // knowing that
10004     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10005     //
10006     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10007     // indexed load/store and the expresion that needs to be re-written.
10008     //
10009     // Therefore, we have:
10010     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10011 
10012     ConstantSDNode *CN =
10013       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
10014     int X0, X1, Y0, Y1;
10015     const APInt &Offset0 = CN->getAPIntValue();
10016     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10017 
10018     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10019     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10020     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10021     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10022 
10023     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10024 
10025     APInt CNV = Offset0;
10026     if (X0 < 0) CNV = -CNV;
10027     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10028     else CNV = CNV - Offset1;
10029 
10030     SDLoc DL(OtherUses[i]);
10031 
10032     // We can now generate the new expression.
10033     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10034     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10035 
10036     SDValue NewUse = DAG.getNode(Opcode,
10037                                  DL,
10038                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10039     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10040     deleteAndRecombine(OtherUses[i]);
10041   }
10042 
10043   // Replace the uses of Ptr with uses of the updated base value.
10044   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10045   deleteAndRecombine(Ptr.getNode());
10046 
10047   return true;
10048 }
10049 
10050 /// Try to combine a load/store with a add/sub of the base pointer node into a
10051 /// post-indexed load/store. The transformation folded the add/subtract into the
10052 /// new indexed load/store effectively and all of its uses are redirected to the
10053 /// new load/store.
10054 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10055   if (Level < AfterLegalizeDAG)
10056     return false;
10057 
10058   bool isLoad = true;
10059   SDValue Ptr;
10060   EVT VT;
10061   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10062     if (LD->isIndexed())
10063       return false;
10064     VT = LD->getMemoryVT();
10065     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10066         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10067       return false;
10068     Ptr = LD->getBasePtr();
10069   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10070     if (ST->isIndexed())
10071       return false;
10072     VT = ST->getMemoryVT();
10073     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10074         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10075       return false;
10076     Ptr = ST->getBasePtr();
10077     isLoad = false;
10078   } else {
10079     return false;
10080   }
10081 
10082   if (Ptr.getNode()->hasOneUse())
10083     return false;
10084 
10085   for (SDNode *Op : Ptr.getNode()->uses()) {
10086     if (Op == N ||
10087         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10088       continue;
10089 
10090     SDValue BasePtr;
10091     SDValue Offset;
10092     ISD::MemIndexedMode AM = ISD::UNINDEXED;
10093     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10094       // Don't create a indexed load / store with zero offset.
10095       if (isNullConstant(Offset))
10096         continue;
10097 
10098       // Try turning it into a post-indexed load / store except when
10099       // 1) All uses are load / store ops that use it as base ptr (and
10100       //    it may be folded as addressing mmode).
10101       // 2) Op must be independent of N, i.e. Op is neither a predecessor
10102       //    nor a successor of N. Otherwise, if Op is folded that would
10103       //    create a cycle.
10104 
10105       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10106         continue;
10107 
10108       // Check for #1.
10109       bool TryNext = false;
10110       for (SDNode *Use : BasePtr.getNode()->uses()) {
10111         if (Use == Ptr.getNode())
10112           continue;
10113 
10114         // If all the uses are load / store addresses, then don't do the
10115         // transformation.
10116         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10117           bool RealUse = false;
10118           for (SDNode *UseUse : Use->uses()) {
10119             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10120               RealUse = true;
10121           }
10122 
10123           if (!RealUse) {
10124             TryNext = true;
10125             break;
10126           }
10127         }
10128       }
10129 
10130       if (TryNext)
10131         continue;
10132 
10133       // Check for #2
10134       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10135         SDValue Result = isLoad
10136           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10137                                BasePtr, Offset, AM)
10138           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10139                                 BasePtr, Offset, AM);
10140         ++PostIndexedNodes;
10141         ++NodesCombined;
10142         DEBUG(dbgs() << "\nReplacing.5 ";
10143               N->dump(&DAG);
10144               dbgs() << "\nWith: ";
10145               Result.getNode()->dump(&DAG);
10146               dbgs() << '\n');
10147         WorklistRemover DeadNodes(*this);
10148         if (isLoad) {
10149           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10150           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10151         } else {
10152           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10153         }
10154 
10155         // Finally, since the node is now dead, remove it from the graph.
10156         deleteAndRecombine(N);
10157 
10158         // Replace the uses of Use with uses of the updated base value.
10159         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10160                                       Result.getValue(isLoad ? 1 : 0));
10161         deleteAndRecombine(Op);
10162         return true;
10163       }
10164     }
10165   }
10166 
10167   return false;
10168 }
10169 
10170 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10171 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10172   ISD::MemIndexedMode AM = LD->getAddressingMode();
10173   assert(AM != ISD::UNINDEXED);
10174   SDValue BP = LD->getOperand(1);
10175   SDValue Inc = LD->getOperand(2);
10176 
10177   // Some backends use TargetConstants for load offsets, but don't expect
10178   // TargetConstants in general ADD nodes. We can convert these constants into
10179   // regular Constants (if the constant is not opaque).
10180   assert((Inc.getOpcode() != ISD::TargetConstant ||
10181           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10182          "Cannot split out indexing using opaque target constants");
10183   if (Inc.getOpcode() == ISD::TargetConstant) {
10184     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10185     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10186                           ConstInc->getValueType(0));
10187   }
10188 
10189   unsigned Opc =
10190       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10191   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10192 }
10193 
10194 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10195   LoadSDNode *LD  = cast<LoadSDNode>(N);
10196   SDValue Chain = LD->getChain();
10197   SDValue Ptr   = LD->getBasePtr();
10198 
10199   // If load is not volatile and there are no uses of the loaded value (and
10200   // the updated indexed value in case of indexed loads), change uses of the
10201   // chain value into uses of the chain input (i.e. delete the dead load).
10202   if (!LD->isVolatile()) {
10203     if (N->getValueType(1) == MVT::Other) {
10204       // Unindexed loads.
10205       if (!N->hasAnyUseOfValue(0)) {
10206         // It's not safe to use the two value CombineTo variant here. e.g.
10207         // v1, chain2 = load chain1, loc
10208         // v2, chain3 = load chain2, loc
10209         // v3         = add v2, c
10210         // Now we replace use of chain2 with chain1.  This makes the second load
10211         // isomorphic to the one we are deleting, and thus makes this load live.
10212         DEBUG(dbgs() << "\nReplacing.6 ";
10213               N->dump(&DAG);
10214               dbgs() << "\nWith chain: ";
10215               Chain.getNode()->dump(&DAG);
10216               dbgs() << "\n");
10217         WorklistRemover DeadNodes(*this);
10218         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10219 
10220         if (N->use_empty())
10221           deleteAndRecombine(N);
10222 
10223         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10224       }
10225     } else {
10226       // Indexed loads.
10227       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10228 
10229       // If this load has an opaque TargetConstant offset, then we cannot split
10230       // the indexing into an add/sub directly (that TargetConstant may not be
10231       // valid for a different type of node, and we cannot convert an opaque
10232       // target constant into a regular constant).
10233       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10234                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10235 
10236       if (!N->hasAnyUseOfValue(0) &&
10237           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10238         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10239         SDValue Index;
10240         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10241           Index = SplitIndexingFromLoad(LD);
10242           // Try to fold the base pointer arithmetic into subsequent loads and
10243           // stores.
10244           AddUsersToWorklist(N);
10245         } else
10246           Index = DAG.getUNDEF(N->getValueType(1));
10247         DEBUG(dbgs() << "\nReplacing.7 ";
10248               N->dump(&DAG);
10249               dbgs() << "\nWith: ";
10250               Undef.getNode()->dump(&DAG);
10251               dbgs() << " and 2 other values\n");
10252         WorklistRemover DeadNodes(*this);
10253         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10254         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10255         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10256         deleteAndRecombine(N);
10257         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10258       }
10259     }
10260   }
10261 
10262   // If this load is directly stored, replace the load value with the stored
10263   // value.
10264   // TODO: Handle store large -> read small portion.
10265   // TODO: Handle TRUNCSTORE/LOADEXT
10266   if (OptLevel != CodeGenOpt::None &&
10267       ISD::isNormalLoad(N) && !LD->isVolatile()) {
10268     // Either a direct store, or a store off of a TokenFactor can be
10269     // forwarded.
10270     if (Chain->getOpcode() == ISD::TokenFactor) {
10271       for (const SDValue &ChainOp : Chain->op_values()) {
10272         if (ISD::isNON_TRUNCStore(ChainOp.getNode())) {
10273           StoreSDNode *PrevST = cast<StoreSDNode>(ChainOp);
10274           if (PrevST->getBasePtr() == Ptr &&
10275               PrevST->getValue().getValueType() == N->getValueType(0))
10276             return CombineTo(N, PrevST->getOperand(1), Chain);
10277         }
10278       }
10279     } else if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10280       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10281       if (PrevST->getBasePtr() == Ptr &&
10282           PrevST->getValue().getValueType() == N->getValueType(0))
10283         return CombineTo(N, PrevST->getOperand(1), Chain);
10284     }
10285   }
10286 
10287   // Try to infer better alignment information than the load already has.
10288   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10289     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10290       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10291         SDValue NewLoad = DAG.getExtLoad(
10292             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10293             LD->getPointerInfo(), LD->getMemoryVT(), Align,
10294             LD->getMemOperand()->getFlags(), LD->getAAInfo());
10295         if (NewLoad.getNode() != N)
10296           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10297       }
10298     }
10299   }
10300 
10301   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10302                                                   : DAG.getSubtarget().useAA();
10303 #ifndef NDEBUG
10304   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10305       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10306     UseAA = false;
10307 #endif
10308   if (UseAA && LD->isUnindexed()) {
10309     // Walk up chain skipping non-aliasing memory nodes.
10310     SDValue BetterChain = FindBetterChain(N, Chain);
10311 
10312     // If there is a better chain.
10313     if (Chain != BetterChain) {
10314       SDValue ReplLoad;
10315 
10316       // Replace the chain to void dependency.
10317       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10318         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10319                                BetterChain, Ptr, LD->getMemOperand());
10320       } else {
10321         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10322                                   LD->getValueType(0),
10323                                   BetterChain, Ptr, LD->getMemoryVT(),
10324                                   LD->getMemOperand());
10325       }
10326 
10327       // Create token factor to keep old chain connected.
10328       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10329                                   MVT::Other, Chain, ReplLoad.getValue(1));
10330 
10331       // Make sure the new and old chains are cleaned up.
10332       AddToWorklist(Token.getNode());
10333 
10334       // Replace uses with load result and token factor. Don't add users
10335       // to work list.
10336       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10337     }
10338   }
10339 
10340   // Try transforming N to an indexed load.
10341   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10342     return SDValue(N, 0);
10343 
10344   // Try to slice up N to more direct loads if the slices are mapped to
10345   // different register banks or pairing can take place.
10346   if (SliceUpLoad(N))
10347     return SDValue(N, 0);
10348 
10349   return SDValue();
10350 }
10351 
10352 namespace {
10353 /// \brief Helper structure used to slice a load in smaller loads.
10354 /// Basically a slice is obtained from the following sequence:
10355 /// Origin = load Ty1, Base
10356 /// Shift = srl Ty1 Origin, CstTy Amount
10357 /// Inst = trunc Shift to Ty2
10358 ///
10359 /// Then, it will be rewriten into:
10360 /// Slice = load SliceTy, Base + SliceOffset
10361 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10362 ///
10363 /// SliceTy is deduced from the number of bits that are actually used to
10364 /// build Inst.
10365 struct LoadedSlice {
10366   /// \brief Helper structure used to compute the cost of a slice.
10367   struct Cost {
10368     /// Are we optimizing for code size.
10369     bool ForCodeSize;
10370     /// Various cost.
10371     unsigned Loads;
10372     unsigned Truncates;
10373     unsigned CrossRegisterBanksCopies;
10374     unsigned ZExts;
10375     unsigned Shift;
10376 
10377     Cost(bool ForCodeSize = false)
10378         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10379           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10380 
10381     /// \brief Get the cost of one isolated slice.
10382     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10383         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10384           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10385       EVT TruncType = LS.Inst->getValueType(0);
10386       EVT LoadedType = LS.getLoadedType();
10387       if (TruncType != LoadedType &&
10388           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10389         ZExts = 1;
10390     }
10391 
10392     /// \brief Account for slicing gain in the current cost.
10393     /// Slicing provide a few gains like removing a shift or a
10394     /// truncate. This method allows to grow the cost of the original
10395     /// load with the gain from this slice.
10396     void addSliceGain(const LoadedSlice &LS) {
10397       // Each slice saves a truncate.
10398       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10399       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10400                               LS.Inst->getValueType(0)))
10401         ++Truncates;
10402       // If there is a shift amount, this slice gets rid of it.
10403       if (LS.Shift)
10404         ++Shift;
10405       // If this slice can merge a cross register bank copy, account for it.
10406       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10407         ++CrossRegisterBanksCopies;
10408     }
10409 
10410     Cost &operator+=(const Cost &RHS) {
10411       Loads += RHS.Loads;
10412       Truncates += RHS.Truncates;
10413       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10414       ZExts += RHS.ZExts;
10415       Shift += RHS.Shift;
10416       return *this;
10417     }
10418 
10419     bool operator==(const Cost &RHS) const {
10420       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10421              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10422              ZExts == RHS.ZExts && Shift == RHS.Shift;
10423     }
10424 
10425     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10426 
10427     bool operator<(const Cost &RHS) const {
10428       // Assume cross register banks copies are as expensive as loads.
10429       // FIXME: Do we want some more target hooks?
10430       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10431       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10432       // Unless we are optimizing for code size, consider the
10433       // expensive operation first.
10434       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10435         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10436       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10437              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10438     }
10439 
10440     bool operator>(const Cost &RHS) const { return RHS < *this; }
10441 
10442     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10443 
10444     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10445   };
10446   // The last instruction that represent the slice. This should be a
10447   // truncate instruction.
10448   SDNode *Inst;
10449   // The original load instruction.
10450   LoadSDNode *Origin;
10451   // The right shift amount in bits from the original load.
10452   unsigned Shift;
10453   // The DAG from which Origin came from.
10454   // This is used to get some contextual information about legal types, etc.
10455   SelectionDAG *DAG;
10456 
10457   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10458               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10459       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10460 
10461   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10462   /// \return Result is \p BitWidth and has used bits set to 1 and
10463   ///         not used bits set to 0.
10464   APInt getUsedBits() const {
10465     // Reproduce the trunc(lshr) sequence:
10466     // - Start from the truncated value.
10467     // - Zero extend to the desired bit width.
10468     // - Shift left.
10469     assert(Origin && "No original load to compare against.");
10470     unsigned BitWidth = Origin->getValueSizeInBits(0);
10471     assert(Inst && "This slice is not bound to an instruction");
10472     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10473            "Extracted slice is bigger than the whole type!");
10474     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10475     UsedBits.setAllBits();
10476     UsedBits = UsedBits.zext(BitWidth);
10477     UsedBits <<= Shift;
10478     return UsedBits;
10479   }
10480 
10481   /// \brief Get the size of the slice to be loaded in bytes.
10482   unsigned getLoadedSize() const {
10483     unsigned SliceSize = getUsedBits().countPopulation();
10484     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10485     return SliceSize / 8;
10486   }
10487 
10488   /// \brief Get the type that will be loaded for this slice.
10489   /// Note: This may not be the final type for the slice.
10490   EVT getLoadedType() const {
10491     assert(DAG && "Missing context");
10492     LLVMContext &Ctxt = *DAG->getContext();
10493     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10494   }
10495 
10496   /// \brief Get the alignment of the load used for this slice.
10497   unsigned getAlignment() const {
10498     unsigned Alignment = Origin->getAlignment();
10499     unsigned Offset = getOffsetFromBase();
10500     if (Offset != 0)
10501       Alignment = MinAlign(Alignment, Alignment + Offset);
10502     return Alignment;
10503   }
10504 
10505   /// \brief Check if this slice can be rewritten with legal operations.
10506   bool isLegal() const {
10507     // An invalid slice is not legal.
10508     if (!Origin || !Inst || !DAG)
10509       return false;
10510 
10511     // Offsets are for indexed load only, we do not handle that.
10512     if (!Origin->getOffset().isUndef())
10513       return false;
10514 
10515     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10516 
10517     // Check that the type is legal.
10518     EVT SliceType = getLoadedType();
10519     if (!TLI.isTypeLegal(SliceType))
10520       return false;
10521 
10522     // Check that the load is legal for this type.
10523     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10524       return false;
10525 
10526     // Check that the offset can be computed.
10527     // 1. Check its type.
10528     EVT PtrType = Origin->getBasePtr().getValueType();
10529     if (PtrType == MVT::Untyped || PtrType.isExtended())
10530       return false;
10531 
10532     // 2. Check that it fits in the immediate.
10533     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10534       return false;
10535 
10536     // 3. Check that the computation is legal.
10537     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10538       return false;
10539 
10540     // Check that the zext is legal if it needs one.
10541     EVT TruncateType = Inst->getValueType(0);
10542     if (TruncateType != SliceType &&
10543         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10544       return false;
10545 
10546     return true;
10547   }
10548 
10549   /// \brief Get the offset in bytes of this slice in the original chunk of
10550   /// bits.
10551   /// \pre DAG != nullptr.
10552   uint64_t getOffsetFromBase() const {
10553     assert(DAG && "Missing context.");
10554     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10555     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10556     uint64_t Offset = Shift / 8;
10557     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10558     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10559            "The size of the original loaded type is not a multiple of a"
10560            " byte.");
10561     // If Offset is bigger than TySizeInBytes, it means we are loading all
10562     // zeros. This should have been optimized before in the process.
10563     assert(TySizeInBytes > Offset &&
10564            "Invalid shift amount for given loaded size");
10565     if (IsBigEndian)
10566       Offset = TySizeInBytes - Offset - getLoadedSize();
10567     return Offset;
10568   }
10569 
10570   /// \brief Generate the sequence of instructions to load the slice
10571   /// represented by this object and redirect the uses of this slice to
10572   /// this new sequence of instructions.
10573   /// \pre this->Inst && this->Origin are valid Instructions and this
10574   /// object passed the legal check: LoadedSlice::isLegal returned true.
10575   /// \return The last instruction of the sequence used to load the slice.
10576   SDValue loadSlice() const {
10577     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10578     const SDValue &OldBaseAddr = Origin->getBasePtr();
10579     SDValue BaseAddr = OldBaseAddr;
10580     // Get the offset in that chunk of bytes w.r.t. the endianness.
10581     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10582     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10583     if (Offset) {
10584       // BaseAddr = BaseAddr + Offset.
10585       EVT ArithType = BaseAddr.getValueType();
10586       SDLoc DL(Origin);
10587       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10588                               DAG->getConstant(Offset, DL, ArithType));
10589     }
10590 
10591     // Create the type of the loaded slice according to its size.
10592     EVT SliceType = getLoadedType();
10593 
10594     // Create the load for the slice.
10595     SDValue LastInst =
10596         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10597                      Origin->getPointerInfo().getWithOffset(Offset),
10598                      getAlignment(), Origin->getMemOperand()->getFlags());
10599     // If the final type is not the same as the loaded type, this means that
10600     // we have to pad with zero. Create a zero extend for that.
10601     EVT FinalType = Inst->getValueType(0);
10602     if (SliceType != FinalType)
10603       LastInst =
10604           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10605     return LastInst;
10606   }
10607 
10608   /// \brief Check if this slice can be merged with an expensive cross register
10609   /// bank copy. E.g.,
10610   /// i = load i32
10611   /// f = bitcast i32 i to float
10612   bool canMergeExpensiveCrossRegisterBankCopy() const {
10613     if (!Inst || !Inst->hasOneUse())
10614       return false;
10615     SDNode *Use = *Inst->use_begin();
10616     if (Use->getOpcode() != ISD::BITCAST)
10617       return false;
10618     assert(DAG && "Missing context");
10619     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10620     EVT ResVT = Use->getValueType(0);
10621     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10622     const TargetRegisterClass *ArgRC =
10623         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10624     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10625       return false;
10626 
10627     // At this point, we know that we perform a cross-register-bank copy.
10628     // Check if it is expensive.
10629     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10630     // Assume bitcasts are cheap, unless both register classes do not
10631     // explicitly share a common sub class.
10632     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10633       return false;
10634 
10635     // Check if it will be merged with the load.
10636     // 1. Check the alignment constraint.
10637     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10638         ResVT.getTypeForEVT(*DAG->getContext()));
10639 
10640     if (RequiredAlignment > getAlignment())
10641       return false;
10642 
10643     // 2. Check that the load is a legal operation for that type.
10644     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10645       return false;
10646 
10647     // 3. Check that we do not have a zext in the way.
10648     if (Inst->getValueType(0) != getLoadedType())
10649       return false;
10650 
10651     return true;
10652   }
10653 };
10654 }
10655 
10656 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10657 /// \p UsedBits looks like 0..0 1..1 0..0.
10658 static bool areUsedBitsDense(const APInt &UsedBits) {
10659   // If all the bits are one, this is dense!
10660   if (UsedBits.isAllOnesValue())
10661     return true;
10662 
10663   // Get rid of the unused bits on the right.
10664   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10665   // Get rid of the unused bits on the left.
10666   if (NarrowedUsedBits.countLeadingZeros())
10667     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10668   // Check that the chunk of bits is completely used.
10669   return NarrowedUsedBits.isAllOnesValue();
10670 }
10671 
10672 /// \brief Check whether or not \p First and \p Second are next to each other
10673 /// in memory. This means that there is no hole between the bits loaded
10674 /// by \p First and the bits loaded by \p Second.
10675 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10676                                      const LoadedSlice &Second) {
10677   assert(First.Origin == Second.Origin && First.Origin &&
10678          "Unable to match different memory origins.");
10679   APInt UsedBits = First.getUsedBits();
10680   assert((UsedBits & Second.getUsedBits()) == 0 &&
10681          "Slices are not supposed to overlap.");
10682   UsedBits |= Second.getUsedBits();
10683   return areUsedBitsDense(UsedBits);
10684 }
10685 
10686 /// \brief Adjust the \p GlobalLSCost according to the target
10687 /// paring capabilities and the layout of the slices.
10688 /// \pre \p GlobalLSCost should account for at least as many loads as
10689 /// there is in the slices in \p LoadedSlices.
10690 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10691                                  LoadedSlice::Cost &GlobalLSCost) {
10692   unsigned NumberOfSlices = LoadedSlices.size();
10693   // If there is less than 2 elements, no pairing is possible.
10694   if (NumberOfSlices < 2)
10695     return;
10696 
10697   // Sort the slices so that elements that are likely to be next to each
10698   // other in memory are next to each other in the list.
10699   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10700             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10701     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10702     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10703   });
10704   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10705   // First (resp. Second) is the first (resp. Second) potentially candidate
10706   // to be placed in a paired load.
10707   const LoadedSlice *First = nullptr;
10708   const LoadedSlice *Second = nullptr;
10709   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10710                 // Set the beginning of the pair.
10711                                                            First = Second) {
10712 
10713     Second = &LoadedSlices[CurrSlice];
10714 
10715     // If First is NULL, it means we start a new pair.
10716     // Get to the next slice.
10717     if (!First)
10718       continue;
10719 
10720     EVT LoadedType = First->getLoadedType();
10721 
10722     // If the types of the slices are different, we cannot pair them.
10723     if (LoadedType != Second->getLoadedType())
10724       continue;
10725 
10726     // Check if the target supplies paired loads for this type.
10727     unsigned RequiredAlignment = 0;
10728     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10729       // move to the next pair, this type is hopeless.
10730       Second = nullptr;
10731       continue;
10732     }
10733     // Check if we meet the alignment requirement.
10734     if (RequiredAlignment > First->getAlignment())
10735       continue;
10736 
10737     // Check that both loads are next to each other in memory.
10738     if (!areSlicesNextToEachOther(*First, *Second))
10739       continue;
10740 
10741     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10742     --GlobalLSCost.Loads;
10743     // Move to the next pair.
10744     Second = nullptr;
10745   }
10746 }
10747 
10748 /// \brief Check the profitability of all involved LoadedSlice.
10749 /// Currently, it is considered profitable if there is exactly two
10750 /// involved slices (1) which are (2) next to each other in memory, and
10751 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10752 ///
10753 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10754 /// the elements themselves.
10755 ///
10756 /// FIXME: When the cost model will be mature enough, we can relax
10757 /// constraints (1) and (2).
10758 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10759                                 const APInt &UsedBits, bool ForCodeSize) {
10760   unsigned NumberOfSlices = LoadedSlices.size();
10761   if (StressLoadSlicing)
10762     return NumberOfSlices > 1;
10763 
10764   // Check (1).
10765   if (NumberOfSlices != 2)
10766     return false;
10767 
10768   // Check (2).
10769   if (!areUsedBitsDense(UsedBits))
10770     return false;
10771 
10772   // Check (3).
10773   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10774   // The original code has one big load.
10775   OrigCost.Loads = 1;
10776   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10777     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10778     // Accumulate the cost of all the slices.
10779     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10780     GlobalSlicingCost += SliceCost;
10781 
10782     // Account as cost in the original configuration the gain obtained
10783     // with the current slices.
10784     OrigCost.addSliceGain(LS);
10785   }
10786 
10787   // If the target supports paired load, adjust the cost accordingly.
10788   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10789   return OrigCost > GlobalSlicingCost;
10790 }
10791 
10792 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10793 /// operations, split it in the various pieces being extracted.
10794 ///
10795 /// This sort of thing is introduced by SROA.
10796 /// This slicing takes care not to insert overlapping loads.
10797 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10798 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10799   if (Level < AfterLegalizeDAG)
10800     return false;
10801 
10802   LoadSDNode *LD = cast<LoadSDNode>(N);
10803   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10804       !LD->getValueType(0).isInteger())
10805     return false;
10806 
10807   // Keep track of already used bits to detect overlapping values.
10808   // In that case, we will just abort the transformation.
10809   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10810 
10811   SmallVector<LoadedSlice, 4> LoadedSlices;
10812 
10813   // Check if this load is used as several smaller chunks of bits.
10814   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10815   // of computation for each trunc.
10816   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10817        UI != UIEnd; ++UI) {
10818     // Skip the uses of the chain.
10819     if (UI.getUse().getResNo() != 0)
10820       continue;
10821 
10822     SDNode *User = *UI;
10823     unsigned Shift = 0;
10824 
10825     // Check if this is a trunc(lshr).
10826     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10827         isa<ConstantSDNode>(User->getOperand(1))) {
10828       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10829       User = *User->use_begin();
10830     }
10831 
10832     // At this point, User is a Truncate, iff we encountered, trunc or
10833     // trunc(lshr).
10834     if (User->getOpcode() != ISD::TRUNCATE)
10835       return false;
10836 
10837     // The width of the type must be a power of 2 and greater than 8-bits.
10838     // Otherwise the load cannot be represented in LLVM IR.
10839     // Moreover, if we shifted with a non-8-bits multiple, the slice
10840     // will be across several bytes. We do not support that.
10841     unsigned Width = User->getValueSizeInBits(0);
10842     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10843       return 0;
10844 
10845     // Build the slice for this chain of computations.
10846     LoadedSlice LS(User, LD, Shift, &DAG);
10847     APInt CurrentUsedBits = LS.getUsedBits();
10848 
10849     // Check if this slice overlaps with another.
10850     if ((CurrentUsedBits & UsedBits) != 0)
10851       return false;
10852     // Update the bits used globally.
10853     UsedBits |= CurrentUsedBits;
10854 
10855     // Check if the new slice would be legal.
10856     if (!LS.isLegal())
10857       return false;
10858 
10859     // Record the slice.
10860     LoadedSlices.push_back(LS);
10861   }
10862 
10863   // Abort slicing if it does not seem to be profitable.
10864   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10865     return false;
10866 
10867   ++SlicedLoads;
10868 
10869   // Rewrite each chain to use an independent load.
10870   // By construction, each chain can be represented by a unique load.
10871 
10872   // Prepare the argument for the new token factor for all the slices.
10873   SmallVector<SDValue, 8> ArgChains;
10874   for (SmallVectorImpl<LoadedSlice>::const_iterator
10875            LSIt = LoadedSlices.begin(),
10876            LSItEnd = LoadedSlices.end();
10877        LSIt != LSItEnd; ++LSIt) {
10878     SDValue SliceInst = LSIt->loadSlice();
10879     CombineTo(LSIt->Inst, SliceInst, true);
10880     if (SliceInst.getOpcode() != ISD::LOAD)
10881       SliceInst = SliceInst.getOperand(0);
10882     assert(SliceInst->getOpcode() == ISD::LOAD &&
10883            "It takes more than a zext to get to the loaded slice!!");
10884     ArgChains.push_back(SliceInst.getValue(1));
10885   }
10886 
10887   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10888                               ArgChains);
10889   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10890   return true;
10891 }
10892 
10893 /// Check to see if V is (and load (ptr), imm), where the load is having
10894 /// specific bytes cleared out.  If so, return the byte size being masked out
10895 /// and the shift amount.
10896 static std::pair<unsigned, unsigned>
10897 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10898   std::pair<unsigned, unsigned> Result(0, 0);
10899 
10900   // Check for the structure we're looking for.
10901   if (V->getOpcode() != ISD::AND ||
10902       !isa<ConstantSDNode>(V->getOperand(1)) ||
10903       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10904     return Result;
10905 
10906   // Check the chain and pointer.
10907   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10908   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10909 
10910   // The store should be chained directly to the load or be an operand of a
10911   // tokenfactor.
10912   if (LD == Chain.getNode())
10913     ; // ok.
10914   else if (Chain->getOpcode() != ISD::TokenFactor)
10915     return Result; // Fail.
10916   else {
10917     bool isOk = false;
10918     for (const SDValue &ChainOp : Chain->op_values())
10919       if (ChainOp.getNode() == LD) {
10920         isOk = true;
10921         break;
10922       }
10923     if (!isOk) return Result;
10924   }
10925 
10926   // This only handles simple types.
10927   if (V.getValueType() != MVT::i16 &&
10928       V.getValueType() != MVT::i32 &&
10929       V.getValueType() != MVT::i64)
10930     return Result;
10931 
10932   // Check the constant mask.  Invert it so that the bits being masked out are
10933   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10934   // follow the sign bit for uniformity.
10935   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10936   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10937   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10938   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10939   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10940   if (NotMaskLZ == 64) return Result;  // All zero mask.
10941 
10942   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10943   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10944     return Result;
10945 
10946   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10947   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10948     NotMaskLZ -= 64-V.getValueSizeInBits();
10949 
10950   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10951   switch (MaskedBytes) {
10952   case 1:
10953   case 2:
10954   case 4: break;
10955   default: return Result; // All one mask, or 5-byte mask.
10956   }
10957 
10958   // Verify that the first bit starts at a multiple of mask so that the access
10959   // is aligned the same as the access width.
10960   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10961 
10962   Result.first = MaskedBytes;
10963   Result.second = NotMaskTZ/8;
10964   return Result;
10965 }
10966 
10967 
10968 /// Check to see if IVal is something that provides a value as specified by
10969 /// MaskInfo. If so, replace the specified store with a narrower store of
10970 /// truncated IVal.
10971 static SDNode *
10972 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10973                                 SDValue IVal, StoreSDNode *St,
10974                                 DAGCombiner *DC) {
10975   unsigned NumBytes = MaskInfo.first;
10976   unsigned ByteShift = MaskInfo.second;
10977   SelectionDAG &DAG = DC->getDAG();
10978 
10979   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10980   // that uses this.  If not, this is not a replacement.
10981   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10982                                   ByteShift*8, (ByteShift+NumBytes)*8);
10983   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10984 
10985   // Check that it is legal on the target to do this.  It is legal if the new
10986   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10987   // legalization.
10988   MVT VT = MVT::getIntegerVT(NumBytes*8);
10989   if (!DC->isTypeLegal(VT))
10990     return nullptr;
10991 
10992   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10993   // shifted by ByteShift and truncated down to NumBytes.
10994   if (ByteShift) {
10995     SDLoc DL(IVal);
10996     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10997                        DAG.getConstant(ByteShift*8, DL,
10998                                     DC->getShiftAmountTy(IVal.getValueType())));
10999   }
11000 
11001   // Figure out the offset for the store and the alignment of the access.
11002   unsigned StOffset;
11003   unsigned NewAlign = St->getAlignment();
11004 
11005   if (DAG.getDataLayout().isLittleEndian())
11006     StOffset = ByteShift;
11007   else
11008     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11009 
11010   SDValue Ptr = St->getBasePtr();
11011   if (StOffset) {
11012     SDLoc DL(IVal);
11013     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11014                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11015     NewAlign = MinAlign(NewAlign, StOffset);
11016   }
11017 
11018   // Truncate down to the new size.
11019   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11020 
11021   ++OpsNarrowed;
11022   return DAG
11023       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11024                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11025       .getNode();
11026 }
11027 
11028 
11029 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11030 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11031 /// narrowing the load and store if it would end up being a win for performance
11032 /// or code size.
11033 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11034   StoreSDNode *ST  = cast<StoreSDNode>(N);
11035   if (ST->isVolatile())
11036     return SDValue();
11037 
11038   SDValue Chain = ST->getChain();
11039   SDValue Value = ST->getValue();
11040   SDValue Ptr   = ST->getBasePtr();
11041   EVT VT = Value.getValueType();
11042 
11043   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11044     return SDValue();
11045 
11046   unsigned Opc = Value.getOpcode();
11047 
11048   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11049   // is a byte mask indicating a consecutive number of bytes, check to see if
11050   // Y is known to provide just those bytes.  If so, we try to replace the
11051   // load + replace + store sequence with a single (narrower) store, which makes
11052   // the load dead.
11053   if (Opc == ISD::OR) {
11054     std::pair<unsigned, unsigned> MaskedLoad;
11055     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11056     if (MaskedLoad.first)
11057       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11058                                                   Value.getOperand(1), ST,this))
11059         return SDValue(NewST, 0);
11060 
11061     // Or is commutative, so try swapping X and Y.
11062     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11063     if (MaskedLoad.first)
11064       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11065                                                   Value.getOperand(0), ST,this))
11066         return SDValue(NewST, 0);
11067   }
11068 
11069   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11070       Value.getOperand(1).getOpcode() != ISD::Constant)
11071     return SDValue();
11072 
11073   SDValue N0 = Value.getOperand(0);
11074   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11075       Chain == SDValue(N0.getNode(), 1)) {
11076     LoadSDNode *LD = cast<LoadSDNode>(N0);
11077     if (LD->getBasePtr() != Ptr ||
11078         LD->getPointerInfo().getAddrSpace() !=
11079         ST->getPointerInfo().getAddrSpace())
11080       return SDValue();
11081 
11082     // Find the type to narrow it the load / op / store to.
11083     SDValue N1 = Value.getOperand(1);
11084     unsigned BitWidth = N1.getValueSizeInBits();
11085     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11086     if (Opc == ISD::AND)
11087       Imm ^= APInt::getAllOnesValue(BitWidth);
11088     if (Imm == 0 || Imm.isAllOnesValue())
11089       return SDValue();
11090     unsigned ShAmt = Imm.countTrailingZeros();
11091     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11092     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11093     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11094     // The narrowing should be profitable, the load/store operation should be
11095     // legal (or custom) and the store size should be equal to the NewVT width.
11096     while (NewBW < BitWidth &&
11097            (NewVT.getStoreSizeInBits() != NewBW ||
11098             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11099             !TLI.isNarrowingProfitable(VT, NewVT))) {
11100       NewBW = NextPowerOf2(NewBW);
11101       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11102     }
11103     if (NewBW >= BitWidth)
11104       return SDValue();
11105 
11106     // If the lsb changed does not start at the type bitwidth boundary,
11107     // start at the previous one.
11108     if (ShAmt % NewBW)
11109       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11110     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11111                                    std::min(BitWidth, ShAmt + NewBW));
11112     if ((Imm & Mask) == Imm) {
11113       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11114       if (Opc == ISD::AND)
11115         NewImm ^= APInt::getAllOnesValue(NewBW);
11116       uint64_t PtrOff = ShAmt / 8;
11117       // For big endian targets, we need to adjust the offset to the pointer to
11118       // load the correct bytes.
11119       if (DAG.getDataLayout().isBigEndian())
11120         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11121 
11122       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11123       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11124       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11125         return SDValue();
11126 
11127       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11128                                    Ptr.getValueType(), Ptr,
11129                                    DAG.getConstant(PtrOff, SDLoc(LD),
11130                                                    Ptr.getValueType()));
11131       SDValue NewLD =
11132           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11133                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11134                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
11135       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11136                                    DAG.getConstant(NewImm, SDLoc(Value),
11137                                                    NewVT));
11138       SDValue NewST =
11139           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11140                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11141 
11142       AddToWorklist(NewPtr.getNode());
11143       AddToWorklist(NewLD.getNode());
11144       AddToWorklist(NewVal.getNode());
11145       WorklistRemover DeadNodes(*this);
11146       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11147       ++OpsNarrowed;
11148       return NewST;
11149     }
11150   }
11151 
11152   return SDValue();
11153 }
11154 
11155 /// For a given floating point load / store pair, if the load value isn't used
11156 /// by any other operations, then consider transforming the pair to integer
11157 /// load / store operations if the target deems the transformation profitable.
11158 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11159   StoreSDNode *ST  = cast<StoreSDNode>(N);
11160   SDValue Chain = ST->getChain();
11161   SDValue Value = ST->getValue();
11162   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11163       Value.hasOneUse() &&
11164       Chain == SDValue(Value.getNode(), 1)) {
11165     LoadSDNode *LD = cast<LoadSDNode>(Value);
11166     EVT VT = LD->getMemoryVT();
11167     if (!VT.isFloatingPoint() ||
11168         VT != ST->getMemoryVT() ||
11169         LD->isNonTemporal() ||
11170         ST->isNonTemporal() ||
11171         LD->getPointerInfo().getAddrSpace() != 0 ||
11172         ST->getPointerInfo().getAddrSpace() != 0)
11173       return SDValue();
11174 
11175     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11176     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11177         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11178         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11179         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11180       return SDValue();
11181 
11182     unsigned LDAlign = LD->getAlignment();
11183     unsigned STAlign = ST->getAlignment();
11184     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11185     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11186     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11187       return SDValue();
11188 
11189     SDValue NewLD =
11190         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11191                     LD->getPointerInfo(), LDAlign);
11192 
11193     SDValue NewST =
11194         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11195                      ST->getPointerInfo(), STAlign);
11196 
11197     AddToWorklist(NewLD.getNode());
11198     AddToWorklist(NewST.getNode());
11199     WorklistRemover DeadNodes(*this);
11200     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11201     ++LdStFP2Int;
11202     return NewST;
11203   }
11204 
11205   return SDValue();
11206 }
11207 
11208 namespace {
11209 /// Helper struct to parse and store a memory address as base + index + offset.
11210 /// We ignore sign extensions when it is safe to do so.
11211 /// The following two expressions are not equivalent. To differentiate we need
11212 /// to store whether there was a sign extension involved in the index
11213 /// computation.
11214 ///  (load (i64 add (i64 copyfromreg %c)
11215 ///                 (i64 signextend (add (i8 load %index)
11216 ///                                      (i8 1))))
11217 /// vs
11218 ///
11219 /// (load (i64 add (i64 copyfromreg %c)
11220 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11221 ///                                         (i32 1)))))
11222 struct BaseIndexOffset {
11223   SDValue Base;
11224   SDValue Index;
11225   int64_t Offset;
11226   bool IsIndexSignExt;
11227 
11228   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11229 
11230   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11231                   bool IsIndexSignExt) :
11232     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11233 
11234   bool equalBaseIndex(const BaseIndexOffset &Other) {
11235     return Other.Base == Base && Other.Index == Index &&
11236       Other.IsIndexSignExt == IsIndexSignExt;
11237   }
11238 
11239   /// Parses tree in Ptr for base, index, offset addresses.
11240   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11241     bool IsIndexSignExt = false;
11242 
11243     // Split up a folded GlobalAddress+Offset into its component parts.
11244     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11245       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11246         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11247                                                     SDLoc(GA),
11248                                                     GA->getValueType(0),
11249                                                     /*Offset=*/0,
11250                                                     /*isTargetGA=*/false,
11251                                                     GA->getTargetFlags()),
11252                                SDValue(),
11253                                GA->getOffset(),
11254                                IsIndexSignExt);
11255       }
11256 
11257     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11258     // instruction, then it could be just the BASE or everything else we don't
11259     // know how to handle. Just use Ptr as BASE and give up.
11260     if (Ptr->getOpcode() != ISD::ADD)
11261       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11262 
11263     // We know that we have at least an ADD instruction. Try to pattern match
11264     // the simple case of BASE + OFFSET.
11265     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11266       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11267       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11268                               IsIndexSignExt);
11269     }
11270 
11271     // Inside a loop the current BASE pointer is calculated using an ADD and a
11272     // MUL instruction. In this case Ptr is the actual BASE pointer.
11273     // (i64 add (i64 %array_ptr)
11274     //          (i64 mul (i64 %induction_var)
11275     //                   (i64 %element_size)))
11276     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11277       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11278 
11279     // Look at Base + Index + Offset cases.
11280     SDValue Base = Ptr->getOperand(0);
11281     SDValue IndexOffset = Ptr->getOperand(1);
11282 
11283     // Skip signextends.
11284     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11285       IndexOffset = IndexOffset->getOperand(0);
11286       IsIndexSignExt = true;
11287     }
11288 
11289     // Either the case of Base + Index (no offset) or something else.
11290     if (IndexOffset->getOpcode() != ISD::ADD)
11291       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11292 
11293     // Now we have the case of Base + Index + offset.
11294     SDValue Index = IndexOffset->getOperand(0);
11295     SDValue Offset = IndexOffset->getOperand(1);
11296 
11297     if (!isa<ConstantSDNode>(Offset))
11298       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11299 
11300     // Ignore signextends.
11301     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11302       Index = Index->getOperand(0);
11303       IsIndexSignExt = true;
11304     } else IsIndexSignExt = false;
11305 
11306     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11307     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11308   }
11309 };
11310 } // namespace
11311 
11312 // This is a helper function for visitMUL to check the profitability
11313 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11314 // MulNode is the original multiply, AddNode is (add x, c1),
11315 // and ConstNode is c2.
11316 //
11317 // If the (add x, c1) has multiple uses, we could increase
11318 // the number of adds if we make this transformation.
11319 // It would only be worth doing this if we can remove a
11320 // multiply in the process. Check for that here.
11321 // To illustrate:
11322 //     (A + c1) * c3
11323 //     (A + c2) * c3
11324 // We're checking for cases where we have common "c3 * A" expressions.
11325 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11326                                               SDValue &AddNode,
11327                                               SDValue &ConstNode) {
11328   APInt Val;
11329 
11330   // If the add only has one use, this would be OK to do.
11331   if (AddNode.getNode()->hasOneUse())
11332     return true;
11333 
11334   // Walk all the users of the constant with which we're multiplying.
11335   for (SDNode *Use : ConstNode->uses()) {
11336 
11337     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11338       continue;
11339 
11340     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11341       SDNode *OtherOp;
11342       SDNode *MulVar = AddNode.getOperand(0).getNode();
11343 
11344       // OtherOp is what we're multiplying against the constant.
11345       if (Use->getOperand(0) == ConstNode)
11346         OtherOp = Use->getOperand(1).getNode();
11347       else
11348         OtherOp = Use->getOperand(0).getNode();
11349 
11350       // Check to see if multiply is with the same operand of our "add".
11351       //
11352       //     ConstNode  = CONST
11353       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11354       //     ...
11355       //     AddNode  = (A + c1)  <-- MulVar is A.
11356       //         = AddNode * ConstNode   <-- current visiting instruction.
11357       //
11358       // If we make this transformation, we will have a common
11359       // multiply (ConstNode * A) that we can save.
11360       if (OtherOp == MulVar)
11361         return true;
11362 
11363       // Now check to see if a future expansion will give us a common
11364       // multiply.
11365       //
11366       //     ConstNode  = CONST
11367       //     AddNode    = (A + c1)
11368       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11369       //     ...
11370       //     OtherOp = (A + c2)
11371       //     Use     = OtherOp * ConstNode <-- visiting Use.
11372       //
11373       // If we make this transformation, we will have a common
11374       // multiply (CONST * A) after we also do the same transformation
11375       // to the "t2" instruction.
11376       if (OtherOp->getOpcode() == ISD::ADD &&
11377           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11378           OtherOp->getOperand(0).getNode() == MulVar)
11379         return true;
11380     }
11381   }
11382 
11383   // Didn't find a case where this would be profitable.
11384   return false;
11385 }
11386 
11387 SDValue DAGCombiner::getMergedConstantVectorStore(
11388     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11389     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11390   SmallVector<SDValue, 8> BuildVector;
11391 
11392   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11393     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11394     Chains.push_back(St->getChain());
11395     BuildVector.push_back(St->getValue());
11396   }
11397 
11398   return DAG.getBuildVector(Ty, SL, BuildVector);
11399 }
11400 
11401 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11402                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11403                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11404   // Make sure we have something to merge.
11405   if (NumStores < 2)
11406     return false;
11407 
11408   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11409   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11410   unsigned LatestNodeUsed = 0;
11411 
11412   for (unsigned i=0; i < NumStores; ++i) {
11413     // Find a chain for the new wide-store operand. Notice that some
11414     // of the store nodes that we found may not be selected for inclusion
11415     // in the wide store. The chain we use needs to be the chain of the
11416     // latest store node which is *used* and replaced by the wide store.
11417     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11418       LatestNodeUsed = i;
11419   }
11420 
11421   SmallVector<SDValue, 8> Chains;
11422 
11423   // The latest Node in the DAG.
11424   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11425   SDLoc DL(StoreNodes[0].MemNode);
11426 
11427   SDValue StoredVal;
11428   if (UseVector) {
11429     bool IsVec = MemVT.isVector();
11430     unsigned Elts = NumStores;
11431     if (IsVec) {
11432       // When merging vector stores, get the total number of elements.
11433       Elts *= MemVT.getVectorNumElements();
11434     }
11435     // Get the type for the merged vector store.
11436     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11437     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11438 
11439     if (IsConstantSrc) {
11440       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11441     } else {
11442       SmallVector<SDValue, 8> Ops;
11443       for (unsigned i = 0; i < NumStores; ++i) {
11444         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11445         SDValue Val = St->getValue();
11446         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11447         if (Val.getValueType() != MemVT)
11448           return false;
11449         Ops.push_back(Val);
11450         Chains.push_back(St->getChain());
11451       }
11452 
11453       // Build the extracted vector elements back into a vector.
11454       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11455                               DL, Ty, Ops);    }
11456   } else {
11457     // We should always use a vector store when merging extracted vector
11458     // elements, so this path implies a store of constants.
11459     assert(IsConstantSrc && "Merged vector elements should use vector store");
11460 
11461     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11462     APInt StoreInt(SizeInBits, 0);
11463 
11464     // Construct a single integer constant which is made of the smaller
11465     // constant inputs.
11466     bool IsLE = DAG.getDataLayout().isLittleEndian();
11467     for (unsigned i = 0; i < NumStores; ++i) {
11468       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11469       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11470       Chains.push_back(St->getChain());
11471 
11472       SDValue Val = St->getValue();
11473       StoreInt <<= ElementSizeBytes * 8;
11474       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11475         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11476       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11477         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11478       } else {
11479         llvm_unreachable("Invalid constant element type");
11480       }
11481     }
11482 
11483     // Create the new Load and Store operations.
11484     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11485     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11486   }
11487 
11488   assert(!Chains.empty());
11489 
11490   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11491   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11492                                   FirstInChain->getBasePtr(),
11493                                   FirstInChain->getPointerInfo(),
11494                                   FirstInChain->getAlignment());
11495 
11496   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11497                                                   : DAG.getSubtarget().useAA();
11498   if (UseAA) {
11499     // Replace all merged stores with the new store.
11500     for (unsigned i = 0; i < NumStores; ++i)
11501       CombineTo(StoreNodes[i].MemNode, NewStore);
11502   } else {
11503     // Replace the last store with the new store.
11504     CombineTo(LatestOp, NewStore);
11505     // Erase all other stores.
11506     for (unsigned i = 0; i < NumStores; ++i) {
11507       if (StoreNodes[i].MemNode == LatestOp)
11508         continue;
11509       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11510       // ReplaceAllUsesWith will replace all uses that existed when it was
11511       // called, but graph optimizations may cause new ones to appear. For
11512       // example, the case in pr14333 looks like
11513       //
11514       //  St's chain -> St -> another store -> X
11515       //
11516       // And the only difference from St to the other store is the chain.
11517       // When we change it's chain to be St's chain they become identical,
11518       // get CSEed and the net result is that X is now a use of St.
11519       // Since we know that St is redundant, just iterate.
11520       while (!St->use_empty())
11521         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11522       deleteAndRecombine(St);
11523     }
11524   }
11525 
11526   StoreNodes.erase(StoreNodes.begin() + NumStores, StoreNodes.end());
11527   return true;
11528 }
11529 
11530 void DAGCombiner::getStoreMergeAndAliasCandidates(
11531     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11532     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11533   // This holds the base pointer, index, and the offset in bytes from the base
11534   // pointer.
11535   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11536 
11537   // We must have a base and an offset.
11538   if (!BasePtr.Base.getNode())
11539     return;
11540 
11541   // Do not handle stores to undef base pointers.
11542   if (BasePtr.Base.isUndef())
11543     return;
11544 
11545   // Walk up the chain and look for nodes with offsets from the same
11546   // base pointer. Stop when reaching an instruction with a different kind
11547   // or instruction which has a different base pointer.
11548   EVT MemVT = St->getMemoryVT();
11549   unsigned Seq = 0;
11550   StoreSDNode *Index = St;
11551 
11552 
11553   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11554                                                   : DAG.getSubtarget().useAA();
11555 
11556   if (UseAA) {
11557     // Look at other users of the same chain. Stores on the same chain do not
11558     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11559     // to be on the same chain, so don't bother looking at adjacent chains.
11560 
11561     SDValue Chain = St->getChain();
11562     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11563       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11564         if (I.getOperandNo() != 0)
11565           continue;
11566 
11567         if (OtherST->isVolatile() || OtherST->isIndexed())
11568           continue;
11569 
11570         if (OtherST->getMemoryVT() != MemVT)
11571           continue;
11572 
11573         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11574 
11575         if (Ptr.equalBaseIndex(BasePtr))
11576           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11577       }
11578     }
11579 
11580     return;
11581   }
11582 
11583   while (Index) {
11584     // If the chain has more than one use, then we can't reorder the mem ops.
11585     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11586       break;
11587 
11588     // Find the base pointer and offset for this memory node.
11589     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11590 
11591     // Check that the base pointer is the same as the original one.
11592     if (!Ptr.equalBaseIndex(BasePtr))
11593       break;
11594 
11595     // The memory operands must not be volatile.
11596     if (Index->isVolatile() || Index->isIndexed())
11597       break;
11598 
11599     // No truncation.
11600     if (Index->isTruncatingStore())
11601       break;
11602 
11603     // The stored memory type must be the same.
11604     if (Index->getMemoryVT() != MemVT)
11605       break;
11606 
11607     // We do not allow under-aligned stores in order to prevent
11608     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11609     // be irrelevant here; what MATTERS is that we not move memory
11610     // operations that potentially overlap past each-other.
11611     if (Index->getAlignment() < MemVT.getStoreSize())
11612       break;
11613 
11614     // We found a potential memory operand to merge.
11615     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11616 
11617     // Find the next memory operand in the chain. If the next operand in the
11618     // chain is a store then move up and continue the scan with the next
11619     // memory operand. If the next operand is a load save it and use alias
11620     // information to check if it interferes with anything.
11621     SDNode *NextInChain = Index->getChain().getNode();
11622     while (1) {
11623       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11624         // We found a store node. Use it for the next iteration.
11625         Index = STn;
11626         break;
11627       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11628         if (Ldn->isVolatile()) {
11629           Index = nullptr;
11630           break;
11631         }
11632 
11633         // Save the load node for later. Continue the scan.
11634         AliasLoadNodes.push_back(Ldn);
11635         NextInChain = Ldn->getChain().getNode();
11636         continue;
11637       } else {
11638         Index = nullptr;
11639         break;
11640       }
11641     }
11642   }
11643 }
11644 
11645 // We need to check that merging these stores does not cause a loop
11646 // in the DAG. Any store candidate may depend on another candidate
11647 // indirectly through its operand (we already consider dependencies
11648 // through the chain). Check in parallel by searching up from
11649 // non-chain operands of candidates.
11650 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11651     SmallVectorImpl<MemOpLink> &StoreNodes) {
11652   SmallPtrSet<const SDNode *, 16> Visited;
11653   SmallVector<const SDNode *, 8> Worklist;
11654   // search ops of store candidates
11655   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11656     SDNode *n = StoreNodes[i].MemNode;
11657     // Potential loops may happen only through non-chain operands
11658     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11659       Worklist.push_back(n->getOperand(j).getNode());
11660   }
11661   // search through DAG. We can stop early if we find a storenode
11662   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11663     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11664       return false;
11665   }
11666   return true;
11667 }
11668 
11669 bool DAGCombiner::MergeConsecutiveStores(
11670     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes) {
11671   if (OptLevel == CodeGenOpt::None)
11672     return false;
11673 
11674   EVT MemVT = St->getMemoryVT();
11675   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11676   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11677       Attribute::NoImplicitFloat);
11678 
11679   // This function cannot currently deal with non-byte-sized memory sizes.
11680   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11681     return false;
11682 
11683   if (!MemVT.isSimple())
11684     return false;
11685 
11686   // Perform an early exit check. Do not bother looking at stored values that
11687   // are not constants, loads, or extracted vector elements.
11688   SDValue StoredVal = St->getValue();
11689   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11690   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11691                        isa<ConstantFPSDNode>(StoredVal);
11692   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11693                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11694 
11695   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11696     return false;
11697 
11698   // Don't merge vectors into wider vectors if the source data comes from loads.
11699   // TODO: This restriction can be lifted by using logic similar to the
11700   // ExtractVecSrc case.
11701   if (MemVT.isVector() && IsLoadSrc)
11702     return false;
11703 
11704   // Only look at ends of store sequences.
11705   SDValue Chain = SDValue(St, 0);
11706   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11707     return false;
11708 
11709   // Save the LoadSDNodes that we find in the chain.
11710   // We need to make sure that these nodes do not interfere with
11711   // any of the store nodes.
11712   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11713 
11714   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11715 
11716   // Check if there is anything to merge.
11717   if (StoreNodes.size() < 2)
11718     return false;
11719 
11720   // only do dependence check in AA case
11721   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11722                                                   : DAG.getSubtarget().useAA();
11723   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11724     return false;
11725 
11726   // Sort the memory operands according to their distance from the
11727   // base pointer.  As a secondary criteria: make sure stores coming
11728   // later in the code come first in the list. This is important for
11729   // the non-UseAA case, because we're merging stores into the FINAL
11730   // store along a chain which potentially contains aliasing stores.
11731   // Thus, if there are multiple stores to the same address, the last
11732   // one can be considered for merging but not the others.
11733   std::sort(StoreNodes.begin(), StoreNodes.end(),
11734             [](MemOpLink LHS, MemOpLink RHS) {
11735     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11736            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11737             LHS.SequenceNum < RHS.SequenceNum);
11738   });
11739 
11740   // Scan the memory operations on the chain and find the first non-consecutive
11741   // store memory address.
11742   unsigned LastConsecutiveStore = 0;
11743   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11744   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11745 
11746     // Check that the addresses are consecutive starting from the second
11747     // element in the list of stores.
11748     if (i > 0) {
11749       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11750       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11751         break;
11752     }
11753 
11754     // Check if this store interferes with any of the loads that we found.
11755     // If we find a load that alias with this store. Stop the sequence.
11756     if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) {
11757           return isAlias(Ldn, StoreNodes[i].MemNode);
11758         }))
11759       break;
11760 
11761     // Mark this node as useful.
11762     LastConsecutiveStore = i;
11763   }
11764 
11765   // The node with the lowest store address.
11766   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11767   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11768   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11769   LLVMContext &Context = *DAG.getContext();
11770   const DataLayout &DL = DAG.getDataLayout();
11771 
11772   // Store the constants into memory as one consecutive store.
11773   if (IsConstantSrc) {
11774     unsigned LastLegalType = 0;
11775     unsigned LastLegalVectorType = 0;
11776     bool NonZero = false;
11777     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11778       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11779       SDValue StoredVal = St->getValue();
11780 
11781       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11782         NonZero |= !C->isNullValue();
11783       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11784         NonZero |= !C->getConstantFPValue()->isNullValue();
11785       } else {
11786         // Non-constant.
11787         break;
11788       }
11789 
11790       // Find a legal type for the constant store.
11791       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11792       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11793       bool IsFast;
11794       if (TLI.isTypeLegal(StoreTy) &&
11795           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11796                                  FirstStoreAlign, &IsFast) && IsFast) {
11797         LastLegalType = i+1;
11798       // Or check whether a truncstore is legal.
11799       } else if (TLI.getTypeAction(Context, StoreTy) ==
11800                  TargetLowering::TypePromoteInteger) {
11801         EVT LegalizedStoredValueTy =
11802           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11803         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11804             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11805                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11806             IsFast) {
11807           LastLegalType = i + 1;
11808         }
11809       }
11810 
11811       // We only use vectors if the constant is known to be zero or the target
11812       // allows it and the function is not marked with the noimplicitfloat
11813       // attribute.
11814       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11815                                                         FirstStoreAS)) &&
11816           !NoVectors) {
11817         // Find a legal type for the vector store.
11818         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11819         if (TLI.isTypeLegal(Ty) &&
11820             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11821                                    FirstStoreAlign, &IsFast) && IsFast)
11822           LastLegalVectorType = i + 1;
11823       }
11824     }
11825 
11826     // Check if we found a legal integer type to store.
11827     if (LastLegalType == 0 && LastLegalVectorType == 0)
11828       return false;
11829 
11830     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11831     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11832 
11833     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11834                                            true, UseVector);
11835   }
11836 
11837   // When extracting multiple vector elements, try to store them
11838   // in one vector store rather than a sequence of scalar stores.
11839   if (IsExtractVecSrc) {
11840     unsigned NumStoresToMerge = 0;
11841     bool IsVec = MemVT.isVector();
11842     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11843       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11844       unsigned StoreValOpcode = St->getValue().getOpcode();
11845       // This restriction could be loosened.
11846       // Bail out if any stored values are not elements extracted from a vector.
11847       // It should be possible to handle mixed sources, but load sources need
11848       // more careful handling (see the block of code below that handles
11849       // consecutive loads).
11850       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11851           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11852         return false;
11853 
11854       // Find a legal type for the vector store.
11855       unsigned Elts = i + 1;
11856       if (IsVec) {
11857         // When merging vector stores, get the total number of elements.
11858         Elts *= MemVT.getVectorNumElements();
11859       }
11860       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11861       bool IsFast;
11862       if (TLI.isTypeLegal(Ty) &&
11863           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11864                                  FirstStoreAlign, &IsFast) && IsFast)
11865         NumStoresToMerge = i + 1;
11866     }
11867 
11868     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11869                                            false, true);
11870   }
11871 
11872   // Below we handle the case of multiple consecutive stores that
11873   // come from multiple consecutive loads. We merge them into a single
11874   // wide load and a single wide store.
11875 
11876   // Look for load nodes which are used by the stored values.
11877   SmallVector<MemOpLink, 8> LoadNodes;
11878 
11879   // Find acceptable loads. Loads need to have the same chain (token factor),
11880   // must not be zext, volatile, indexed, and they must be consecutive.
11881   BaseIndexOffset LdBasePtr;
11882   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11883     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11884     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11885     if (!Ld) break;
11886 
11887     // Loads must only have one use.
11888     if (!Ld->hasNUsesOfValue(1, 0))
11889       break;
11890 
11891     // The memory operands must not be volatile.
11892     if (Ld->isVolatile() || Ld->isIndexed())
11893       break;
11894 
11895     // We do not accept ext loads.
11896     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11897       break;
11898 
11899     // The stored memory type must be the same.
11900     if (Ld->getMemoryVT() != MemVT)
11901       break;
11902 
11903     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11904     // If this is not the first ptr that we check.
11905     if (LdBasePtr.Base.getNode()) {
11906       // The base ptr must be the same.
11907       if (!LdPtr.equalBaseIndex(LdBasePtr))
11908         break;
11909     } else {
11910       // Check that all other base pointers are the same as this one.
11911       LdBasePtr = LdPtr;
11912     }
11913 
11914     // We found a potential memory operand to merge.
11915     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11916   }
11917 
11918   if (LoadNodes.size() < 2)
11919     return false;
11920 
11921   // If we have load/store pair instructions and we only have two values,
11922   // don't bother.
11923   unsigned RequiredAlignment;
11924   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11925       St->getAlignment() >= RequiredAlignment)
11926     return false;
11927 
11928   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11929   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11930   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11931 
11932   // Scan the memory operations on the chain and find the first non-consecutive
11933   // load memory address. These variables hold the index in the store node
11934   // array.
11935   unsigned LastConsecutiveLoad = 0;
11936   // This variable refers to the size and not index in the array.
11937   unsigned LastLegalVectorType = 0;
11938   unsigned LastLegalIntegerType = 0;
11939   StartAddress = LoadNodes[0].OffsetFromBase;
11940   SDValue FirstChain = FirstLoad->getChain();
11941   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11942     // All loads must share the same chain.
11943     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11944       break;
11945 
11946     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11947     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11948       break;
11949     LastConsecutiveLoad = i;
11950     // Find a legal type for the vector store.
11951     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11952     bool IsFastSt, IsFastLd;
11953     if (TLI.isTypeLegal(StoreTy) &&
11954         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11955                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11956         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11957                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11958       LastLegalVectorType = i + 1;
11959     }
11960 
11961     // Find a legal type for the integer store.
11962     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11963     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11964     if (TLI.isTypeLegal(StoreTy) &&
11965         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11966                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11967         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11968                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11969       LastLegalIntegerType = i + 1;
11970     // Or check whether a truncstore and extload is legal.
11971     else if (TLI.getTypeAction(Context, StoreTy) ==
11972              TargetLowering::TypePromoteInteger) {
11973       EVT LegalizedStoredValueTy =
11974         TLI.getTypeToTransformTo(Context, StoreTy);
11975       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11976           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11977           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11978           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11979           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11980                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11981           IsFastSt &&
11982           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11983                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11984           IsFastLd)
11985         LastLegalIntegerType = i+1;
11986     }
11987   }
11988 
11989   // Only use vector types if the vector type is larger than the integer type.
11990   // If they are the same, use integers.
11991   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11992   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11993 
11994   // We add +1 here because the LastXXX variables refer to location while
11995   // the NumElem refers to array/index size.
11996   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11997   NumElem = std::min(LastLegalType, NumElem);
11998 
11999   if (NumElem < 2)
12000     return false;
12001 
12002   // Collect the chains from all merged stores.
12003   SmallVector<SDValue, 8> MergeStoreChains;
12004   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
12005 
12006   // The latest Node in the DAG.
12007   unsigned LatestNodeUsed = 0;
12008   for (unsigned i=1; i<NumElem; ++i) {
12009     // Find a chain for the new wide-store operand. Notice that some
12010     // of the store nodes that we found may not be selected for inclusion
12011     // in the wide store. The chain we use needs to be the chain of the
12012     // latest store node which is *used* and replaced by the wide store.
12013     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
12014       LatestNodeUsed = i;
12015 
12016     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
12017   }
12018 
12019   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
12020 
12021   // Find if it is better to use vectors or integers to load and store
12022   // to memory.
12023   EVT JointMemOpVT;
12024   if (UseVectorTy) {
12025     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12026   } else {
12027     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12028     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12029   }
12030 
12031   SDLoc LoadDL(LoadNodes[0].MemNode);
12032   SDLoc StoreDL(StoreNodes[0].MemNode);
12033 
12034   // The merged loads are required to have the same incoming chain, so
12035   // using the first's chain is acceptable.
12036   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12037                                 FirstLoad->getBasePtr(),
12038                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
12039 
12040   SDValue NewStoreChain =
12041     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
12042 
12043   SDValue NewStore =
12044       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12045                    FirstInChain->getPointerInfo(), FirstStoreAlign);
12046 
12047   // Transfer chain users from old loads to the new load.
12048   for (unsigned i = 0; i < NumElem; ++i) {
12049     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12050     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12051                                   SDValue(NewLoad.getNode(), 1));
12052   }
12053 
12054   if (UseAA) {
12055     // Replace the all stores with the new store.
12056     for (unsigned i = 0; i < NumElem; ++i)
12057       CombineTo(StoreNodes[i].MemNode, NewStore);
12058   } else {
12059     // Replace the last store with the new store.
12060     CombineTo(LatestOp, NewStore);
12061     // Erase all other stores.
12062     for (unsigned i = 0; i < NumElem; ++i) {
12063       // Remove all Store nodes.
12064       if (StoreNodes[i].MemNode == LatestOp)
12065         continue;
12066       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12067       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
12068       deleteAndRecombine(St);
12069     }
12070   }
12071 
12072   StoreNodes.erase(StoreNodes.begin() + NumElem, StoreNodes.end());
12073   return true;
12074 }
12075 
12076 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12077   SDLoc SL(ST);
12078   SDValue ReplStore;
12079 
12080   // Replace the chain to avoid dependency.
12081   if (ST->isTruncatingStore()) {
12082     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12083                                   ST->getBasePtr(), ST->getMemoryVT(),
12084                                   ST->getMemOperand());
12085   } else {
12086     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12087                              ST->getMemOperand());
12088   }
12089 
12090   // Create token to keep both nodes around.
12091   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12092                               MVT::Other, ST->getChain(), ReplStore);
12093 
12094   // Make sure the new and old chains are cleaned up.
12095   AddToWorklist(Token.getNode());
12096 
12097   // Don't add users to work list.
12098   return CombineTo(ST, Token, false);
12099 }
12100 
12101 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12102   SDValue Value = ST->getValue();
12103   if (Value.getOpcode() == ISD::TargetConstantFP)
12104     return SDValue();
12105 
12106   SDLoc DL(ST);
12107 
12108   SDValue Chain = ST->getChain();
12109   SDValue Ptr = ST->getBasePtr();
12110 
12111   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12112 
12113   // NOTE: If the original store is volatile, this transform must not increase
12114   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12115   // processor operation but an i64 (which is not legal) requires two.  So the
12116   // transform should not be done in this case.
12117 
12118   SDValue Tmp;
12119   switch (CFP->getSimpleValueType(0).SimpleTy) {
12120   default:
12121     llvm_unreachable("Unknown FP type");
12122   case MVT::f16:    // We don't do this for these yet.
12123   case MVT::f80:
12124   case MVT::f128:
12125   case MVT::ppcf128:
12126     return SDValue();
12127   case MVT::f32:
12128     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12129         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12130       ;
12131       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12132                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12133                             MVT::i32);
12134       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12135     }
12136 
12137     return SDValue();
12138   case MVT::f64:
12139     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12140          !ST->isVolatile()) ||
12141         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12142       ;
12143       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12144                             getZExtValue(), SDLoc(CFP), MVT::i64);
12145       return DAG.getStore(Chain, DL, Tmp,
12146                           Ptr, ST->getMemOperand());
12147     }
12148 
12149     if (!ST->isVolatile() &&
12150         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12151       // Many FP stores are not made apparent until after legalize, e.g. for
12152       // argument passing.  Since this is so common, custom legalize the
12153       // 64-bit integer store into two 32-bit stores.
12154       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12155       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12156       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12157       if (DAG.getDataLayout().isBigEndian())
12158         std::swap(Lo, Hi);
12159 
12160       unsigned Alignment = ST->getAlignment();
12161       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12162       AAMDNodes AAInfo = ST->getAAInfo();
12163 
12164       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12165                                  ST->getAlignment(), MMOFlags, AAInfo);
12166       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12167                         DAG.getConstant(4, DL, Ptr.getValueType()));
12168       Alignment = MinAlign(Alignment, 4U);
12169       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12170                                  ST->getPointerInfo().getWithOffset(4),
12171                                  Alignment, MMOFlags, AAInfo);
12172       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12173                          St0, St1);
12174     }
12175 
12176     return SDValue();
12177   }
12178 }
12179 
12180 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12181   StoreSDNode *ST  = cast<StoreSDNode>(N);
12182   SDValue Chain = ST->getChain();
12183   SDValue Value = ST->getValue();
12184   SDValue Ptr   = ST->getBasePtr();
12185 
12186   // If this is a store of a bit convert, store the input value if the
12187   // resultant store does not need a higher alignment than the original.
12188   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12189       ST->isUnindexed()) {
12190     EVT SVT = Value.getOperand(0).getValueType();
12191     if (((!LegalOperations && !ST->isVolatile()) ||
12192          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12193         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12194       unsigned OrigAlign = ST->getAlignment();
12195       bool Fast = false;
12196       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12197                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12198           Fast) {
12199         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12200                             ST->getPointerInfo(), OrigAlign,
12201                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12202       }
12203     }
12204   }
12205 
12206   // Turn 'store undef, Ptr' -> nothing.
12207   if (Value.isUndef() && ST->isUnindexed())
12208     return Chain;
12209 
12210   // Try to infer better alignment information than the store already has.
12211   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12212     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12213       if (Align > ST->getAlignment()) {
12214         SDValue NewStore =
12215             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12216                               ST->getMemoryVT(), Align,
12217                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12218         if (NewStore.getNode() != N)
12219           return CombineTo(ST, NewStore, true);
12220       }
12221     }
12222   }
12223 
12224   // Try transforming a pair floating point load / store ops to integer
12225   // load / store ops.
12226   if (SDValue NewST = TransformFPLoadStorePair(N))
12227     return NewST;
12228 
12229   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12230                                                   : DAG.getSubtarget().useAA();
12231 #ifndef NDEBUG
12232   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12233       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12234     UseAA = false;
12235 #endif
12236   if (UseAA && ST->isUnindexed()) {
12237     // FIXME: We should do this even without AA enabled. AA will just allow
12238     // FindBetterChain to work in more situations. The problem with this is that
12239     // any combine that expects memory operations to be on consecutive chains
12240     // first needs to be updated to look for users of the same chain.
12241 
12242     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12243     // adjacent stores.
12244     if (findBetterNeighborChains(ST)) {
12245       // replaceStoreChain uses CombineTo, which handled all of the worklist
12246       // manipulation. Return the original node to not do anything else.
12247       return SDValue(ST, 0);
12248     }
12249     Chain = ST->getChain();
12250   }
12251 
12252   // Try transforming N to an indexed store.
12253   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12254     return SDValue(N, 0);
12255 
12256   // FIXME: is there such a thing as a truncating indexed store?
12257   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12258       Value.getValueType().isInteger()) {
12259     // See if we can simplify the input to this truncstore with knowledge that
12260     // only the low bits are being used.  For example:
12261     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12262     SDValue Shorter = GetDemandedBits(
12263         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12264                                     ST->getMemoryVT().getScalarSizeInBits()));
12265     AddToWorklist(Value.getNode());
12266     if (Shorter.getNode())
12267       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12268                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12269 
12270     // Otherwise, see if we can simplify the operation with
12271     // SimplifyDemandedBits, which only works if the value has a single use.
12272     if (SimplifyDemandedBits(
12273             Value,
12274             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12275                                  ST->getMemoryVT().getScalarSizeInBits())))
12276       return SDValue(N, 0);
12277   }
12278 
12279   // If this is a load followed by a store to the same location, then the store
12280   // is dead/noop.
12281   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12282     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12283         ST->isUnindexed() && !ST->isVolatile() &&
12284         // There can't be any side effects between the load and store, such as
12285         // a call or store.
12286         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12287       // The store is dead, remove it.
12288       return Chain;
12289     }
12290   }
12291 
12292   // If this is a store followed by a store with the same value to the same
12293   // location, then the store is dead/noop.
12294   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12295     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12296         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12297         ST1->isUnindexed() && !ST1->isVolatile()) {
12298       // The store is dead, remove it.
12299       return Chain;
12300     }
12301   }
12302 
12303   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12304   // truncating store.  We can do this even if this is already a truncstore.
12305   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12306       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12307       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12308                             ST->getMemoryVT())) {
12309     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12310                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12311   }
12312 
12313   // Only perform this optimization before the types are legal, because we
12314   // don't want to perform this optimization on every DAGCombine invocation.
12315   if (!LegalTypes) {
12316     for (;;) {
12317       // There can be multiple store sequences on the same chain.
12318       // Keep trying to merge store sequences until we are unable to do so
12319       // or until we merge the last store on the chain.
12320       SmallVector<MemOpLink, 8> StoreNodes;
12321       bool Changed = MergeConsecutiveStores(ST, StoreNodes);
12322       if (!Changed) break;
12323 
12324       if (any_of(StoreNodes,
12325                  [ST](const MemOpLink &Link) { return Link.MemNode == ST; })) {
12326         // ST has been merged and no longer exists.
12327         return SDValue(N, 0);
12328       }
12329     }
12330   }
12331 
12332   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12333   //
12334   // Make sure to do this only after attempting to merge stores in order to
12335   //  avoid changing the types of some subset of stores due to visit order,
12336   //  preventing their merging.
12337   if (isa<ConstantFPSDNode>(Value)) {
12338     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12339       return NewSt;
12340   }
12341 
12342   if (SDValue NewSt = splitMergedValStore(ST))
12343     return NewSt;
12344 
12345   return ReduceLoadOpStoreWidth(N);
12346 }
12347 
12348 /// For the instruction sequence of store below, F and I values
12349 /// are bundled together as an i64 value before being stored into memory.
12350 /// Sometimes it is more efficent to generate separate stores for F and I,
12351 /// which can remove the bitwise instructions or sink them to colder places.
12352 ///
12353 ///   (store (or (zext (bitcast F to i32) to i64),
12354 ///              (shl (zext I to i64), 32)), addr)  -->
12355 ///   (store F, addr) and (store I, addr+4)
12356 ///
12357 /// Similarly, splitting for other merged store can also be beneficial, like:
12358 /// For pair of {i32, i32}, i64 store --> two i32 stores.
12359 /// For pair of {i32, i16}, i64 store --> two i32 stores.
12360 /// For pair of {i16, i16}, i32 store --> two i16 stores.
12361 /// For pair of {i16, i8},  i32 store --> two i16 stores.
12362 /// For pair of {i8, i8},   i16 store --> two i8 stores.
12363 ///
12364 /// We allow each target to determine specifically which kind of splitting is
12365 /// supported.
12366 ///
12367 /// The store patterns are commonly seen from the simple code snippet below
12368 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
12369 ///   void goo(const std::pair<int, float> &);
12370 ///   hoo() {
12371 ///     ...
12372 ///     goo(std::make_pair(tmp, ftmp));
12373 ///     ...
12374 ///   }
12375 ///
12376 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
12377   if (OptLevel == CodeGenOpt::None)
12378     return SDValue();
12379 
12380   SDValue Val = ST->getValue();
12381   SDLoc DL(ST);
12382 
12383   // Match OR operand.
12384   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
12385     return SDValue();
12386 
12387   // Match SHL operand and get Lower and Higher parts of Val.
12388   SDValue Op1 = Val.getOperand(0);
12389   SDValue Op2 = Val.getOperand(1);
12390   SDValue Lo, Hi;
12391   if (Op1.getOpcode() != ISD::SHL) {
12392     std::swap(Op1, Op2);
12393     if (Op1.getOpcode() != ISD::SHL)
12394       return SDValue();
12395   }
12396   Lo = Op2;
12397   Hi = Op1.getOperand(0);
12398   if (!Op1.hasOneUse())
12399     return SDValue();
12400 
12401   // Match shift amount to HalfValBitSize.
12402   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
12403   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
12404   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
12405     return SDValue();
12406 
12407   // Lo and Hi are zero-extended from int with size less equal than 32
12408   // to i64.
12409   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
12410       !Lo.getOperand(0).getValueType().isScalarInteger() ||
12411       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
12412       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
12413       !Hi.getOperand(0).getValueType().isScalarInteger() ||
12414       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
12415     return SDValue();
12416 
12417   if (!TLI.isMultiStoresCheaperThanBitsMerge(Lo.getOperand(0),
12418                                              Hi.getOperand(0)))
12419     return SDValue();
12420 
12421   // Start to split store.
12422   unsigned Alignment = ST->getAlignment();
12423   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12424   AAMDNodes AAInfo = ST->getAAInfo();
12425 
12426   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
12427   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
12428   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
12429   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
12430 
12431   SDValue Chain = ST->getChain();
12432   SDValue Ptr = ST->getBasePtr();
12433   // Lower value store.
12434   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12435                              ST->getAlignment(), MMOFlags, AAInfo);
12436   Ptr =
12437       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12438                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
12439   // Higher value store.
12440   SDValue St1 =
12441       DAG.getStore(St0, DL, Hi, Ptr,
12442                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
12443                    Alignment / 2, MMOFlags, AAInfo);
12444   return St1;
12445 }
12446 
12447 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12448   SDValue InVec = N->getOperand(0);
12449   SDValue InVal = N->getOperand(1);
12450   SDValue EltNo = N->getOperand(2);
12451   SDLoc DL(N);
12452 
12453   // If the inserted element is an UNDEF, just use the input vector.
12454   if (InVal.isUndef())
12455     return InVec;
12456 
12457   EVT VT = InVec.getValueType();
12458 
12459   // If we can't generate a legal BUILD_VECTOR, exit
12460   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12461     return SDValue();
12462 
12463   // Check that we know which element is being inserted
12464   if (!isa<ConstantSDNode>(EltNo))
12465     return SDValue();
12466   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12467 
12468   // Canonicalize insert_vector_elt dag nodes.
12469   // Example:
12470   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12471   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12472   //
12473   // Do this only if the child insert_vector node has one use; also
12474   // do this only if indices are both constants and Idx1 < Idx0.
12475   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12476       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12477     unsigned OtherElt =
12478       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12479     if (Elt < OtherElt) {
12480       // Swap nodes.
12481       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
12482                                   InVec.getOperand(0), InVal, EltNo);
12483       AddToWorklist(NewOp.getNode());
12484       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12485                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12486     }
12487   }
12488 
12489   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12490   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12491   // vector elements.
12492   SmallVector<SDValue, 8> Ops;
12493   // Do not combine these two vectors if the output vector will not replace
12494   // the input vector.
12495   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12496     Ops.append(InVec.getNode()->op_begin(),
12497                InVec.getNode()->op_end());
12498   } else if (InVec.isUndef()) {
12499     unsigned NElts = VT.getVectorNumElements();
12500     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12501   } else {
12502     return SDValue();
12503   }
12504 
12505   // Insert the element
12506   if (Elt < Ops.size()) {
12507     // All the operands of BUILD_VECTOR must have the same type;
12508     // we enforce that here.
12509     EVT OpVT = Ops[0].getValueType();
12510     if (InVal.getValueType() != OpVT)
12511       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12512                 DAG.getNode(ISD::ANY_EXTEND, DL, OpVT, InVal) :
12513                 DAG.getNode(ISD::TRUNCATE, DL, OpVT, InVal);
12514     Ops[Elt] = InVal;
12515   }
12516 
12517   // Return the new vector
12518   return DAG.getBuildVector(VT, DL, Ops);
12519 }
12520 
12521 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12522     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12523   assert(!OriginalLoad->isVolatile());
12524 
12525   EVT ResultVT = EVE->getValueType(0);
12526   EVT VecEltVT = InVecVT.getVectorElementType();
12527   unsigned Align = OriginalLoad->getAlignment();
12528   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12529       VecEltVT.getTypeForEVT(*DAG.getContext()));
12530 
12531   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12532     return SDValue();
12533 
12534   Align = NewAlign;
12535 
12536   SDValue NewPtr = OriginalLoad->getBasePtr();
12537   SDValue Offset;
12538   EVT PtrType = NewPtr.getValueType();
12539   MachinePointerInfo MPI;
12540   SDLoc DL(EVE);
12541   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12542     int Elt = ConstEltNo->getZExtValue();
12543     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12544     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12545     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12546   } else {
12547     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12548     Offset = DAG.getNode(
12549         ISD::MUL, DL, PtrType, Offset,
12550         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12551     MPI = OriginalLoad->getPointerInfo();
12552   }
12553   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12554 
12555   // The replacement we need to do here is a little tricky: we need to
12556   // replace an extractelement of a load with a load.
12557   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12558   // Note that this replacement assumes that the extractvalue is the only
12559   // use of the load; that's okay because we don't want to perform this
12560   // transformation in other cases anyway.
12561   SDValue Load;
12562   SDValue Chain;
12563   if (ResultVT.bitsGT(VecEltVT)) {
12564     // If the result type of vextract is wider than the load, then issue an
12565     // extending load instead.
12566     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12567                                                   VecEltVT)
12568                                    ? ISD::ZEXTLOAD
12569                                    : ISD::EXTLOAD;
12570     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12571                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12572                           Align, OriginalLoad->getMemOperand()->getFlags(),
12573                           OriginalLoad->getAAInfo());
12574     Chain = Load.getValue(1);
12575   } else {
12576     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12577                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12578                        OriginalLoad->getAAInfo());
12579     Chain = Load.getValue(1);
12580     if (ResultVT.bitsLT(VecEltVT))
12581       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12582     else
12583       Load = DAG.getBitcast(ResultVT, Load);
12584   }
12585   WorklistRemover DeadNodes(*this);
12586   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12587   SDValue To[] = { Load, Chain };
12588   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12589   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12590   // worklist explicitly as well.
12591   AddToWorklist(Load.getNode());
12592   AddUsersToWorklist(Load.getNode()); // Add users too
12593   // Make sure to revisit this node to clean it up; it will usually be dead.
12594   AddToWorklist(EVE);
12595   ++OpsNarrowed;
12596   return SDValue(EVE, 0);
12597 }
12598 
12599 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12600   // (vextract (scalar_to_vector val, 0) -> val
12601   SDValue InVec = N->getOperand(0);
12602   EVT VT = InVec.getValueType();
12603   EVT NVT = N->getValueType(0);
12604 
12605   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12606     // Check if the result type doesn't match the inserted element type. A
12607     // SCALAR_TO_VECTOR may truncate the inserted element and the
12608     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12609     SDValue InOp = InVec.getOperand(0);
12610     if (InOp.getValueType() != NVT) {
12611       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12612       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12613     }
12614     return InOp;
12615   }
12616 
12617   SDValue EltNo = N->getOperand(1);
12618   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12619 
12620   // extract_vector_elt (build_vector x, y), 1 -> y
12621   if (ConstEltNo &&
12622       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12623       TLI.isTypeLegal(VT) &&
12624       (InVec.hasOneUse() ||
12625        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12626     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12627     EVT InEltVT = Elt.getValueType();
12628 
12629     // Sometimes build_vector's scalar input types do not match result type.
12630     if (NVT == InEltVT)
12631       return Elt;
12632 
12633     // TODO: It may be useful to truncate if free if the build_vector implicitly
12634     // converts.
12635   }
12636 
12637   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12638   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12639       ConstEltNo->isNullValue() && VT.isInteger()) {
12640     SDValue BCSrc = InVec.getOperand(0);
12641     if (BCSrc.getValueType().isScalarInteger())
12642       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12643   }
12644 
12645   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12646   //
12647   // This only really matters if the index is non-constant since other combines
12648   // on the constant elements already work.
12649   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12650       EltNo == InVec.getOperand(2)) {
12651     SDValue Elt = InVec.getOperand(1);
12652     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12653   }
12654 
12655   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12656   // We only perform this optimization before the op legalization phase because
12657   // we may introduce new vector instructions which are not backed by TD
12658   // patterns. For example on AVX, extracting elements from a wide vector
12659   // without using extract_subvector. However, if we can find an underlying
12660   // scalar value, then we can always use that.
12661   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12662     int NumElem = VT.getVectorNumElements();
12663     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12664     // Find the new index to extract from.
12665     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12666 
12667     // Extracting an undef index is undef.
12668     if (OrigElt == -1)
12669       return DAG.getUNDEF(NVT);
12670 
12671     // Select the right vector half to extract from.
12672     SDValue SVInVec;
12673     if (OrigElt < NumElem) {
12674       SVInVec = InVec->getOperand(0);
12675     } else {
12676       SVInVec = InVec->getOperand(1);
12677       OrigElt -= NumElem;
12678     }
12679 
12680     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12681       SDValue InOp = SVInVec.getOperand(OrigElt);
12682       if (InOp.getValueType() != NVT) {
12683         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12684         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12685       }
12686 
12687       return InOp;
12688     }
12689 
12690     // FIXME: We should handle recursing on other vector shuffles and
12691     // scalar_to_vector here as well.
12692 
12693     if (!LegalOperations) {
12694       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12695       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12696                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12697     }
12698   }
12699 
12700   bool BCNumEltsChanged = false;
12701   EVT ExtVT = VT.getVectorElementType();
12702   EVT LVT = ExtVT;
12703 
12704   // If the result of load has to be truncated, then it's not necessarily
12705   // profitable.
12706   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12707     return SDValue();
12708 
12709   if (InVec.getOpcode() == ISD::BITCAST) {
12710     // Don't duplicate a load with other uses.
12711     if (!InVec.hasOneUse())
12712       return SDValue();
12713 
12714     EVT BCVT = InVec.getOperand(0).getValueType();
12715     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12716       return SDValue();
12717     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12718       BCNumEltsChanged = true;
12719     InVec = InVec.getOperand(0);
12720     ExtVT = BCVT.getVectorElementType();
12721   }
12722 
12723   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12724   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12725       ISD::isNormalLoad(InVec.getNode()) &&
12726       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12727     SDValue Index = N->getOperand(1);
12728     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12729       if (!OrigLoad->isVolatile()) {
12730         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12731                                                              OrigLoad);
12732       }
12733     }
12734   }
12735 
12736   // Perform only after legalization to ensure build_vector / vector_shuffle
12737   // optimizations have already been done.
12738   if (!LegalOperations) return SDValue();
12739 
12740   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12741   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12742   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12743 
12744   if (ConstEltNo) {
12745     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12746 
12747     LoadSDNode *LN0 = nullptr;
12748     const ShuffleVectorSDNode *SVN = nullptr;
12749     if (ISD::isNormalLoad(InVec.getNode())) {
12750       LN0 = cast<LoadSDNode>(InVec);
12751     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12752                InVec.getOperand(0).getValueType() == ExtVT &&
12753                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12754       // Don't duplicate a load with other uses.
12755       if (!InVec.hasOneUse())
12756         return SDValue();
12757 
12758       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12759     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12760       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12761       // =>
12762       // (load $addr+1*size)
12763 
12764       // Don't duplicate a load with other uses.
12765       if (!InVec.hasOneUse())
12766         return SDValue();
12767 
12768       // If the bit convert changed the number of elements, it is unsafe
12769       // to examine the mask.
12770       if (BCNumEltsChanged)
12771         return SDValue();
12772 
12773       // Select the input vector, guarding against out of range extract vector.
12774       unsigned NumElems = VT.getVectorNumElements();
12775       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12776       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12777 
12778       if (InVec.getOpcode() == ISD::BITCAST) {
12779         // Don't duplicate a load with other uses.
12780         if (!InVec.hasOneUse())
12781           return SDValue();
12782 
12783         InVec = InVec.getOperand(0);
12784       }
12785       if (ISD::isNormalLoad(InVec.getNode())) {
12786         LN0 = cast<LoadSDNode>(InVec);
12787         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12788         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12789       }
12790     }
12791 
12792     // Make sure we found a non-volatile load and the extractelement is
12793     // the only use.
12794     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12795       return SDValue();
12796 
12797     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12798     if (Elt == -1)
12799       return DAG.getUNDEF(LVT);
12800 
12801     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12802   }
12803 
12804   return SDValue();
12805 }
12806 
12807 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12808 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12809   // We perform this optimization post type-legalization because
12810   // the type-legalizer often scalarizes integer-promoted vectors.
12811   // Performing this optimization before may create bit-casts which
12812   // will be type-legalized to complex code sequences.
12813   // We perform this optimization only before the operation legalizer because we
12814   // may introduce illegal operations.
12815   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12816     return SDValue();
12817 
12818   unsigned NumInScalars = N->getNumOperands();
12819   SDLoc DL(N);
12820   EVT VT = N->getValueType(0);
12821 
12822   // Check to see if this is a BUILD_VECTOR of a bunch of values
12823   // which come from any_extend or zero_extend nodes. If so, we can create
12824   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12825   // optimizations. We do not handle sign-extend because we can't fill the sign
12826   // using shuffles.
12827   EVT SourceType = MVT::Other;
12828   bool AllAnyExt = true;
12829 
12830   for (unsigned i = 0; i != NumInScalars; ++i) {
12831     SDValue In = N->getOperand(i);
12832     // Ignore undef inputs.
12833     if (In.isUndef()) continue;
12834 
12835     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12836     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12837 
12838     // Abort if the element is not an extension.
12839     if (!ZeroExt && !AnyExt) {
12840       SourceType = MVT::Other;
12841       break;
12842     }
12843 
12844     // The input is a ZeroExt or AnyExt. Check the original type.
12845     EVT InTy = In.getOperand(0).getValueType();
12846 
12847     // Check that all of the widened source types are the same.
12848     if (SourceType == MVT::Other)
12849       // First time.
12850       SourceType = InTy;
12851     else if (InTy != SourceType) {
12852       // Multiple income types. Abort.
12853       SourceType = MVT::Other;
12854       break;
12855     }
12856 
12857     // Check if all of the extends are ANY_EXTENDs.
12858     AllAnyExt &= AnyExt;
12859   }
12860 
12861   // In order to have valid types, all of the inputs must be extended from the
12862   // same source type and all of the inputs must be any or zero extend.
12863   // Scalar sizes must be a power of two.
12864   EVT OutScalarTy = VT.getScalarType();
12865   bool ValidTypes = SourceType != MVT::Other &&
12866                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12867                  isPowerOf2_32(SourceType.getSizeInBits());
12868 
12869   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12870   // turn into a single shuffle instruction.
12871   if (!ValidTypes)
12872     return SDValue();
12873 
12874   bool isLE = DAG.getDataLayout().isLittleEndian();
12875   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12876   assert(ElemRatio > 1 && "Invalid element size ratio");
12877   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12878                                DAG.getConstant(0, DL, SourceType);
12879 
12880   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12881   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12882 
12883   // Populate the new build_vector
12884   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12885     SDValue Cast = N->getOperand(i);
12886     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12887             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12888             Cast.isUndef()) && "Invalid cast opcode");
12889     SDValue In;
12890     if (Cast.isUndef())
12891       In = DAG.getUNDEF(SourceType);
12892     else
12893       In = Cast->getOperand(0);
12894     unsigned Index = isLE ? (i * ElemRatio) :
12895                             (i * ElemRatio + (ElemRatio - 1));
12896 
12897     assert(Index < Ops.size() && "Invalid index");
12898     Ops[Index] = In;
12899   }
12900 
12901   // The type of the new BUILD_VECTOR node.
12902   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12903   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12904          "Invalid vector size");
12905   // Check if the new vector type is legal.
12906   if (!isTypeLegal(VecVT)) return SDValue();
12907 
12908   // Make the new BUILD_VECTOR.
12909   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
12910 
12911   // The new BUILD_VECTOR node has the potential to be further optimized.
12912   AddToWorklist(BV.getNode());
12913   // Bitcast to the desired type.
12914   return DAG.getBitcast(VT, BV);
12915 }
12916 
12917 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12918   EVT VT = N->getValueType(0);
12919 
12920   unsigned NumInScalars = N->getNumOperands();
12921   SDLoc DL(N);
12922 
12923   EVT SrcVT = MVT::Other;
12924   unsigned Opcode = ISD::DELETED_NODE;
12925   unsigned NumDefs = 0;
12926 
12927   for (unsigned i = 0; i != NumInScalars; ++i) {
12928     SDValue In = N->getOperand(i);
12929     unsigned Opc = In.getOpcode();
12930 
12931     if (Opc == ISD::UNDEF)
12932       continue;
12933 
12934     // If all scalar values are floats and converted from integers.
12935     if (Opcode == ISD::DELETED_NODE &&
12936         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12937       Opcode = Opc;
12938     }
12939 
12940     if (Opc != Opcode)
12941       return SDValue();
12942 
12943     EVT InVT = In.getOperand(0).getValueType();
12944 
12945     // If all scalar values are typed differently, bail out. It's chosen to
12946     // simplify BUILD_VECTOR of integer types.
12947     if (SrcVT == MVT::Other)
12948       SrcVT = InVT;
12949     if (SrcVT != InVT)
12950       return SDValue();
12951     NumDefs++;
12952   }
12953 
12954   // If the vector has just one element defined, it's not worth to fold it into
12955   // a vectorized one.
12956   if (NumDefs < 2)
12957     return SDValue();
12958 
12959   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12960          && "Should only handle conversion from integer to float.");
12961   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12962 
12963   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12964 
12965   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12966     return SDValue();
12967 
12968   // Just because the floating-point vector type is legal does not necessarily
12969   // mean that the corresponding integer vector type is.
12970   if (!isTypeLegal(NVT))
12971     return SDValue();
12972 
12973   SmallVector<SDValue, 8> Opnds;
12974   for (unsigned i = 0; i != NumInScalars; ++i) {
12975     SDValue In = N->getOperand(i);
12976 
12977     if (In.isUndef())
12978       Opnds.push_back(DAG.getUNDEF(SrcVT));
12979     else
12980       Opnds.push_back(In.getOperand(0));
12981   }
12982   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
12983   AddToWorklist(BV.getNode());
12984 
12985   return DAG.getNode(Opcode, DL, VT, BV);
12986 }
12987 
12988 SDValue DAGCombiner::createBuildVecShuffle(SDLoc DL, SDNode *N,
12989                                            ArrayRef<int> VectorMask,
12990                                            SDValue VecIn1, SDValue VecIn2,
12991                                            unsigned LeftIdx) {
12992   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12993   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
12994 
12995   EVT VT = N->getValueType(0);
12996   EVT InVT1 = VecIn1.getValueType();
12997   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
12998 
12999   unsigned Vec2Offset = InVT1.getVectorNumElements();
13000   unsigned NumElems = VT.getVectorNumElements();
13001   unsigned ShuffleNumElems = NumElems;
13002 
13003   // We can't generate a shuffle node with mismatched input and output types.
13004   // Try to make the types match the type of the output.
13005   if (InVT1 != VT || InVT2 != VT) {
13006     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13007       // If the output vector length is a multiple of both input lengths,
13008       // we can concatenate them and pad the rest with undefs.
13009       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13010       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13011       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13012       ConcatOps[0] = VecIn1;
13013       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13014       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13015       VecIn2 = SDValue();
13016     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13017       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13018         return SDValue();
13019 
13020       if (!VecIn2.getNode()) {
13021         // If we only have one input vector, and it's twice the size of the
13022         // output, split it in two.
13023         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13024                              DAG.getConstant(NumElems, DL, IdxTy));
13025         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13026         // Since we now have shorter input vectors, adjust the offset of the
13027         // second vector's start.
13028         Vec2Offset = NumElems;
13029       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13030         // VecIn1 is wider than the output, and we have another, possibly
13031         // smaller input. Pad the smaller input with undefs, shuffle at the
13032         // input vector width, and extract the output.
13033         // The shuffle type is different than VT, so check legality again.
13034         if (LegalOperations &&
13035             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13036           return SDValue();
13037 
13038         if (InVT1 != InVT2)
13039           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13040                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13041         ShuffleNumElems = NumElems * 2;
13042       } else {
13043         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13044         // than VecIn1. We can't handle this for now - this case will disappear
13045         // when we start sorting the vectors by type.
13046         return SDValue();
13047       }
13048     } else {
13049       // TODO: Support cases where the length mismatch isn't exactly by a
13050       // factor of 2.
13051       // TODO: Move this check upwards, so that if we have bad type
13052       // mismatches, we don't create any DAG nodes.
13053       return SDValue();
13054     }
13055   }
13056 
13057   // Initialize mask to undef.
13058   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13059 
13060   // Only need to run up to the number of elements actually used, not the
13061   // total number of elements in the shuffle - if we are shuffling a wider
13062   // vector, the high lanes should be set to undef.
13063   for (unsigned i = 0; i != NumElems; ++i) {
13064     if (VectorMask[i] <= 0)
13065       continue;
13066 
13067     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13068     if (VectorMask[i] == (int)LeftIdx) {
13069       Mask[i] = ExtIndex;
13070     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13071       Mask[i] = Vec2Offset + ExtIndex;
13072     }
13073   }
13074 
13075   // The type the input vectors may have changed above.
13076   InVT1 = VecIn1.getValueType();
13077 
13078   // If we already have a VecIn2, it should have the same type as VecIn1.
13079   // If we don't, get an undef/zero vector of the appropriate type.
13080   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13081   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13082 
13083   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13084   if (ShuffleNumElems > NumElems)
13085     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13086 
13087   return Shuffle;
13088 }
13089 
13090 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13091 // operations. If the types of the vectors we're extracting from allow it,
13092 // turn this into a vector_shuffle node.
13093 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13094   SDLoc DL(N);
13095   EVT VT = N->getValueType(0);
13096 
13097   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13098   if (!isTypeLegal(VT))
13099     return SDValue();
13100 
13101   // May only combine to shuffle after legalize if shuffle is legal.
13102   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13103     return SDValue();
13104 
13105   bool UsesZeroVector = false;
13106   unsigned NumElems = N->getNumOperands();
13107 
13108   // Record, for each element of the newly built vector, which input vector
13109   // that element comes from. -1 stands for undef, 0 for the zero vector,
13110   // and positive values for the input vectors.
13111   // VectorMask maps each element to its vector number, and VecIn maps vector
13112   // numbers to their initial SDValues.
13113 
13114   SmallVector<int, 8> VectorMask(NumElems, -1);
13115   SmallVector<SDValue, 8> VecIn;
13116   VecIn.push_back(SDValue());
13117 
13118   for (unsigned i = 0; i != NumElems; ++i) {
13119     SDValue Op = N->getOperand(i);
13120 
13121     if (Op.isUndef())
13122       continue;
13123 
13124     // See if we can use a blend with a zero vector.
13125     // TODO: Should we generalize this to a blend with an arbitrary constant
13126     // vector?
13127     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13128       UsesZeroVector = true;
13129       VectorMask[i] = 0;
13130       continue;
13131     }
13132 
13133     // Not an undef or zero. If the input is something other than an
13134     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13135     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13136         !isa<ConstantSDNode>(Op.getOperand(1)))
13137       return SDValue();
13138 
13139     SDValue ExtractedFromVec = Op.getOperand(0);
13140 
13141     // All inputs must have the same element type as the output.
13142     if (VT.getVectorElementType() !=
13143         ExtractedFromVec.getValueType().getVectorElementType())
13144       return SDValue();
13145 
13146     // Have we seen this input vector before?
13147     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13148     // a map back from SDValues to numbers isn't worth it.
13149     unsigned Idx = std::distance(
13150         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13151     if (Idx == VecIn.size())
13152       VecIn.push_back(ExtractedFromVec);
13153 
13154     VectorMask[i] = Idx;
13155   }
13156 
13157   // If we didn't find at least one input vector, bail out.
13158   if (VecIn.size() < 2)
13159     return SDValue();
13160 
13161   // TODO: We want to sort the vectors by descending length, so that adjacent
13162   // pairs have similar length, and the longer vector is always first in the
13163   // pair.
13164 
13165   // TODO: Should this fire if some of the input vectors has illegal type (like
13166   // it does now), or should we let legalization run its course first?
13167 
13168   // Shuffle phase:
13169   // Take pairs of vectors, and shuffle them so that the result has elements
13170   // from these vectors in the correct places.
13171   // For example, given:
13172   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13173   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13174   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13175   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13176   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13177   // We will generate:
13178   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13179   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13180   SmallVector<SDValue, 4> Shuffles;
13181   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13182     unsigned LeftIdx = 2 * In + 1;
13183     SDValue VecLeft = VecIn[LeftIdx];
13184     SDValue VecRight =
13185         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13186 
13187     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13188                                                 VecRight, LeftIdx))
13189       Shuffles.push_back(Shuffle);
13190     else
13191       return SDValue();
13192   }
13193 
13194   // If we need the zero vector as an "ingredient" in the blend tree, add it
13195   // to the list of shuffles.
13196   if (UsesZeroVector)
13197     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13198                                       : DAG.getConstantFP(0.0, DL, VT));
13199 
13200   // If we only have one shuffle, we're done.
13201   if (Shuffles.size() == 1)
13202     return Shuffles[0];
13203 
13204   // Update the vector mask to point to the post-shuffle vectors.
13205   for (int &Vec : VectorMask)
13206     if (Vec == 0)
13207       Vec = Shuffles.size() - 1;
13208     else
13209       Vec = (Vec - 1) / 2;
13210 
13211   // More than one shuffle. Generate a binary tree of blends, e.g. if from
13212   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13213   // generate:
13214   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13215   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13216   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13217   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13218   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13219   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13220   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13221 
13222   // Make sure the initial size of the shuffle list is even.
13223   if (Shuffles.size() % 2)
13224     Shuffles.push_back(DAG.getUNDEF(VT));
13225 
13226   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13227     if (CurSize % 2) {
13228       Shuffles[CurSize] = DAG.getUNDEF(VT);
13229       CurSize++;
13230     }
13231     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13232       int Left = 2 * In;
13233       int Right = 2 * In + 1;
13234       SmallVector<int, 8> Mask(NumElems, -1);
13235       for (unsigned i = 0; i != NumElems; ++i) {
13236         if (VectorMask[i] == Left) {
13237           Mask[i] = i;
13238           VectorMask[i] = In;
13239         } else if (VectorMask[i] == Right) {
13240           Mask[i] = i + NumElems;
13241           VectorMask[i] = In;
13242         }
13243       }
13244 
13245       Shuffles[In] =
13246           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13247     }
13248   }
13249 
13250   return Shuffles[0];
13251 }
13252 
13253 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13254   EVT VT = N->getValueType(0);
13255 
13256   // A vector built entirely of undefs is undef.
13257   if (ISD::allOperandsUndef(N))
13258     return DAG.getUNDEF(VT);
13259 
13260   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13261     return V;
13262 
13263   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13264     return V;
13265 
13266   if (SDValue V = reduceBuildVecToShuffle(N))
13267     return V;
13268 
13269   return SDValue();
13270 }
13271 
13272 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13274   EVT OpVT = N->getOperand(0).getValueType();
13275 
13276   // If the operands are legal vectors, leave them alone.
13277   if (TLI.isTypeLegal(OpVT))
13278     return SDValue();
13279 
13280   SDLoc DL(N);
13281   EVT VT = N->getValueType(0);
13282   SmallVector<SDValue, 8> Ops;
13283 
13284   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13285   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13286 
13287   // Keep track of what we encounter.
13288   bool AnyInteger = false;
13289   bool AnyFP = false;
13290   for (const SDValue &Op : N->ops()) {
13291     if (ISD::BITCAST == Op.getOpcode() &&
13292         !Op.getOperand(0).getValueType().isVector())
13293       Ops.push_back(Op.getOperand(0));
13294     else if (ISD::UNDEF == Op.getOpcode())
13295       Ops.push_back(ScalarUndef);
13296     else
13297       return SDValue();
13298 
13299     // Note whether we encounter an integer or floating point scalar.
13300     // If it's neither, bail out, it could be something weird like x86mmx.
13301     EVT LastOpVT = Ops.back().getValueType();
13302     if (LastOpVT.isFloatingPoint())
13303       AnyFP = true;
13304     else if (LastOpVT.isInteger())
13305       AnyInteger = true;
13306     else
13307       return SDValue();
13308   }
13309 
13310   // If any of the operands is a floating point scalar bitcast to a vector,
13311   // use floating point types throughout, and bitcast everything.
13312   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
13313   if (AnyFP) {
13314     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
13315     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13316     if (AnyInteger) {
13317       for (SDValue &Op : Ops) {
13318         if (Op.getValueType() == SVT)
13319           continue;
13320         if (Op.isUndef())
13321           Op = ScalarUndef;
13322         else
13323           Op = DAG.getBitcast(SVT, Op);
13324       }
13325     }
13326   }
13327 
13328   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
13329                                VT.getSizeInBits() / SVT.getSizeInBits());
13330   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
13331 }
13332 
13333 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
13334 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
13335 // most two distinct vectors the same size as the result, attempt to turn this
13336 // into a legal shuffle.
13337 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
13338   EVT VT = N->getValueType(0);
13339   EVT OpVT = N->getOperand(0).getValueType();
13340   int NumElts = VT.getVectorNumElements();
13341   int NumOpElts = OpVT.getVectorNumElements();
13342 
13343   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
13344   SmallVector<int, 8> Mask;
13345 
13346   for (SDValue Op : N->ops()) {
13347     // Peek through any bitcast.
13348     while (Op.getOpcode() == ISD::BITCAST)
13349       Op = Op.getOperand(0);
13350 
13351     // UNDEF nodes convert to UNDEF shuffle mask values.
13352     if (Op.isUndef()) {
13353       Mask.append((unsigned)NumOpElts, -1);
13354       continue;
13355     }
13356 
13357     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13358       return SDValue();
13359 
13360     // What vector are we extracting the subvector from and at what index?
13361     SDValue ExtVec = Op.getOperand(0);
13362 
13363     // We want the EVT of the original extraction to correctly scale the
13364     // extraction index.
13365     EVT ExtVT = ExtVec.getValueType();
13366 
13367     // Peek through any bitcast.
13368     while (ExtVec.getOpcode() == ISD::BITCAST)
13369       ExtVec = ExtVec.getOperand(0);
13370 
13371     // UNDEF nodes convert to UNDEF shuffle mask values.
13372     if (ExtVec.isUndef()) {
13373       Mask.append((unsigned)NumOpElts, -1);
13374       continue;
13375     }
13376 
13377     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13378       return SDValue();
13379     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13380 
13381     // Ensure that we are extracting a subvector from a vector the same
13382     // size as the result.
13383     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13384       return SDValue();
13385 
13386     // Scale the subvector index to account for any bitcast.
13387     int NumExtElts = ExtVT.getVectorNumElements();
13388     if (0 == (NumExtElts % NumElts))
13389       ExtIdx /= (NumExtElts / NumElts);
13390     else if (0 == (NumElts % NumExtElts))
13391       ExtIdx *= (NumElts / NumExtElts);
13392     else
13393       return SDValue();
13394 
13395     // At most we can reference 2 inputs in the final shuffle.
13396     if (SV0.isUndef() || SV0 == ExtVec) {
13397       SV0 = ExtVec;
13398       for (int i = 0; i != NumOpElts; ++i)
13399         Mask.push_back(i + ExtIdx);
13400     } else if (SV1.isUndef() || SV1 == ExtVec) {
13401       SV1 = ExtVec;
13402       for (int i = 0; i != NumOpElts; ++i)
13403         Mask.push_back(i + ExtIdx + NumElts);
13404     } else {
13405       return SDValue();
13406     }
13407   }
13408 
13409   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13410     return SDValue();
13411 
13412   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13413                               DAG.getBitcast(VT, SV1), Mask);
13414 }
13415 
13416 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13417   // If we only have one input vector, we don't need to do any concatenation.
13418   if (N->getNumOperands() == 1)
13419     return N->getOperand(0);
13420 
13421   // Check if all of the operands are undefs.
13422   EVT VT = N->getValueType(0);
13423   if (ISD::allOperandsUndef(N))
13424     return DAG.getUNDEF(VT);
13425 
13426   // Optimize concat_vectors where all but the first of the vectors are undef.
13427   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13428         return Op.isUndef();
13429       })) {
13430     SDValue In = N->getOperand(0);
13431     assert(In.getValueType().isVector() && "Must concat vectors");
13432 
13433     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13434     if (In->getOpcode() == ISD::BITCAST &&
13435         !In->getOperand(0)->getValueType(0).isVector()) {
13436       SDValue Scalar = In->getOperand(0);
13437 
13438       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13439       // look through the trunc so we can still do the transform:
13440       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13441       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13442           !TLI.isTypeLegal(Scalar.getValueType()) &&
13443           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13444         Scalar = Scalar->getOperand(0);
13445 
13446       EVT SclTy = Scalar->getValueType(0);
13447 
13448       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13449         return SDValue();
13450 
13451       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13452                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13453       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13454         return SDValue();
13455 
13456       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
13457       return DAG.getBitcast(VT, Res);
13458     }
13459   }
13460 
13461   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13462   // We have already tested above for an UNDEF only concatenation.
13463   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13464   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13465   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13466     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13467   };
13468   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13469     SmallVector<SDValue, 8> Opnds;
13470     EVT SVT = VT.getScalarType();
13471 
13472     EVT MinVT = SVT;
13473     if (!SVT.isFloatingPoint()) {
13474       // If BUILD_VECTOR are from built from integer, they may have different
13475       // operand types. Get the smallest type and truncate all operands to it.
13476       bool FoundMinVT = false;
13477       for (const SDValue &Op : N->ops())
13478         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13479           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13480           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13481           FoundMinVT = true;
13482         }
13483       assert(FoundMinVT && "Concat vector type mismatch");
13484     }
13485 
13486     for (const SDValue &Op : N->ops()) {
13487       EVT OpVT = Op.getValueType();
13488       unsigned NumElts = OpVT.getVectorNumElements();
13489 
13490       if (ISD::UNDEF == Op.getOpcode())
13491         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13492 
13493       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13494         if (SVT.isFloatingPoint()) {
13495           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13496           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13497         } else {
13498           for (unsigned i = 0; i != NumElts; ++i)
13499             Opnds.push_back(
13500                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13501         }
13502       }
13503     }
13504 
13505     assert(VT.getVectorNumElements() == Opnds.size() &&
13506            "Concat vector type mismatch");
13507     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13508   }
13509 
13510   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13511   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13512     return V;
13513 
13514   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13515   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13516     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13517       return V;
13518 
13519   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13520   // nodes often generate nop CONCAT_VECTOR nodes.
13521   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13522   // place the incoming vectors at the exact same location.
13523   SDValue SingleSource = SDValue();
13524   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13525 
13526   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13527     SDValue Op = N->getOperand(i);
13528 
13529     if (Op.isUndef())
13530       continue;
13531 
13532     // Check if this is the identity extract:
13533     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13534       return SDValue();
13535 
13536     // Find the single incoming vector for the extract_subvector.
13537     if (SingleSource.getNode()) {
13538       if (Op.getOperand(0) != SingleSource)
13539         return SDValue();
13540     } else {
13541       SingleSource = Op.getOperand(0);
13542 
13543       // Check the source type is the same as the type of the result.
13544       // If not, this concat may extend the vector, so we can not
13545       // optimize it away.
13546       if (SingleSource.getValueType() != N->getValueType(0))
13547         return SDValue();
13548     }
13549 
13550     unsigned IdentityIndex = i * PartNumElem;
13551     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13552     // The extract index must be constant.
13553     if (!CS)
13554       return SDValue();
13555 
13556     // Check that we are reading from the identity index.
13557     if (CS->getZExtValue() != IdentityIndex)
13558       return SDValue();
13559   }
13560 
13561   if (SingleSource.getNode())
13562     return SingleSource;
13563 
13564   return SDValue();
13565 }
13566 
13567 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13568   EVT NVT = N->getValueType(0);
13569   SDValue V = N->getOperand(0);
13570 
13571   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13572     // Combine:
13573     //    (extract_subvec (concat V1, V2, ...), i)
13574     // Into:
13575     //    Vi if possible
13576     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13577     // type.
13578     if (V->getOperand(0).getValueType() != NVT)
13579       return SDValue();
13580     unsigned Idx = N->getConstantOperandVal(1);
13581     unsigned NumElems = NVT.getVectorNumElements();
13582     assert((Idx % NumElems) == 0 &&
13583            "IDX in concat is not a multiple of the result vector length.");
13584     return V->getOperand(Idx / NumElems);
13585   }
13586 
13587   // Skip bitcasting
13588   if (V->getOpcode() == ISD::BITCAST)
13589     V = V.getOperand(0);
13590 
13591   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13592     // Handle only simple case where vector being inserted and vector
13593     // being extracted are of same type, and are half size of larger vectors.
13594     EVT BigVT = V->getOperand(0).getValueType();
13595     EVT SmallVT = V->getOperand(1).getValueType();
13596     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13597       return SDValue();
13598 
13599     // Only handle cases where both indexes are constants with the same type.
13600     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13601     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13602 
13603     if (InsIdx && ExtIdx &&
13604         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13605         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13606       // Combine:
13607       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13608       // Into:
13609       //    indices are equal or bit offsets are equal => V1
13610       //    otherwise => (extract_subvec V1, ExtIdx)
13611       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
13612           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
13613         return DAG.getBitcast(NVT, V->getOperand(1));
13614       return DAG.getNode(
13615           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
13616           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13617           N->getOperand(1));
13618     }
13619   }
13620 
13621   return SDValue();
13622 }
13623 
13624 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13625                                                  SDValue V, SelectionDAG &DAG) {
13626   SDLoc DL(V);
13627   EVT VT = V.getValueType();
13628 
13629   switch (V.getOpcode()) {
13630   default:
13631     return V;
13632 
13633   case ISD::CONCAT_VECTORS: {
13634     EVT OpVT = V->getOperand(0).getValueType();
13635     int OpSize = OpVT.getVectorNumElements();
13636     SmallBitVector OpUsedElements(OpSize, false);
13637     bool FoundSimplification = false;
13638     SmallVector<SDValue, 4> NewOps;
13639     NewOps.reserve(V->getNumOperands());
13640     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13641       SDValue Op = V->getOperand(i);
13642       bool OpUsed = false;
13643       for (int j = 0; j < OpSize; ++j)
13644         if (UsedElements[i * OpSize + j]) {
13645           OpUsedElements[j] = true;
13646           OpUsed = true;
13647         }
13648       NewOps.push_back(
13649           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13650                  : DAG.getUNDEF(OpVT));
13651       FoundSimplification |= Op == NewOps.back();
13652       OpUsedElements.reset();
13653     }
13654     if (FoundSimplification)
13655       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13656     return V;
13657   }
13658 
13659   case ISD::INSERT_SUBVECTOR: {
13660     SDValue BaseV = V->getOperand(0);
13661     SDValue SubV = V->getOperand(1);
13662     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13663     if (!IdxN)
13664       return V;
13665 
13666     int SubSize = SubV.getValueType().getVectorNumElements();
13667     int Idx = IdxN->getZExtValue();
13668     bool SubVectorUsed = false;
13669     SmallBitVector SubUsedElements(SubSize, false);
13670     for (int i = 0; i < SubSize; ++i)
13671       if (UsedElements[i + Idx]) {
13672         SubVectorUsed = true;
13673         SubUsedElements[i] = true;
13674         UsedElements[i + Idx] = false;
13675       }
13676 
13677     // Now recurse on both the base and sub vectors.
13678     SDValue SimplifiedSubV =
13679         SubVectorUsed
13680             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13681             : DAG.getUNDEF(SubV.getValueType());
13682     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13683     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13684       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13685                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13686     return V;
13687   }
13688   }
13689 }
13690 
13691 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13692                                        SDValue N1, SelectionDAG &DAG) {
13693   EVT VT = SVN->getValueType(0);
13694   int NumElts = VT.getVectorNumElements();
13695   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13696   for (int M : SVN->getMask())
13697     if (M >= 0 && M < NumElts)
13698       N0UsedElements[M] = true;
13699     else if (M >= NumElts)
13700       N1UsedElements[M - NumElts] = true;
13701 
13702   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13703   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13704   if (S0 == N0 && S1 == N1)
13705     return SDValue();
13706 
13707   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13708 }
13709 
13710 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13711 // or turn a shuffle of a single concat into simpler shuffle then concat.
13712 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13713   EVT VT = N->getValueType(0);
13714   unsigned NumElts = VT.getVectorNumElements();
13715 
13716   SDValue N0 = N->getOperand(0);
13717   SDValue N1 = N->getOperand(1);
13718   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13719 
13720   SmallVector<SDValue, 4> Ops;
13721   EVT ConcatVT = N0.getOperand(0).getValueType();
13722   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13723   unsigned NumConcats = NumElts / NumElemsPerConcat;
13724 
13725   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13726   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13727   // half vector elements.
13728   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13729       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13730                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13731     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13732                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13733     N1 = DAG.getUNDEF(ConcatVT);
13734     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13735   }
13736 
13737   // Look at every vector that's inserted. We're looking for exact
13738   // subvector-sized copies from a concatenated vector
13739   for (unsigned I = 0; I != NumConcats; ++I) {
13740     // Make sure we're dealing with a copy.
13741     unsigned Begin = I * NumElemsPerConcat;
13742     bool AllUndef = true, NoUndef = true;
13743     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13744       if (SVN->getMaskElt(J) >= 0)
13745         AllUndef = false;
13746       else
13747         NoUndef = false;
13748     }
13749 
13750     if (NoUndef) {
13751       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13752         return SDValue();
13753 
13754       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13755         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13756           return SDValue();
13757 
13758       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13759       if (FirstElt < N0.getNumOperands())
13760         Ops.push_back(N0.getOperand(FirstElt));
13761       else
13762         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13763 
13764     } else if (AllUndef) {
13765       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13766     } else { // Mixed with general masks and undefs, can't do optimization.
13767       return SDValue();
13768     }
13769   }
13770 
13771   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13772 }
13773 
13774 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13775 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13776 // This combine is done in the following cases:
13777 // 1. Both N0,N1 are BUILD_VECTOR's composed of constants or undefs.
13778 // 2. Only one of N0,N1 is a BUILD_VECTOR composed of constants or undefs -
13779 //    Combine iff that node is ALL_ZEROS. We prefer not to combine a
13780 //    BUILD_VECTOR of all constants to allow efficient materialization of
13781 //    constant vectors, but the ALL_ZEROS is an exception because
13782 //    zero-extension matching seems to rely on having BUILD_VECTOR nodes with
13783 //    zero padding between elements. FIXME: Eliminate this exception for
13784 //    ALL_ZEROS constant vectors.
13785 // 3. Neither N0,N1 are composed of only constants.
13786 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
13787                                        SelectionDAG &DAG,
13788                                        const TargetLowering &TLI) {
13789   EVT VT = SVN->getValueType(0);
13790   unsigned NumElts = VT.getVectorNumElements();
13791   SDValue N0 = SVN->getOperand(0);
13792   SDValue N1 = SVN->getOperand(1);
13793 
13794   if (!N0->hasOneUse() || !N1->hasOneUse())
13795     return SDValue();
13796   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
13797   // discussed above.
13798   if (!N1.isUndef()) {
13799     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
13800     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
13801     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
13802       return SDValue();
13803     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
13804       return SDValue();
13805   }
13806 
13807   SmallVector<SDValue, 8> Ops;
13808   for (int M : SVN->getMask()) {
13809     SDValue Op = DAG.getUNDEF(VT.getScalarType());
13810     if (M >= 0) {
13811       int Idx = M < (int)NumElts ? M : M - NumElts;
13812       SDValue &S = (M < (int)NumElts ? N0 : N1);
13813       if (S.getOpcode() == ISD::BUILD_VECTOR) {
13814         Op = S.getOperand(Idx);
13815       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13816         if (Idx == 0)
13817           Op = S.getOperand(0);
13818       } else {
13819         // Operand can't be combined - bail out.
13820         return SDValue();
13821       }
13822     }
13823     Ops.push_back(Op);
13824   }
13825   // BUILD_VECTOR requires all inputs to be of the same type, find the
13826   // maximum type and extend them all.
13827   EVT SVT = VT.getScalarType();
13828   if (SVT.isInteger())
13829     for (SDValue &Op : Ops)
13830       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13831   if (SVT != VT.getScalarType())
13832     for (SDValue &Op : Ops)
13833       Op = TLI.isZExtFree(Op.getValueType(), SVT)
13834                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
13835                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
13836   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
13837 }
13838 
13839 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13840   EVT VT = N->getValueType(0);
13841   unsigned NumElts = VT.getVectorNumElements();
13842 
13843   SDValue N0 = N->getOperand(0);
13844   SDValue N1 = N->getOperand(1);
13845 
13846   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13847 
13848   // Canonicalize shuffle undef, undef -> undef
13849   if (N0.isUndef() && N1.isUndef())
13850     return DAG.getUNDEF(VT);
13851 
13852   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13853 
13854   // Canonicalize shuffle v, v -> v, undef
13855   if (N0 == N1) {
13856     SmallVector<int, 8> NewMask;
13857     for (unsigned i = 0; i != NumElts; ++i) {
13858       int Idx = SVN->getMaskElt(i);
13859       if (Idx >= (int)NumElts) Idx -= NumElts;
13860       NewMask.push_back(Idx);
13861     }
13862     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
13863   }
13864 
13865   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13866   if (N0.isUndef())
13867     return DAG.getCommutedVectorShuffle(*SVN);
13868 
13869   // Remove references to rhs if it is undef
13870   if (N1.isUndef()) {
13871     bool Changed = false;
13872     SmallVector<int, 8> NewMask;
13873     for (unsigned i = 0; i != NumElts; ++i) {
13874       int Idx = SVN->getMaskElt(i);
13875       if (Idx >= (int)NumElts) {
13876         Idx = -1;
13877         Changed = true;
13878       }
13879       NewMask.push_back(Idx);
13880     }
13881     if (Changed)
13882       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
13883   }
13884 
13885   // If it is a splat, check if the argument vector is another splat or a
13886   // build_vector.
13887   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13888     SDNode *V = N0.getNode();
13889 
13890     // If this is a bit convert that changes the element type of the vector but
13891     // not the number of vector elements, look through it.  Be careful not to
13892     // look though conversions that change things like v4f32 to v2f64.
13893     if (V->getOpcode() == ISD::BITCAST) {
13894       SDValue ConvInput = V->getOperand(0);
13895       if (ConvInput.getValueType().isVector() &&
13896           ConvInput.getValueType().getVectorNumElements() == NumElts)
13897         V = ConvInput.getNode();
13898     }
13899 
13900     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13901       assert(V->getNumOperands() == NumElts &&
13902              "BUILD_VECTOR has wrong number of operands");
13903       SDValue Base;
13904       bool AllSame = true;
13905       for (unsigned i = 0; i != NumElts; ++i) {
13906         if (!V->getOperand(i).isUndef()) {
13907           Base = V->getOperand(i);
13908           break;
13909         }
13910       }
13911       // Splat of <u, u, u, u>, return <u, u, u, u>
13912       if (!Base.getNode())
13913         return N0;
13914       for (unsigned i = 0; i != NumElts; ++i) {
13915         if (V->getOperand(i) != Base) {
13916           AllSame = false;
13917           break;
13918         }
13919       }
13920       // Splat of <x, x, x, x>, return <x, x, x, x>
13921       if (AllSame)
13922         return N0;
13923 
13924       // Canonicalize any other splat as a build_vector.
13925       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13926       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13927       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13928 
13929       // We may have jumped through bitcasts, so the type of the
13930       // BUILD_VECTOR may not match the type of the shuffle.
13931       if (V->getValueType(0) != VT)
13932         NewBV = DAG.getBitcast(VT, NewBV);
13933       return NewBV;
13934     }
13935   }
13936 
13937   // There are various patterns used to build up a vector from smaller vectors,
13938   // subvectors, or elements. Scan chains of these and replace unused insertions
13939   // or components with undef.
13940   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13941     return S;
13942 
13943   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13944       Level < AfterLegalizeVectorOps &&
13945       (N1.isUndef() ||
13946       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13947        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13948     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13949       return V;
13950   }
13951 
13952   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13953   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13954   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13955     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
13956       return Res;
13957 
13958   // If this shuffle only has a single input that is a bitcasted shuffle,
13959   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13960   // back to their original types.
13961   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13962       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13963       TLI.isTypeLegal(VT)) {
13964 
13965     // Peek through the bitcast only if there is one user.
13966     SDValue BC0 = N0;
13967     while (BC0.getOpcode() == ISD::BITCAST) {
13968       if (!BC0.hasOneUse())
13969         break;
13970       BC0 = BC0.getOperand(0);
13971     }
13972 
13973     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13974       if (Scale == 1)
13975         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13976 
13977       SmallVector<int, 8> NewMask;
13978       for (int M : Mask)
13979         for (int s = 0; s != Scale; ++s)
13980           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13981       return NewMask;
13982     };
13983 
13984     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13985       EVT SVT = VT.getScalarType();
13986       EVT InnerVT = BC0->getValueType(0);
13987       EVT InnerSVT = InnerVT.getScalarType();
13988 
13989       // Determine which shuffle works with the smaller scalar type.
13990       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13991       EVT ScaleSVT = ScaleVT.getScalarType();
13992 
13993       if (TLI.isTypeLegal(ScaleVT) &&
13994           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13995           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13996 
13997         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13998         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13999 
14000         // Scale the shuffle masks to the smaller scalar type.
14001         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
14002         SmallVector<int, 8> InnerMask =
14003             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
14004         SmallVector<int, 8> OuterMask =
14005             ScaleShuffleMask(SVN->getMask(), OuterScale);
14006 
14007         // Merge the shuffle masks.
14008         SmallVector<int, 8> NewMask;
14009         for (int M : OuterMask)
14010           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
14011 
14012         // Test for shuffle mask legality over both commutations.
14013         SDValue SV0 = BC0->getOperand(0);
14014         SDValue SV1 = BC0->getOperand(1);
14015         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14016         if (!LegalMask) {
14017           std::swap(SV0, SV1);
14018           ShuffleVectorSDNode::commuteMask(NewMask);
14019           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14020         }
14021 
14022         if (LegalMask) {
14023           SV0 = DAG.getBitcast(ScaleVT, SV0);
14024           SV1 = DAG.getBitcast(ScaleVT, SV1);
14025           return DAG.getBitcast(
14026               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
14027         }
14028       }
14029     }
14030   }
14031 
14032   // Canonicalize shuffles according to rules:
14033   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
14034   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
14035   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
14036   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
14037       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
14038       TLI.isTypeLegal(VT)) {
14039     // The incoming shuffle must be of the same type as the result of the
14040     // current shuffle.
14041     assert(N1->getOperand(0).getValueType() == VT &&
14042            "Shuffle types don't match");
14043 
14044     SDValue SV0 = N1->getOperand(0);
14045     SDValue SV1 = N1->getOperand(1);
14046     bool HasSameOp0 = N0 == SV0;
14047     bool IsSV1Undef = SV1.isUndef();
14048     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
14049       // Commute the operands of this shuffle so that next rule
14050       // will trigger.
14051       return DAG.getCommutedVectorShuffle(*SVN);
14052   }
14053 
14054   // Try to fold according to rules:
14055   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14056   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14057   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14058   // Don't try to fold shuffles with illegal type.
14059   // Only fold if this shuffle is the only user of the other shuffle.
14060   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14061       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14062     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14063 
14064     // The incoming shuffle must be of the same type as the result of the
14065     // current shuffle.
14066     assert(OtherSV->getOperand(0).getValueType() == VT &&
14067            "Shuffle types don't match");
14068 
14069     SDValue SV0, SV1;
14070     SmallVector<int, 4> Mask;
14071     // Compute the combined shuffle mask for a shuffle with SV0 as the first
14072     // operand, and SV1 as the second operand.
14073     for (unsigned i = 0; i != NumElts; ++i) {
14074       int Idx = SVN->getMaskElt(i);
14075       if (Idx < 0) {
14076         // Propagate Undef.
14077         Mask.push_back(Idx);
14078         continue;
14079       }
14080 
14081       SDValue CurrentVec;
14082       if (Idx < (int)NumElts) {
14083         // This shuffle index refers to the inner shuffle N0. Lookup the inner
14084         // shuffle mask to identify which vector is actually referenced.
14085         Idx = OtherSV->getMaskElt(Idx);
14086         if (Idx < 0) {
14087           // Propagate Undef.
14088           Mask.push_back(Idx);
14089           continue;
14090         }
14091 
14092         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14093                                            : OtherSV->getOperand(1);
14094       } else {
14095         // This shuffle index references an element within N1.
14096         CurrentVec = N1;
14097       }
14098 
14099       // Simple case where 'CurrentVec' is UNDEF.
14100       if (CurrentVec.isUndef()) {
14101         Mask.push_back(-1);
14102         continue;
14103       }
14104 
14105       // Canonicalize the shuffle index. We don't know yet if CurrentVec
14106       // will be the first or second operand of the combined shuffle.
14107       Idx = Idx % NumElts;
14108       if (!SV0.getNode() || SV0 == CurrentVec) {
14109         // Ok. CurrentVec is the left hand side.
14110         // Update the mask accordingly.
14111         SV0 = CurrentVec;
14112         Mask.push_back(Idx);
14113         continue;
14114       }
14115 
14116       // Bail out if we cannot convert the shuffle pair into a single shuffle.
14117       if (SV1.getNode() && SV1 != CurrentVec)
14118         return SDValue();
14119 
14120       // Ok. CurrentVec is the right hand side.
14121       // Update the mask accordingly.
14122       SV1 = CurrentVec;
14123       Mask.push_back(Idx + NumElts);
14124     }
14125 
14126     // Check if all indices in Mask are Undef. In case, propagate Undef.
14127     bool isUndefMask = true;
14128     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14129       isUndefMask &= Mask[i] < 0;
14130 
14131     if (isUndefMask)
14132       return DAG.getUNDEF(VT);
14133 
14134     if (!SV0.getNode())
14135       SV0 = DAG.getUNDEF(VT);
14136     if (!SV1.getNode())
14137       SV1 = DAG.getUNDEF(VT);
14138 
14139     // Avoid introducing shuffles with illegal mask.
14140     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14141       ShuffleVectorSDNode::commuteMask(Mask);
14142 
14143       if (!TLI.isShuffleMaskLegal(Mask, VT))
14144         return SDValue();
14145 
14146       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14147       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14148       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14149       std::swap(SV0, SV1);
14150     }
14151 
14152     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14153     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14154     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14155     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14156   }
14157 
14158   return SDValue();
14159 }
14160 
14161 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14162   SDValue InVal = N->getOperand(0);
14163   EVT VT = N->getValueType(0);
14164 
14165   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14166   // with a VECTOR_SHUFFLE.
14167   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14168     SDValue InVec = InVal->getOperand(0);
14169     SDValue EltNo = InVal->getOperand(1);
14170 
14171     // FIXME: We could support implicit truncation if the shuffle can be
14172     // scaled to a smaller vector scalar type.
14173     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
14174     if (C0 && VT == InVec.getValueType() &&
14175         VT.getScalarType() == InVal.getValueType()) {
14176       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
14177       int Elt = C0->getZExtValue();
14178       NewMask[0] = Elt;
14179 
14180       if (TLI.isShuffleMaskLegal(NewMask, VT))
14181         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
14182                                     NewMask);
14183     }
14184   }
14185 
14186   return SDValue();
14187 }
14188 
14189 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
14190   EVT VT = N->getValueType(0);
14191   SDValue N0 = N->getOperand(0);
14192   SDValue N1 = N->getOperand(1);
14193   SDValue N2 = N->getOperand(2);
14194 
14195   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
14196   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
14197   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
14198   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
14199       N0.getOperand(1).getValueType() == N1.getValueType() &&
14200       N0.getOperand(2) == N2)
14201     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
14202                        N1, N2);
14203 
14204   if (N0.getValueType() != N1.getValueType())
14205     return SDValue();
14206 
14207   // If the input vector is a concatenation, and the insert replaces
14208   // one of the halves, we can optimize into a single concat_vectors.
14209   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
14210       N2.getOpcode() == ISD::Constant) {
14211     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
14212 
14213     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14214     // (concat_vectors Z, Y)
14215     if (InsIdx == 0)
14216       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
14217                          N0.getOperand(1));
14218 
14219     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14220     // (concat_vectors X, Z)
14221     if (InsIdx == VT.getVectorNumElements() / 2)
14222       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
14223                          N1);
14224   }
14225 
14226   return SDValue();
14227 }
14228 
14229 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
14230   SDValue N0 = N->getOperand(0);
14231 
14232   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
14233   if (N0->getOpcode() == ISD::FP16_TO_FP)
14234     return N0->getOperand(0);
14235 
14236   return SDValue();
14237 }
14238 
14239 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
14240   SDValue N0 = N->getOperand(0);
14241 
14242   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
14243   if (N0->getOpcode() == ISD::AND) {
14244     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
14245     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
14246       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
14247                          N0.getOperand(0));
14248     }
14249   }
14250 
14251   return SDValue();
14252 }
14253 
14254 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
14255 /// with the destination vector and a zero vector.
14256 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
14257 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
14258 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
14259   EVT VT = N->getValueType(0);
14260   SDValue LHS = N->getOperand(0);
14261   SDValue RHS = N->getOperand(1);
14262   SDLoc DL(N);
14263 
14264   // Make sure we're not running after operation legalization where it
14265   // may have custom lowered the vector shuffles.
14266   if (LegalOperations)
14267     return SDValue();
14268 
14269   if (N->getOpcode() != ISD::AND)
14270     return SDValue();
14271 
14272   if (RHS.getOpcode() == ISD::BITCAST)
14273     RHS = RHS.getOperand(0);
14274 
14275   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
14276     return SDValue();
14277 
14278   EVT RVT = RHS.getValueType();
14279   unsigned NumElts = RHS.getNumOperands();
14280 
14281   // Attempt to create a valid clear mask, splitting the mask into
14282   // sub elements and checking to see if each is
14283   // all zeros or all ones - suitable for shuffle masking.
14284   auto BuildClearMask = [&](int Split) {
14285     int NumSubElts = NumElts * Split;
14286     int NumSubBits = RVT.getScalarSizeInBits() / Split;
14287 
14288     SmallVector<int, 8> Indices;
14289     for (int i = 0; i != NumSubElts; ++i) {
14290       int EltIdx = i / Split;
14291       int SubIdx = i % Split;
14292       SDValue Elt = RHS.getOperand(EltIdx);
14293       if (Elt.isUndef()) {
14294         Indices.push_back(-1);
14295         continue;
14296       }
14297 
14298       APInt Bits;
14299       if (isa<ConstantSDNode>(Elt))
14300         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
14301       else if (isa<ConstantFPSDNode>(Elt))
14302         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
14303       else
14304         return SDValue();
14305 
14306       // Extract the sub element from the constant bit mask.
14307       if (DAG.getDataLayout().isBigEndian()) {
14308         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
14309       } else {
14310         Bits = Bits.lshr(SubIdx * NumSubBits);
14311       }
14312 
14313       if (Split > 1)
14314         Bits = Bits.trunc(NumSubBits);
14315 
14316       if (Bits.isAllOnesValue())
14317         Indices.push_back(i);
14318       else if (Bits == 0)
14319         Indices.push_back(i + NumSubElts);
14320       else
14321         return SDValue();
14322     }
14323 
14324     // Let's see if the target supports this vector_shuffle.
14325     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
14326     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
14327     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
14328       return SDValue();
14329 
14330     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
14331     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
14332                                                    DAG.getBitcast(ClearVT, LHS),
14333                                                    Zero, Indices));
14334   };
14335 
14336   // Determine maximum split level (byte level masking).
14337   int MaxSplit = 1;
14338   if (RVT.getScalarSizeInBits() % 8 == 0)
14339     MaxSplit = RVT.getScalarSizeInBits() / 8;
14340 
14341   for (int Split = 1; Split <= MaxSplit; ++Split)
14342     if (RVT.getScalarSizeInBits() % Split == 0)
14343       if (SDValue S = BuildClearMask(Split))
14344         return S;
14345 
14346   return SDValue();
14347 }
14348 
14349 /// Visit a binary vector operation, like ADD.
14350 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
14351   assert(N->getValueType(0).isVector() &&
14352          "SimplifyVBinOp only works on vectors!");
14353 
14354   SDValue LHS = N->getOperand(0);
14355   SDValue RHS = N->getOperand(1);
14356   SDValue Ops[] = {LHS, RHS};
14357 
14358   // See if we can constant fold the vector operation.
14359   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
14360           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
14361     return Fold;
14362 
14363   // Try to convert a constant mask AND into a shuffle clear mask.
14364   if (SDValue Shuffle = XformToShuffleWithZero(N))
14365     return Shuffle;
14366 
14367   // Type legalization might introduce new shuffles in the DAG.
14368   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
14369   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
14370   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
14371       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
14372       LHS.getOperand(1).isUndef() &&
14373       RHS.getOperand(1).isUndef()) {
14374     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
14375     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
14376 
14377     if (SVN0->getMask().equals(SVN1->getMask())) {
14378       EVT VT = N->getValueType(0);
14379       SDValue UndefVector = LHS.getOperand(1);
14380       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
14381                                      LHS.getOperand(0), RHS.getOperand(0),
14382                                      N->getFlags());
14383       AddUsersToWorklist(N);
14384       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
14385                                   SVN0->getMask());
14386     }
14387   }
14388 
14389   return SDValue();
14390 }
14391 
14392 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
14393                                     SDValue N2) {
14394   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14395 
14396   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14397                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
14398 
14399   // If we got a simplified select_cc node back from SimplifySelectCC, then
14400   // break it down into a new SETCC node, and a new SELECT node, and then return
14401   // the SELECT node, since we were called with a SELECT node.
14402   if (SCC.getNode()) {
14403     // Check to see if we got a select_cc back (to turn into setcc/select).
14404     // Otherwise, just return whatever node we got back, like fabs.
14405     if (SCC.getOpcode() == ISD::SELECT_CC) {
14406       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14407                                   N0.getValueType(),
14408                                   SCC.getOperand(0), SCC.getOperand(1),
14409                                   SCC.getOperand(4));
14410       AddToWorklist(SETCC.getNode());
14411       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14412                            SCC.getOperand(2), SCC.getOperand(3));
14413     }
14414 
14415     return SCC;
14416   }
14417   return SDValue();
14418 }
14419 
14420 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14421 /// being selected between, see if we can simplify the select.  Callers of this
14422 /// should assume that TheSelect is deleted if this returns true.  As such, they
14423 /// should return the appropriate thing (e.g. the node) back to the top-level of
14424 /// the DAG combiner loop to avoid it being looked at.
14425 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14426                                     SDValue RHS) {
14427 
14428   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14429   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14430   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14431     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14432       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14433       SDValue Sqrt = RHS;
14434       ISD::CondCode CC;
14435       SDValue CmpLHS;
14436       const ConstantFPSDNode *Zero = nullptr;
14437 
14438       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14439         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14440         CmpLHS = TheSelect->getOperand(0);
14441         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14442       } else {
14443         // SELECT or VSELECT
14444         SDValue Cmp = TheSelect->getOperand(0);
14445         if (Cmp.getOpcode() == ISD::SETCC) {
14446           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14447           CmpLHS = Cmp.getOperand(0);
14448           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14449         }
14450       }
14451       if (Zero && Zero->isZero() &&
14452           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14453           CC == ISD::SETULT || CC == ISD::SETLT)) {
14454         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14455         CombineTo(TheSelect, Sqrt);
14456         return true;
14457       }
14458     }
14459   }
14460   // Cannot simplify select with vector condition
14461   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14462 
14463   // If this is a select from two identical things, try to pull the operation
14464   // through the select.
14465   if (LHS.getOpcode() != RHS.getOpcode() ||
14466       !LHS.hasOneUse() || !RHS.hasOneUse())
14467     return false;
14468 
14469   // If this is a load and the token chain is identical, replace the select
14470   // of two loads with a load through a select of the address to load from.
14471   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14472   // constants have been dropped into the constant pool.
14473   if (LHS.getOpcode() == ISD::LOAD) {
14474     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14475     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14476 
14477     // Token chains must be identical.
14478     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14479         // Do not let this transformation reduce the number of volatile loads.
14480         LLD->isVolatile() || RLD->isVolatile() ||
14481         // FIXME: If either is a pre/post inc/dec load,
14482         // we'd need to split out the address adjustment.
14483         LLD->isIndexed() || RLD->isIndexed() ||
14484         // If this is an EXTLOAD, the VT's must match.
14485         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14486         // If this is an EXTLOAD, the kind of extension must match.
14487         (LLD->getExtensionType() != RLD->getExtensionType() &&
14488          // The only exception is if one of the extensions is anyext.
14489          LLD->getExtensionType() != ISD::EXTLOAD &&
14490          RLD->getExtensionType() != ISD::EXTLOAD) ||
14491         // FIXME: this discards src value information.  This is
14492         // over-conservative. It would be beneficial to be able to remember
14493         // both potential memory locations.  Since we are discarding
14494         // src value info, don't do the transformation if the memory
14495         // locations are not in the default address space.
14496         LLD->getPointerInfo().getAddrSpace() != 0 ||
14497         RLD->getPointerInfo().getAddrSpace() != 0 ||
14498         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14499                                       LLD->getBasePtr().getValueType()))
14500       return false;
14501 
14502     // Check that the select condition doesn't reach either load.  If so,
14503     // folding this will induce a cycle into the DAG.  If not, this is safe to
14504     // xform, so create a select of the addresses.
14505     SDValue Addr;
14506     if (TheSelect->getOpcode() == ISD::SELECT) {
14507       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14508       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14509           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14510         return false;
14511       // The loads must not depend on one another.
14512       if (LLD->isPredecessorOf(RLD) ||
14513           RLD->isPredecessorOf(LLD))
14514         return false;
14515       Addr = DAG.getSelect(SDLoc(TheSelect),
14516                            LLD->getBasePtr().getValueType(),
14517                            TheSelect->getOperand(0), LLD->getBasePtr(),
14518                            RLD->getBasePtr());
14519     } else {  // Otherwise SELECT_CC
14520       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14521       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14522 
14523       if ((LLD->hasAnyUseOfValue(1) &&
14524            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14525           (RLD->hasAnyUseOfValue(1) &&
14526            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14527         return false;
14528 
14529       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14530                          LLD->getBasePtr().getValueType(),
14531                          TheSelect->getOperand(0),
14532                          TheSelect->getOperand(1),
14533                          LLD->getBasePtr(), RLD->getBasePtr(),
14534                          TheSelect->getOperand(4));
14535     }
14536 
14537     SDValue Load;
14538     // It is safe to replace the two loads if they have different alignments,
14539     // but the new load must be the minimum (most restrictive) alignment of the
14540     // inputs.
14541     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14542     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14543     if (!RLD->isInvariant())
14544       MMOFlags &= ~MachineMemOperand::MOInvariant;
14545     if (!RLD->isDereferenceable())
14546       MMOFlags &= ~MachineMemOperand::MODereferenceable;
14547     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14548       // FIXME: Discards pointer and AA info.
14549       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14550                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14551                          MMOFlags);
14552     } else {
14553       // FIXME: Discards pointer and AA info.
14554       Load = DAG.getExtLoad(
14555           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14556                                                   : LLD->getExtensionType(),
14557           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14558           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14559     }
14560 
14561     // Users of the select now use the result of the load.
14562     CombineTo(TheSelect, Load);
14563 
14564     // Users of the old loads now use the new load's chain.  We know the
14565     // old-load value is dead now.
14566     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14567     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14568     return true;
14569   }
14570 
14571   return false;
14572 }
14573 
14574 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14575 /// where 'cond' is the comparison specified by CC.
14576 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14577                                       SDValue N2, SDValue N3, ISD::CondCode CC,
14578                                       bool NotExtCompare) {
14579   // (x ? y : y) -> y.
14580   if (N2 == N3) return N2;
14581 
14582   EVT VT = N2.getValueType();
14583   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14584   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14585 
14586   // Determine if the condition we're dealing with is constant
14587   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14588                               N0, N1, CC, DL, false);
14589   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14590 
14591   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14592     // fold select_cc true, x, y -> x
14593     // fold select_cc false, x, y -> y
14594     return !SCCC->isNullValue() ? N2 : N3;
14595   }
14596 
14597   // Check to see if we can simplify the select into an fabs node
14598   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14599     // Allow either -0.0 or 0.0
14600     if (CFP->isZero()) {
14601       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14602       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14603           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14604           N2 == N3.getOperand(0))
14605         return DAG.getNode(ISD::FABS, DL, VT, N0);
14606 
14607       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14608       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14609           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14610           N2.getOperand(0) == N3)
14611         return DAG.getNode(ISD::FABS, DL, VT, N3);
14612     }
14613   }
14614 
14615   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14616   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14617   // in it.  This is a win when the constant is not otherwise available because
14618   // it replaces two constant pool loads with one.  We only do this if the FP
14619   // type is known to be legal, because if it isn't, then we are before legalize
14620   // types an we want the other legalization to happen first (e.g. to avoid
14621   // messing with soft float) and if the ConstantFP is not legal, because if
14622   // it is legal, we may not need to store the FP constant in a constant pool.
14623   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14624     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14625       if (TLI.isTypeLegal(N2.getValueType()) &&
14626           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14627                TargetLowering::Legal &&
14628            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14629            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14630           // If both constants have multiple uses, then we won't need to do an
14631           // extra load, they are likely around in registers for other users.
14632           (TV->hasOneUse() || FV->hasOneUse())) {
14633         Constant *Elts[] = {
14634           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14635           const_cast<ConstantFP*>(TV->getConstantFPValue())
14636         };
14637         Type *FPTy = Elts[0]->getType();
14638         const DataLayout &TD = DAG.getDataLayout();
14639 
14640         // Create a ConstantArray of the two constants.
14641         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14642         SDValue CPIdx =
14643             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14644                                 TD.getPrefTypeAlignment(FPTy));
14645         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14646 
14647         // Get the offsets to the 0 and 1 element of the array so that we can
14648         // select between them.
14649         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14650         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14651         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14652 
14653         SDValue Cond = DAG.getSetCC(DL,
14654                                     getSetCCResultType(N0.getValueType()),
14655                                     N0, N1, CC);
14656         AddToWorklist(Cond.getNode());
14657         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14658                                           Cond, One, Zero);
14659         AddToWorklist(CstOffset.getNode());
14660         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14661                             CstOffset);
14662         AddToWorklist(CPIdx.getNode());
14663         return DAG.getLoad(
14664             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14665             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14666             Alignment);
14667       }
14668     }
14669 
14670   // Check to see if we can perform the "gzip trick", transforming
14671   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14672   if (isNullConstant(N3) && CC == ISD::SETLT &&
14673       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14674        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14675     EVT XType = N0.getValueType();
14676     EVT AType = N2.getValueType();
14677     if (XType.bitsGE(AType)) {
14678       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14679       // single-bit constant.
14680       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14681         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14682         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14683         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14684                                        getShiftAmountTy(N0.getValueType()));
14685         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14686                                     XType, N0, ShCt);
14687         AddToWorklist(Shift.getNode());
14688 
14689         if (XType.bitsGT(AType)) {
14690           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14691           AddToWorklist(Shift.getNode());
14692         }
14693 
14694         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14695       }
14696 
14697       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14698                                   XType, N0,
14699                                   DAG.getConstant(XType.getSizeInBits() - 1,
14700                                                   SDLoc(N0),
14701                                          getShiftAmountTy(N0.getValueType())));
14702       AddToWorklist(Shift.getNode());
14703 
14704       if (XType.bitsGT(AType)) {
14705         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14706         AddToWorklist(Shift.getNode());
14707       }
14708 
14709       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14710     }
14711   }
14712 
14713   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14714   // where y is has a single bit set.
14715   // A plaintext description would be, we can turn the SELECT_CC into an AND
14716   // when the condition can be materialized as an all-ones register.  Any
14717   // single bit-test can be materialized as an all-ones register with
14718   // shift-left and shift-right-arith.
14719   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14720       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14721     SDValue AndLHS = N0->getOperand(0);
14722     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14723     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14724       // Shift the tested bit over the sign bit.
14725       const APInt &AndMask = ConstAndRHS->getAPIntValue();
14726       SDValue ShlAmt =
14727         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14728                         getShiftAmountTy(AndLHS.getValueType()));
14729       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14730 
14731       // Now arithmetic right shift it all the way over, so the result is either
14732       // all-ones, or zero.
14733       SDValue ShrAmt =
14734         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14735                         getShiftAmountTy(Shl.getValueType()));
14736       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14737 
14738       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14739     }
14740   }
14741 
14742   // fold select C, 16, 0 -> shl C, 4
14743   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14744       TLI.getBooleanContents(N0.getValueType()) ==
14745           TargetLowering::ZeroOrOneBooleanContent) {
14746 
14747     // If the caller doesn't want us to simplify this into a zext of a compare,
14748     // don't do it.
14749     if (NotExtCompare && N2C->isOne())
14750       return SDValue();
14751 
14752     // Get a SetCC of the condition
14753     // NOTE: Don't create a SETCC if it's not legal on this target.
14754     if (!LegalOperations ||
14755         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14756       SDValue Temp, SCC;
14757       // cast from setcc result type to select result type
14758       if (LegalTypes) {
14759         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14760                             N0, N1, CC);
14761         if (N2.getValueType().bitsLT(SCC.getValueType()))
14762           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14763                                         N2.getValueType());
14764         else
14765           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14766                              N2.getValueType(), SCC);
14767       } else {
14768         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14769         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14770                            N2.getValueType(), SCC);
14771       }
14772 
14773       AddToWorklist(SCC.getNode());
14774       AddToWorklist(Temp.getNode());
14775 
14776       if (N2C->isOne())
14777         return Temp;
14778 
14779       // shl setcc result by log2 n2c
14780       return DAG.getNode(
14781           ISD::SHL, DL, N2.getValueType(), Temp,
14782           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14783                           getShiftAmountTy(Temp.getValueType())));
14784     }
14785   }
14786 
14787   // Check to see if this is an integer abs.
14788   // select_cc setg[te] X,  0,  X, -X ->
14789   // select_cc setgt    X, -1,  X, -X ->
14790   // select_cc setl[te] X,  0, -X,  X ->
14791   // select_cc setlt    X,  1, -X,  X ->
14792   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14793   if (N1C) {
14794     ConstantSDNode *SubC = nullptr;
14795     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14796          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14797         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14798       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14799     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14800               (N1C->isOne() && CC == ISD::SETLT)) &&
14801              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14802       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14803 
14804     EVT XType = N0.getValueType();
14805     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14806       SDLoc DL(N0);
14807       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14808                                   N0,
14809                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14810                                          getShiftAmountTy(N0.getValueType())));
14811       SDValue Add = DAG.getNode(ISD::ADD, DL,
14812                                 XType, N0, Shift);
14813       AddToWorklist(Shift.getNode());
14814       AddToWorklist(Add.getNode());
14815       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14816     }
14817   }
14818 
14819   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14820   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14821   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14822   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14823   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14824   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14825   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14826   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14827   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14828     SDValue ValueOnZero = N2;
14829     SDValue Count = N3;
14830     // If the condition is NE instead of E, swap the operands.
14831     if (CC == ISD::SETNE)
14832       std::swap(ValueOnZero, Count);
14833     // Check if the value on zero is a constant equal to the bits in the type.
14834     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14835       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14836         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14837         // legal, combine to just cttz.
14838         if ((Count.getOpcode() == ISD::CTTZ ||
14839              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14840             N0 == Count.getOperand(0) &&
14841             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14842           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14843         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14844         // legal, combine to just ctlz.
14845         if ((Count.getOpcode() == ISD::CTLZ ||
14846              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14847             N0 == Count.getOperand(0) &&
14848             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14849           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14850       }
14851     }
14852   }
14853 
14854   return SDValue();
14855 }
14856 
14857 /// This is a stub for TargetLowering::SimplifySetCC.
14858 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14859                                    ISD::CondCode Cond, const SDLoc &DL,
14860                                    bool foldBooleans) {
14861   TargetLowering::DAGCombinerInfo
14862     DagCombineInfo(DAG, Level, false, this);
14863   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14864 }
14865 
14866 /// Given an ISD::SDIV node expressing a divide by constant, return
14867 /// a DAG expression to select that will generate the same value by multiplying
14868 /// by a magic number.
14869 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14870 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14871   // when optimising for minimum size, we don't want to expand a div to a mul
14872   // and a shift.
14873   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14874     return SDValue();
14875 
14876   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14877   if (!C)
14878     return SDValue();
14879 
14880   // Avoid division by zero.
14881   if (C->isNullValue())
14882     return SDValue();
14883 
14884   std::vector<SDNode*> Built;
14885   SDValue S =
14886       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14887 
14888   for (SDNode *N : Built)
14889     AddToWorklist(N);
14890   return S;
14891 }
14892 
14893 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14894 /// DAG expression that will generate the same value by right shifting.
14895 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14896   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14897   if (!C)
14898     return SDValue();
14899 
14900   // Avoid division by zero.
14901   if (C->isNullValue())
14902     return SDValue();
14903 
14904   std::vector<SDNode *> Built;
14905   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14906 
14907   for (SDNode *N : Built)
14908     AddToWorklist(N);
14909   return S;
14910 }
14911 
14912 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14913 /// expression that will generate the same value by multiplying by a magic
14914 /// number.
14915 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14916 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14917   // when optimising for minimum size, we don't want to expand a div to a mul
14918   // and a shift.
14919   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14920     return SDValue();
14921 
14922   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14923   if (!C)
14924     return SDValue();
14925 
14926   // Avoid division by zero.
14927   if (C->isNullValue())
14928     return SDValue();
14929 
14930   std::vector<SDNode*> Built;
14931   SDValue S =
14932       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14933 
14934   for (SDNode *N : Built)
14935     AddToWorklist(N);
14936   return S;
14937 }
14938 
14939 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14940 /// For the reciprocal, we need to find the zero of the function:
14941 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
14942 ///     =>
14943 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14944 ///     does not require additional intermediate precision]
14945 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14946   if (Level >= AfterLegalizeDAG)
14947     return SDValue();
14948 
14949   // TODO: Handle half and/or extended types?
14950   EVT VT = Op.getValueType();
14951   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
14952     return SDValue();
14953 
14954   // If estimates are explicitly disabled for this function, we're done.
14955   MachineFunction &MF = DAG.getMachineFunction();
14956   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
14957   if (Enabled == TLI.ReciprocalEstimate::Disabled)
14958     return SDValue();
14959 
14960   // Estimates may be explicitly enabled for this type with a custom number of
14961   // refinement steps.
14962   int Iterations = TLI.getDivRefinementSteps(VT, MF);
14963   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
14964     AddToWorklist(Est.getNode());
14965 
14966     if (Iterations) {
14967       EVT VT = Op.getValueType();
14968       SDLoc DL(Op);
14969       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14970 
14971       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14972       for (int i = 0; i < Iterations; ++i) {
14973         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14974         AddToWorklist(NewEst.getNode());
14975 
14976         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14977         AddToWorklist(NewEst.getNode());
14978 
14979         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14980         AddToWorklist(NewEst.getNode());
14981 
14982         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14983         AddToWorklist(Est.getNode());
14984       }
14985     }
14986     return Est;
14987   }
14988 
14989   return SDValue();
14990 }
14991 
14992 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14993 /// For the reciprocal sqrt, we need to find the zero of the function:
14994 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14995 ///     =>
14996 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14997 /// As a result, we precompute A/2 prior to the iteration loop.
14998 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
14999                                          unsigned Iterations,
15000                                          SDNodeFlags *Flags, bool Reciprocal) {
15001   EVT VT = Arg.getValueType();
15002   SDLoc DL(Arg);
15003   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
15004 
15005   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
15006   // this entire sequence requires only one FP constant.
15007   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
15008   AddToWorklist(HalfArg.getNode());
15009 
15010   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
15011   AddToWorklist(HalfArg.getNode());
15012 
15013   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
15014   for (unsigned i = 0; i < Iterations; ++i) {
15015     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
15016     AddToWorklist(NewEst.getNode());
15017 
15018     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
15019     AddToWorklist(NewEst.getNode());
15020 
15021     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
15022     AddToWorklist(NewEst.getNode());
15023 
15024     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15025     AddToWorklist(Est.getNode());
15026   }
15027 
15028   // If non-reciprocal square root is requested, multiply the result by Arg.
15029   if (!Reciprocal) {
15030     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
15031     AddToWorklist(Est.getNode());
15032   }
15033 
15034   return Est;
15035 }
15036 
15037 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15038 /// For the reciprocal sqrt, we need to find the zero of the function:
15039 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15040 ///     =>
15041 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
15042 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
15043                                          unsigned Iterations,
15044                                          SDNodeFlags *Flags, bool Reciprocal) {
15045   EVT VT = Arg.getValueType();
15046   SDLoc DL(Arg);
15047   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
15048   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
15049 
15050   // This routine must enter the loop below to work correctly
15051   // when (Reciprocal == false).
15052   assert(Iterations > 0);
15053 
15054   // Newton iterations for reciprocal square root:
15055   // E = (E * -0.5) * ((A * E) * E + -3.0)
15056   for (unsigned i = 0; i < Iterations; ++i) {
15057     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15058     AddToWorklist(AE.getNode());
15059 
15060     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15061     AddToWorklist(AEE.getNode());
15062 
15063     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15064     AddToWorklist(RHS.getNode());
15065 
15066     // When calculating a square root at the last iteration build:
15067     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15068     // (notice a common subexpression)
15069     SDValue LHS;
15070     if (Reciprocal || (i + 1) < Iterations) {
15071       // RSQRT: LHS = (E * -0.5)
15072       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15073     } else {
15074       // SQRT: LHS = (A * E) * -0.5
15075       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15076     }
15077     AddToWorklist(LHS.getNode());
15078 
15079     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15080     AddToWorklist(Est.getNode());
15081   }
15082 
15083   return Est;
15084 }
15085 
15086 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15087 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15088 /// Op can be zero.
15089 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15090                                            bool Reciprocal) {
15091   if (Level >= AfterLegalizeDAG)
15092     return SDValue();
15093 
15094   // TODO: Handle half and/or extended types?
15095   EVT VT = Op.getValueType();
15096   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15097     return SDValue();
15098 
15099   // If estimates are explicitly disabled for this function, we're done.
15100   MachineFunction &MF = DAG.getMachineFunction();
15101   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
15102   if (Enabled == TLI.ReciprocalEstimate::Disabled)
15103     return SDValue();
15104 
15105   // Estimates may be explicitly enabled for this type with a custom number of
15106   // refinement steps.
15107   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
15108 
15109   bool UseOneConstNR = false;
15110   if (SDValue Est =
15111       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
15112                           Reciprocal)) {
15113     AddToWorklist(Est.getNode());
15114 
15115     if (Iterations) {
15116       Est = UseOneConstNR
15117             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
15118             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
15119 
15120       if (!Reciprocal) {
15121         // Unfortunately, Est is now NaN if the input was exactly 0.0.
15122         // Select out this case and force the answer to 0.0.
15123         EVT VT = Op.getValueType();
15124         SDLoc DL(Op);
15125 
15126         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
15127         EVT CCVT = getSetCCResultType(VT);
15128         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
15129         AddToWorklist(ZeroCmp.getNode());
15130 
15131         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
15132                           ZeroCmp, FPZero, Est);
15133         AddToWorklist(Est.getNode());
15134       }
15135     }
15136     return Est;
15137   }
15138 
15139   return SDValue();
15140 }
15141 
15142 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15143   return buildSqrtEstimateImpl(Op, Flags, true);
15144 }
15145 
15146 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15147   return buildSqrtEstimateImpl(Op, Flags, false);
15148 }
15149 
15150 /// Return true if base is a frame index, which is known not to alias with
15151 /// anything but itself.  Provides base object and offset as results.
15152 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
15153                            const GlobalValue *&GV, const void *&CV) {
15154   // Assume it is a primitive operation.
15155   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
15156 
15157   // If it's an adding a simple constant then integrate the offset.
15158   if (Base.getOpcode() == ISD::ADD) {
15159     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
15160       Base = Base.getOperand(0);
15161       Offset += C->getZExtValue();
15162     }
15163   }
15164 
15165   // Return the underlying GlobalValue, and update the Offset.  Return false
15166   // for GlobalAddressSDNode since the same GlobalAddress may be represented
15167   // by multiple nodes with different offsets.
15168   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
15169     GV = G->getGlobal();
15170     Offset += G->getOffset();
15171     return false;
15172   }
15173 
15174   // Return the underlying Constant value, and update the Offset.  Return false
15175   // for ConstantSDNodes since the same constant pool entry may be represented
15176   // by multiple nodes with different offsets.
15177   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
15178     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
15179                                          : (const void *)C->getConstVal();
15180     Offset += C->getOffset();
15181     return false;
15182   }
15183   // If it's any of the following then it can't alias with anything but itself.
15184   return isa<FrameIndexSDNode>(Base);
15185 }
15186 
15187 /// Return true if there is any possibility that the two addresses overlap.
15188 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
15189   // If they are the same then they must be aliases.
15190   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
15191 
15192   // If they are both volatile then they cannot be reordered.
15193   if (Op0->isVolatile() && Op1->isVolatile()) return true;
15194 
15195   // If one operation reads from invariant memory, and the other may store, they
15196   // cannot alias. These should really be checking the equivalent of mayWrite,
15197   // but it only matters for memory nodes other than load /store.
15198   if (Op0->isInvariant() && Op1->writeMem())
15199     return false;
15200 
15201   if (Op1->isInvariant() && Op0->writeMem())
15202     return false;
15203 
15204   // Gather base node and offset information.
15205   SDValue Base1, Base2;
15206   int64_t Offset1, Offset2;
15207   const GlobalValue *GV1, *GV2;
15208   const void *CV1, *CV2;
15209   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
15210                                       Base1, Offset1, GV1, CV1);
15211   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
15212                                       Base2, Offset2, GV2, CV2);
15213 
15214   // If they have a same base address then check to see if they overlap.
15215   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
15216     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15217              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15218 
15219   // It is possible for different frame indices to alias each other, mostly
15220   // when tail call optimization reuses return address slots for arguments.
15221   // To catch this case, look up the actual index of frame indices to compute
15222   // the real alias relationship.
15223   if (isFrameIndex1 && isFrameIndex2) {
15224     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
15225     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
15226     Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
15227     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15228              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15229   }
15230 
15231   // Otherwise, if we know what the bases are, and they aren't identical, then
15232   // we know they cannot alias.
15233   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
15234     return false;
15235 
15236   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
15237   // compared to the size and offset of the access, we may be able to prove they
15238   // do not alias.  This check is conservative for now to catch cases created by
15239   // splitting vector types.
15240   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
15241       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
15242       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
15243        Op1->getMemoryVT().getSizeInBits() >> 3) &&
15244       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
15245     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
15246     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
15247 
15248     // There is no overlap between these relatively aligned accesses of similar
15249     // size, return no alias.
15250     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
15251         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
15252       return false;
15253   }
15254 
15255   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
15256                    ? CombinerGlobalAA
15257                    : DAG.getSubtarget().useAA();
15258 #ifndef NDEBUG
15259   if (CombinerAAOnlyFunc.getNumOccurrences() &&
15260       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
15261     UseAA = false;
15262 #endif
15263   if (UseAA &&
15264       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
15265     // Use alias analysis information.
15266     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
15267                                  Op1->getSrcValueOffset());
15268     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
15269         Op0->getSrcValueOffset() - MinOffset;
15270     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
15271         Op1->getSrcValueOffset() - MinOffset;
15272     AliasResult AAResult =
15273         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
15274                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
15275                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
15276                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
15277     if (AAResult == NoAlias)
15278       return false;
15279   }
15280 
15281   // Otherwise we have to assume they alias.
15282   return true;
15283 }
15284 
15285 /// Walk up chain skipping non-aliasing memory nodes,
15286 /// looking for aliasing nodes and adding them to the Aliases vector.
15287 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
15288                                    SmallVectorImpl<SDValue> &Aliases) {
15289   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
15290   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
15291 
15292   // Get alias information for node.
15293   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
15294 
15295   // Starting off.
15296   Chains.push_back(OriginalChain);
15297   unsigned Depth = 0;
15298 
15299   // Look at each chain and determine if it is an alias.  If so, add it to the
15300   // aliases list.  If not, then continue up the chain looking for the next
15301   // candidate.
15302   while (!Chains.empty()) {
15303     SDValue Chain = Chains.pop_back_val();
15304 
15305     // For TokenFactor nodes, look at each operand and only continue up the
15306     // chain until we reach the depth limit.
15307     //
15308     // FIXME: The depth check could be made to return the last non-aliasing
15309     // chain we found before we hit a tokenfactor rather than the original
15310     // chain.
15311     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
15312       Aliases.clear();
15313       Aliases.push_back(OriginalChain);
15314       return;
15315     }
15316 
15317     // Don't bother if we've been before.
15318     if (!Visited.insert(Chain.getNode()).second)
15319       continue;
15320 
15321     switch (Chain.getOpcode()) {
15322     case ISD::EntryToken:
15323       // Entry token is ideal chain operand, but handled in FindBetterChain.
15324       break;
15325 
15326     case ISD::LOAD:
15327     case ISD::STORE: {
15328       // Get alias information for Chain.
15329       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
15330           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
15331 
15332       // If chain is alias then stop here.
15333       if (!(IsLoad && IsOpLoad) &&
15334           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
15335         Aliases.push_back(Chain);
15336       } else {
15337         // Look further up the chain.
15338         Chains.push_back(Chain.getOperand(0));
15339         ++Depth;
15340       }
15341       break;
15342     }
15343 
15344     case ISD::TokenFactor:
15345       // We have to check each of the operands of the token factor for "small"
15346       // token factors, so we queue them up.  Adding the operands to the queue
15347       // (stack) in reverse order maintains the original order and increases the
15348       // likelihood that getNode will find a matching token factor (CSE.)
15349       if (Chain.getNumOperands() > 16) {
15350         Aliases.push_back(Chain);
15351         break;
15352       }
15353       for (unsigned n = Chain.getNumOperands(); n;)
15354         Chains.push_back(Chain.getOperand(--n));
15355       ++Depth;
15356       break;
15357 
15358     default:
15359       // For all other instructions we will just have to take what we can get.
15360       Aliases.push_back(Chain);
15361       break;
15362     }
15363   }
15364 }
15365 
15366 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
15367 /// (aliasing node.)
15368 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
15369   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
15370 
15371   // Accumulate all the aliases to this node.
15372   GatherAllAliases(N, OldChain, Aliases);
15373 
15374   // If no operands then chain to entry token.
15375   if (Aliases.size() == 0)
15376     return DAG.getEntryNode();
15377 
15378   // If a single operand then chain to it.  We don't need to revisit it.
15379   if (Aliases.size() == 1)
15380     return Aliases[0];
15381 
15382   // Construct a custom tailored token factor.
15383   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
15384 }
15385 
15386 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
15387   // This holds the base pointer, index, and the offset in bytes from the base
15388   // pointer.
15389   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
15390 
15391   // We must have a base and an offset.
15392   if (!BasePtr.Base.getNode())
15393     return false;
15394 
15395   // Do not handle stores to undef base pointers.
15396   if (BasePtr.Base.isUndef())
15397     return false;
15398 
15399   SmallVector<StoreSDNode *, 8> ChainedStores;
15400   ChainedStores.push_back(St);
15401 
15402   // Walk up the chain and look for nodes with offsets from the same
15403   // base pointer. Stop when reaching an instruction with a different kind
15404   // or instruction which has a different base pointer.
15405   StoreSDNode *Index = St;
15406   while (Index) {
15407     // If the chain has more than one use, then we can't reorder the mem ops.
15408     if (Index != St && !SDValue(Index, 0)->hasOneUse())
15409       break;
15410 
15411     if (Index->isVolatile() || Index->isIndexed())
15412       break;
15413 
15414     // Find the base pointer and offset for this memory node.
15415     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
15416 
15417     // Check that the base pointer is the same as the original one.
15418     if (!Ptr.equalBaseIndex(BasePtr))
15419       break;
15420 
15421     // Find the next memory operand in the chain. If the next operand in the
15422     // chain is a store then move up and continue the scan with the next
15423     // memory operand. If the next operand is a load save it and use alias
15424     // information to check if it interferes with anything.
15425     SDNode *NextInChain = Index->getChain().getNode();
15426     while (true) {
15427       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
15428         // We found a store node. Use it for the next iteration.
15429         if (STn->isVolatile() || STn->isIndexed()) {
15430           Index = nullptr;
15431           break;
15432         }
15433         ChainedStores.push_back(STn);
15434         Index = STn;
15435         break;
15436       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
15437         NextInChain = Ldn->getChain().getNode();
15438         continue;
15439       } else {
15440         Index = nullptr;
15441         break;
15442       }
15443     }
15444   }
15445 
15446   bool MadeChangeToSt = false;
15447   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15448 
15449   for (StoreSDNode *ChainedStore : ChainedStores) {
15450     SDValue Chain = ChainedStore->getChain();
15451     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15452 
15453     if (Chain != BetterChain) {
15454       if (ChainedStore == St)
15455         MadeChangeToSt = true;
15456       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15457     }
15458   }
15459 
15460   // Do all replacements after finding the replacements to make to avoid making
15461   // the chains more complicated by introducing new TokenFactors.
15462   for (auto Replacement : BetterChains)
15463     replaceStoreChain(Replacement.first, Replacement.second);
15464 
15465   return MadeChangeToSt;
15466 }
15467 
15468 /// This is the entry point for the file.
15469 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15470                            CodeGenOpt::Level OptLevel) {
15471   /// This is the main entry point to this class.
15472   DAGCombiner(*this, AA, OptLevel).Run(Level);
15473 }
15474