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) &&
2161       isConstantOrConstantVector(N0.getOperand(1))) {
2162     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2163     AddToWorklist(C3.getNode());
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     AddToWorklist(Shl.getNode());
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 prefered 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   SDLoc DL(N);
5546 
5547   // If the MSTORE data type requires splitting and the mask is provided by a
5548   // SETCC, then split both nodes and its operands before legalization. This
5549   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5550   // and enables future optimizations (e.g. min/max pattern matching on X86).
5551   if (Mask.getOpcode() == ISD::SETCC) {
5552 
5553     // Check if any splitting is required.
5554     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5555         TargetLowering::TypeSplitVector)
5556       return SDValue();
5557 
5558     SDValue MaskLo, MaskHi, Lo, Hi;
5559     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5560 
5561     EVT LoVT, HiVT;
5562     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5563 
5564     SDValue Chain = MST->getChain();
5565     SDValue Ptr   = MST->getBasePtr();
5566 
5567     EVT MemoryVT = MST->getMemoryVT();
5568     unsigned Alignment = MST->getOriginalAlignment();
5569 
5570     // if Alignment is equal to the vector size,
5571     // take the half of it for the second part
5572     unsigned SecondHalfAlignment =
5573       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5574          Alignment/2 : Alignment;
5575 
5576     EVT LoMemVT, HiMemVT;
5577     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5578 
5579     SDValue DataLo, DataHi;
5580     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5581 
5582     MachineMemOperand *MMO = DAG.getMachineFunction().
5583       getMachineMemOperand(MST->getPointerInfo(),
5584                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5585                            Alignment, MST->getAAInfo(), MST->getRanges());
5586 
5587     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5588                             MST->isTruncatingStore(), MST->isCompressingStore());
5589 
5590     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5591     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5592                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5593 
5594     MMO = DAG.getMachineFunction().
5595       getMachineMemOperand(MST->getPointerInfo(),
5596                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5597                            SecondHalfAlignment, MST->getAAInfo(),
5598                            MST->getRanges());
5599 
5600     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5601                             MST->isTruncatingStore(), MST->isCompressingStore());
5602 
5603     AddToWorklist(Lo.getNode());
5604     AddToWorklist(Hi.getNode());
5605 
5606     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5607   }
5608   return SDValue();
5609 }
5610 
5611 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5612 
5613   if (Level >= AfterLegalizeTypes)
5614     return SDValue();
5615 
5616   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5617   SDValue Mask = MGT->getMask();
5618   SDLoc DL(N);
5619 
5620   // If the MGATHER result requires splitting and the mask is provided by a
5621   // SETCC, then split both nodes and its operands before legalization. This
5622   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5623   // and enables future optimizations (e.g. min/max pattern matching on X86).
5624 
5625   if (Mask.getOpcode() != ISD::SETCC)
5626     return SDValue();
5627 
5628   EVT VT = N->getValueType(0);
5629 
5630   // Check if any splitting is required.
5631   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5632       TargetLowering::TypeSplitVector)
5633     return SDValue();
5634 
5635   SDValue MaskLo, MaskHi, Lo, Hi;
5636   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5637 
5638   SDValue Src0 = MGT->getValue();
5639   SDValue Src0Lo, Src0Hi;
5640   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5641 
5642   EVT LoVT, HiVT;
5643   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5644 
5645   SDValue Chain = MGT->getChain();
5646   EVT MemoryVT = MGT->getMemoryVT();
5647   unsigned Alignment = MGT->getOriginalAlignment();
5648 
5649   EVT LoMemVT, HiMemVT;
5650   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5651 
5652   SDValue BasePtr = MGT->getBasePtr();
5653   SDValue Index = MGT->getIndex();
5654   SDValue IndexLo, IndexHi;
5655   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5656 
5657   MachineMemOperand *MMO = DAG.getMachineFunction().
5658     getMachineMemOperand(MGT->getPointerInfo(),
5659                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5660                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5661 
5662   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5663   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5664                             MMO);
5665 
5666   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5667   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5668                             MMO);
5669 
5670   AddToWorklist(Lo.getNode());
5671   AddToWorklist(Hi.getNode());
5672 
5673   // Build a factor node to remember that this load is independent of the
5674   // other one.
5675   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5676                       Hi.getValue(1));
5677 
5678   // Legalized the chain result - switch anything that used the old chain to
5679   // use the new one.
5680   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5681 
5682   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5683 
5684   SDValue RetOps[] = { GatherRes, Chain };
5685   return DAG.getMergeValues(RetOps, DL);
5686 }
5687 
5688 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5689 
5690   if (Level >= AfterLegalizeTypes)
5691     return SDValue();
5692 
5693   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5694   SDValue Mask = MLD->getMask();
5695   SDLoc DL(N);
5696 
5697   // If the MLOAD result requires splitting and the mask is provided by a
5698   // SETCC, then split both nodes and its operands before legalization. This
5699   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5700   // and enables future optimizations (e.g. min/max pattern matching on X86).
5701 
5702   if (Mask.getOpcode() == ISD::SETCC) {
5703     EVT VT = N->getValueType(0);
5704 
5705     // Check if any splitting is required.
5706     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5707         TargetLowering::TypeSplitVector)
5708       return SDValue();
5709 
5710     SDValue MaskLo, MaskHi, Lo, Hi;
5711     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5712 
5713     SDValue Src0 = MLD->getSrc0();
5714     SDValue Src0Lo, Src0Hi;
5715     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5716 
5717     EVT LoVT, HiVT;
5718     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5719 
5720     SDValue Chain = MLD->getChain();
5721     SDValue Ptr   = MLD->getBasePtr();
5722     EVT MemoryVT = MLD->getMemoryVT();
5723     unsigned Alignment = MLD->getOriginalAlignment();
5724 
5725     // if Alignment is equal to the vector size,
5726     // take the half of it for the second part
5727     unsigned SecondHalfAlignment =
5728       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5729          Alignment/2 : Alignment;
5730 
5731     EVT LoMemVT, HiMemVT;
5732     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5733 
5734     MachineMemOperand *MMO = DAG.getMachineFunction().
5735     getMachineMemOperand(MLD->getPointerInfo(),
5736                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5737                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5738 
5739     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5740                            ISD::NON_EXTLOAD);
5741 
5742     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5743     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5744                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5745 
5746     MMO = DAG.getMachineFunction().
5747     getMachineMemOperand(MLD->getPointerInfo(),
5748                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5749                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5750 
5751     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5752                            ISD::NON_EXTLOAD);
5753 
5754     AddToWorklist(Lo.getNode());
5755     AddToWorklist(Hi.getNode());
5756 
5757     // Build a factor node to remember that this load is independent of the
5758     // other one.
5759     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5760                         Hi.getValue(1));
5761 
5762     // Legalized the chain result - switch anything that used the old chain to
5763     // use the new one.
5764     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5765 
5766     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5767 
5768     SDValue RetOps[] = { LoadRes, Chain };
5769     return DAG.getMergeValues(RetOps, DL);
5770   }
5771   return SDValue();
5772 }
5773 
5774 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5775   SDValue N0 = N->getOperand(0);
5776   SDValue N1 = N->getOperand(1);
5777   SDValue N2 = N->getOperand(2);
5778   SDLoc DL(N);
5779 
5780   // Canonicalize integer abs.
5781   // vselect (setg[te] X,  0),  X, -X ->
5782   // vselect (setgt    X, -1),  X, -X ->
5783   // vselect (setl[te] X,  0), -X,  X ->
5784   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5785   if (N0.getOpcode() == ISD::SETCC) {
5786     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5787     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5788     bool isAbs = false;
5789     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5790 
5791     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5792          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5793         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5794       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5795     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5796              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5797       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5798 
5799     if (isAbs) {
5800       EVT VT = LHS.getValueType();
5801       SDValue Shift = DAG.getNode(
5802           ISD::SRA, DL, VT, LHS,
5803           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
5804       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5805       AddToWorklist(Shift.getNode());
5806       AddToWorklist(Add.getNode());
5807       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5808     }
5809   }
5810 
5811   if (SimplifySelectOps(N, N1, N2))
5812     return SDValue(N, 0);  // Don't revisit N.
5813 
5814   // If the VSELECT result requires splitting and the mask is provided by a
5815   // SETCC, then split both nodes and its operands before legalization. This
5816   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5817   // and enables future optimizations (e.g. min/max pattern matching on X86).
5818   if (N0.getOpcode() == ISD::SETCC) {
5819     EVT VT = N->getValueType(0);
5820 
5821     // Check if any splitting is required.
5822     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5823         TargetLowering::TypeSplitVector)
5824       return SDValue();
5825 
5826     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5827     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5828     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5829     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5830 
5831     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5832     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5833 
5834     // Add the new VSELECT nodes to the work list in case they need to be split
5835     // again.
5836     AddToWorklist(Lo.getNode());
5837     AddToWorklist(Hi.getNode());
5838 
5839     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5840   }
5841 
5842   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5843   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5844     return N1;
5845   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5846   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5847     return N2;
5848 
5849   // The ConvertSelectToConcatVector function is assuming both the above
5850   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5851   // and addressed.
5852   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5853       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5854       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5855     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5856       return CV;
5857   }
5858 
5859   return SDValue();
5860 }
5861 
5862 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5863   SDValue N0 = N->getOperand(0);
5864   SDValue N1 = N->getOperand(1);
5865   SDValue N2 = N->getOperand(2);
5866   SDValue N3 = N->getOperand(3);
5867   SDValue N4 = N->getOperand(4);
5868   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5869 
5870   // fold select_cc lhs, rhs, x, x, cc -> x
5871   if (N2 == N3)
5872     return N2;
5873 
5874   // Determine if the condition we're dealing with is constant
5875   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5876                                   CC, SDLoc(N), false)) {
5877     AddToWorklist(SCC.getNode());
5878 
5879     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5880       if (!SCCC->isNullValue())
5881         return N2;    // cond always true -> true val
5882       else
5883         return N3;    // cond always false -> false val
5884     } else if (SCC->isUndef()) {
5885       // When the condition is UNDEF, just return the first operand. This is
5886       // coherent the DAG creation, no setcc node is created in this case
5887       return N2;
5888     } else if (SCC.getOpcode() == ISD::SETCC) {
5889       // Fold to a simpler select_cc
5890       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5891                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5892                          SCC.getOperand(2));
5893     }
5894   }
5895 
5896   // If we can fold this based on the true/false value, do so.
5897   if (SimplifySelectOps(N, N2, N3))
5898     return SDValue(N, 0);  // Don't revisit N.
5899 
5900   // fold select_cc into other things, such as min/max/abs
5901   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5902 }
5903 
5904 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5905   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5906                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5907                        SDLoc(N));
5908 }
5909 
5910 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5911   SDValue LHS = N->getOperand(0);
5912   SDValue RHS = N->getOperand(1);
5913   SDValue Carry = N->getOperand(2);
5914   SDValue Cond = N->getOperand(3);
5915 
5916   // If Carry is false, fold to a regular SETCC.
5917   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5918     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5919 
5920   return SDValue();
5921 }
5922 
5923 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5924 /// a build_vector of constants.
5925 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5926 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5927 /// Vector extends are not folded if operations are legal; this is to
5928 /// avoid introducing illegal build_vector dag nodes.
5929 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5930                                          SelectionDAG &DAG, bool LegalTypes,
5931                                          bool LegalOperations) {
5932   unsigned Opcode = N->getOpcode();
5933   SDValue N0 = N->getOperand(0);
5934   EVT VT = N->getValueType(0);
5935 
5936   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5937          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5938          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5939          && "Expected EXTEND dag node in input!");
5940 
5941   // fold (sext c1) -> c1
5942   // fold (zext c1) -> c1
5943   // fold (aext c1) -> c1
5944   if (isa<ConstantSDNode>(N0))
5945     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5946 
5947   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5948   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5949   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5950   EVT SVT = VT.getScalarType();
5951   if (!(VT.isVector() &&
5952       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5953       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5954     return nullptr;
5955 
5956   // We can fold this node into a build_vector.
5957   unsigned VTBits = SVT.getSizeInBits();
5958   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
5959   SmallVector<SDValue, 8> Elts;
5960   unsigned NumElts = VT.getVectorNumElements();
5961   SDLoc DL(N);
5962 
5963   for (unsigned i=0; i != NumElts; ++i) {
5964     SDValue Op = N0->getOperand(i);
5965     if (Op->isUndef()) {
5966       Elts.push_back(DAG.getUNDEF(SVT));
5967       continue;
5968     }
5969 
5970     SDLoc DL(Op);
5971     // Get the constant value and if needed trunc it to the size of the type.
5972     // Nodes like build_vector might have constants wider than the scalar type.
5973     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5974     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5975       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5976     else
5977       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5978   }
5979 
5980   return DAG.getBuildVector(VT, DL, Elts).getNode();
5981 }
5982 
5983 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5984 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5985 // transformation. Returns true if extension are possible and the above
5986 // mentioned transformation is profitable.
5987 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5988                                     unsigned ExtOpc,
5989                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5990                                     const TargetLowering &TLI) {
5991   bool HasCopyToRegUses = false;
5992   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5993   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5994                             UE = N0.getNode()->use_end();
5995        UI != UE; ++UI) {
5996     SDNode *User = *UI;
5997     if (User == N)
5998       continue;
5999     if (UI.getUse().getResNo() != N0.getResNo())
6000       continue;
6001     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6002     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6003       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6004       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6005         // Sign bits will be lost after a zext.
6006         return false;
6007       bool Add = false;
6008       for (unsigned i = 0; i != 2; ++i) {
6009         SDValue UseOp = User->getOperand(i);
6010         if (UseOp == N0)
6011           continue;
6012         if (!isa<ConstantSDNode>(UseOp))
6013           return false;
6014         Add = true;
6015       }
6016       if (Add)
6017         ExtendNodes.push_back(User);
6018       continue;
6019     }
6020     // If truncates aren't free and there are users we can't
6021     // extend, it isn't worthwhile.
6022     if (!isTruncFree)
6023       return false;
6024     // Remember if this value is live-out.
6025     if (User->getOpcode() == ISD::CopyToReg)
6026       HasCopyToRegUses = true;
6027   }
6028 
6029   if (HasCopyToRegUses) {
6030     bool BothLiveOut = false;
6031     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6032          UI != UE; ++UI) {
6033       SDUse &Use = UI.getUse();
6034       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6035         BothLiveOut = true;
6036         break;
6037       }
6038     }
6039     if (BothLiveOut)
6040       // Both unextended and extended values are live out. There had better be
6041       // a good reason for the transformation.
6042       return ExtendNodes.size();
6043   }
6044   return true;
6045 }
6046 
6047 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6048                                   SDValue Trunc, SDValue ExtLoad,
6049                                   const SDLoc &DL, ISD::NodeType ExtType) {
6050   // Extend SetCC uses if necessary.
6051   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6052     SDNode *SetCC = SetCCs[i];
6053     SmallVector<SDValue, 4> Ops;
6054 
6055     for (unsigned j = 0; j != 2; ++j) {
6056       SDValue SOp = SetCC->getOperand(j);
6057       if (SOp == Trunc)
6058         Ops.push_back(ExtLoad);
6059       else
6060         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6061     }
6062 
6063     Ops.push_back(SetCC->getOperand(2));
6064     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6065   }
6066 }
6067 
6068 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6069 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6070   SDValue N0 = N->getOperand(0);
6071   EVT DstVT = N->getValueType(0);
6072   EVT SrcVT = N0.getValueType();
6073 
6074   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6075           N->getOpcode() == ISD::ZERO_EXTEND) &&
6076          "Unexpected node type (not an extend)!");
6077 
6078   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6079   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6080   //   (v8i32 (sext (v8i16 (load x))))
6081   // into:
6082   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6083   //                          (v4i32 (sextload (x + 16)))))
6084   // Where uses of the original load, i.e.:
6085   //   (v8i16 (load x))
6086   // are replaced with:
6087   //   (v8i16 (truncate
6088   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6089   //                            (v4i32 (sextload (x + 16)))))))
6090   //
6091   // This combine is only applicable to illegal, but splittable, vectors.
6092   // All legal types, and illegal non-vector types, are handled elsewhere.
6093   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6094   //
6095   if (N0->getOpcode() != ISD::LOAD)
6096     return SDValue();
6097 
6098   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6099 
6100   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6101       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6102       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6103     return SDValue();
6104 
6105   SmallVector<SDNode *, 4> SetCCs;
6106   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6107     return SDValue();
6108 
6109   ISD::LoadExtType ExtType =
6110       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6111 
6112   // Try to split the vector types to get down to legal types.
6113   EVT SplitSrcVT = SrcVT;
6114   EVT SplitDstVT = DstVT;
6115   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6116          SplitSrcVT.getVectorNumElements() > 1) {
6117     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6118     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6119   }
6120 
6121   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6122     return SDValue();
6123 
6124   SDLoc DL(N);
6125   const unsigned NumSplits =
6126       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6127   const unsigned Stride = SplitSrcVT.getStoreSize();
6128   SmallVector<SDValue, 4> Loads;
6129   SmallVector<SDValue, 4> Chains;
6130 
6131   SDValue BasePtr = LN0->getBasePtr();
6132   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6133     const unsigned Offset = Idx * Stride;
6134     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6135 
6136     SDValue SplitLoad = DAG.getExtLoad(
6137         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6138         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6139         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6140 
6141     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6142                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6143 
6144     Loads.push_back(SplitLoad.getValue(0));
6145     Chains.push_back(SplitLoad.getValue(1));
6146   }
6147 
6148   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6149   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6150 
6151   CombineTo(N, NewValue);
6152 
6153   // Replace uses of the original load (before extension)
6154   // with a truncate of the concatenated sextloaded vectors.
6155   SDValue Trunc =
6156       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6157   CombineTo(N0.getNode(), Trunc, NewChain);
6158   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6159                   (ISD::NodeType)N->getOpcode());
6160   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6161 }
6162 
6163 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6164   SDValue N0 = N->getOperand(0);
6165   EVT VT = N->getValueType(0);
6166 
6167   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6168                                               LegalOperations))
6169     return SDValue(Res, 0);
6170 
6171   // fold (sext (sext x)) -> (sext x)
6172   // fold (sext (aext x)) -> (sext x)
6173   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6174     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6175                        N0.getOperand(0));
6176 
6177   if (N0.getOpcode() == ISD::TRUNCATE) {
6178     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6179     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6180     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6181       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6182       if (NarrowLoad.getNode() != N0.getNode()) {
6183         CombineTo(N0.getNode(), NarrowLoad);
6184         // CombineTo deleted the truncate, if needed, but not what's under it.
6185         AddToWorklist(oye);
6186       }
6187       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6188     }
6189 
6190     // See if the value being truncated is already sign extended.  If so, just
6191     // eliminate the trunc/sext pair.
6192     SDValue Op = N0.getOperand(0);
6193     unsigned OpBits   = Op.getScalarValueSizeInBits();
6194     unsigned MidBits  = N0.getScalarValueSizeInBits();
6195     unsigned DestBits = VT.getScalarSizeInBits();
6196     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6197 
6198     if (OpBits == DestBits) {
6199       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6200       // bits, it is already ready.
6201       if (NumSignBits > DestBits-MidBits)
6202         return Op;
6203     } else if (OpBits < DestBits) {
6204       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6205       // bits, just sext from i32.
6206       if (NumSignBits > OpBits-MidBits)
6207         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6208     } else {
6209       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6210       // bits, just truncate to i32.
6211       if (NumSignBits > OpBits-MidBits)
6212         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6213     }
6214 
6215     // fold (sext (truncate x)) -> (sextinreg x).
6216     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6217                                                  N0.getValueType())) {
6218       if (OpBits < DestBits)
6219         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6220       else if (OpBits > DestBits)
6221         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6222       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6223                          DAG.getValueType(N0.getValueType()));
6224     }
6225   }
6226 
6227   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6228   // Only generate vector extloads when 1) they're legal, and 2) they are
6229   // deemed desirable by the target.
6230   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6231       ((!LegalOperations && !VT.isVector() &&
6232         !cast<LoadSDNode>(N0)->isVolatile()) ||
6233        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6234     bool DoXform = true;
6235     SmallVector<SDNode*, 4> SetCCs;
6236     if (!N0.hasOneUse())
6237       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6238     if (VT.isVector())
6239       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6240     if (DoXform) {
6241       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6242       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6243                                        LN0->getChain(),
6244                                        LN0->getBasePtr(), N0.getValueType(),
6245                                        LN0->getMemOperand());
6246       CombineTo(N, ExtLoad);
6247       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6248                                   N0.getValueType(), ExtLoad);
6249       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6250       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6251                       ISD::SIGN_EXTEND);
6252       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6253     }
6254   }
6255 
6256   // fold (sext (load x)) to multiple smaller sextloads.
6257   // Only on illegal but splittable vectors.
6258   if (SDValue ExtLoad = CombineExtLoad(N))
6259     return ExtLoad;
6260 
6261   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6262   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6263   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6264       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6265     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6266     EVT MemVT = LN0->getMemoryVT();
6267     if ((!LegalOperations && !LN0->isVolatile()) ||
6268         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6269       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6270                                        LN0->getChain(),
6271                                        LN0->getBasePtr(), MemVT,
6272                                        LN0->getMemOperand());
6273       CombineTo(N, ExtLoad);
6274       CombineTo(N0.getNode(),
6275                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6276                             N0.getValueType(), ExtLoad),
6277                 ExtLoad.getValue(1));
6278       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6279     }
6280   }
6281 
6282   // fold (sext (and/or/xor (load x), cst)) ->
6283   //      (and/or/xor (sextload x), (sext cst))
6284   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6285        N0.getOpcode() == ISD::XOR) &&
6286       isa<LoadSDNode>(N0.getOperand(0)) &&
6287       N0.getOperand(1).getOpcode() == ISD::Constant &&
6288       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6289       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6290     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6291     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6292       bool DoXform = true;
6293       SmallVector<SDNode*, 4> SetCCs;
6294       if (!N0.hasOneUse())
6295         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6296                                           SetCCs, TLI);
6297       if (DoXform) {
6298         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6299                                          LN0->getChain(), LN0->getBasePtr(),
6300                                          LN0->getMemoryVT(),
6301                                          LN0->getMemOperand());
6302         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6303         Mask = Mask.sext(VT.getSizeInBits());
6304         SDLoc DL(N);
6305         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6306                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6307         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6308                                     SDLoc(N0.getOperand(0)),
6309                                     N0.getOperand(0).getValueType(), ExtLoad);
6310         CombineTo(N, And);
6311         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6312         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6313                         ISD::SIGN_EXTEND);
6314         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6315       }
6316     }
6317   }
6318 
6319   if (N0.getOpcode() == ISD::SETCC) {
6320     EVT N0VT = N0.getOperand(0).getValueType();
6321     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6322     // Only do this before legalize for now.
6323     if (VT.isVector() && !LegalOperations &&
6324         TLI.getBooleanContents(N0VT) ==
6325             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6326       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6327       // of the same size as the compared operands. Only optimize sext(setcc())
6328       // if this is the case.
6329       EVT SVT = getSetCCResultType(N0VT);
6330 
6331       // We know that the # elements of the results is the same as the
6332       // # elements of the compare (and the # elements of the compare result
6333       // for that matter).  Check to see that they are the same size.  If so,
6334       // we know that the element size of the sext'd result matches the
6335       // element size of the compare operands.
6336       if (VT.getSizeInBits() == SVT.getSizeInBits())
6337         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6338                              N0.getOperand(1),
6339                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6340 
6341       // If the desired elements are smaller or larger than the source
6342       // elements we can use a matching integer vector type and then
6343       // truncate/sign extend
6344       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6345       if (SVT == MatchingVectorType) {
6346         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6347                                N0.getOperand(0), N0.getOperand(1),
6348                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6349         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6350       }
6351     }
6352 
6353     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6354     // Here, T can be 1 or -1, depending on the type of the setcc and
6355     // getBooleanContents().
6356     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
6357 
6358     SDLoc DL(N);
6359     // To determine the "true" side of the select, we need to know the high bit
6360     // of the value returned by the setcc if it evaluates to true.
6361     // If the type of the setcc is i1, then the true case of the select is just
6362     // sext(i1 1), that is, -1.
6363     // If the type of the setcc is larger (say, i8) then the value of the high
6364     // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6365     // of the appropriate width.
6366     SDValue ExtTrueVal =
6367         (SetCCWidth == 1)
6368             ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6369                               DL, VT)
6370             : TLI.getConstTrueVal(DAG, VT, DL);
6371 
6372     if (SDValue SCC = SimplifySelectCC(
6373             DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6374             DAG.getConstant(0, DL, VT),
6375             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6376       return SCC;
6377 
6378     if (!VT.isVector()) {
6379       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6380       if (!LegalOperations ||
6381           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6382         SDLoc DL(N);
6383         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6384         SDValue SetCC =
6385             DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6386         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6387                              DAG.getConstant(0, DL, VT));
6388       }
6389     }
6390   }
6391 
6392   // fold (sext x) -> (zext x) if the sign bit is known zero.
6393   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6394       DAG.SignBitIsZero(N0))
6395     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6396 
6397   return SDValue();
6398 }
6399 
6400 // isTruncateOf - If N is a truncate of some other value, return true, record
6401 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6402 // This function computes KnownZero to avoid a duplicated call to
6403 // computeKnownBits in the caller.
6404 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6405                          APInt &KnownZero) {
6406   APInt KnownOne;
6407   if (N->getOpcode() == ISD::TRUNCATE) {
6408     Op = N->getOperand(0);
6409     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6410     return true;
6411   }
6412 
6413   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6414       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6415     return false;
6416 
6417   SDValue Op0 = N->getOperand(0);
6418   SDValue Op1 = N->getOperand(1);
6419   assert(Op0.getValueType() == Op1.getValueType());
6420 
6421   if (isNullConstant(Op0))
6422     Op = Op1;
6423   else if (isNullConstant(Op1))
6424     Op = Op0;
6425   else
6426     return false;
6427 
6428   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6429 
6430   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6431     return false;
6432 
6433   return true;
6434 }
6435 
6436 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6437   SDValue N0 = N->getOperand(0);
6438   EVT VT = N->getValueType(0);
6439 
6440   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6441                                               LegalOperations))
6442     return SDValue(Res, 0);
6443 
6444   // fold (zext (zext x)) -> (zext x)
6445   // fold (zext (aext x)) -> (zext x)
6446   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6447     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6448                        N0.getOperand(0));
6449 
6450   // fold (zext (truncate x)) -> (zext x) or
6451   //      (zext (truncate x)) -> (truncate x)
6452   // This is valid when the truncated bits of x are already zero.
6453   // FIXME: We should extend this to work for vectors too.
6454   SDValue Op;
6455   APInt KnownZero;
6456   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6457     APInt TruncatedBits =
6458       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6459       APInt(Op.getValueSizeInBits(), 0) :
6460       APInt::getBitsSet(Op.getValueSizeInBits(),
6461                         N0.getValueSizeInBits(),
6462                         std::min(Op.getValueSizeInBits(),
6463                                  VT.getSizeInBits()));
6464     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6465       if (VT.bitsGT(Op.getValueType()))
6466         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6467       if (VT.bitsLT(Op.getValueType()))
6468         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6469 
6470       return Op;
6471     }
6472   }
6473 
6474   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6475   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6476   if (N0.getOpcode() == ISD::TRUNCATE) {
6477     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6478       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6479       if (NarrowLoad.getNode() != N0.getNode()) {
6480         CombineTo(N0.getNode(), NarrowLoad);
6481         // CombineTo deleted the truncate, if needed, but not what's under it.
6482         AddToWorklist(oye);
6483       }
6484       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6485     }
6486   }
6487 
6488   // fold (zext (truncate x)) -> (and x, mask)
6489   if (N0.getOpcode() == ISD::TRUNCATE) {
6490     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6491     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6492     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6493       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6494       if (NarrowLoad.getNode() != N0.getNode()) {
6495         CombineTo(N0.getNode(), NarrowLoad);
6496         // CombineTo deleted the truncate, if needed, but not what's under it.
6497         AddToWorklist(oye);
6498       }
6499       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6500     }
6501 
6502     EVT SrcVT = N0.getOperand(0).getValueType();
6503     EVT MinVT = N0.getValueType();
6504 
6505     // Try to mask before the extension to avoid having to generate a larger mask,
6506     // possibly over several sub-vectors.
6507     if (SrcVT.bitsLT(VT)) {
6508       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6509                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6510         SDValue Op = N0.getOperand(0);
6511         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6512         AddToWorklist(Op.getNode());
6513         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6514       }
6515     }
6516 
6517     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6518       SDValue Op = N0.getOperand(0);
6519       if (SrcVT.bitsLT(VT)) {
6520         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6521         AddToWorklist(Op.getNode());
6522       } else if (SrcVT.bitsGT(VT)) {
6523         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6524         AddToWorklist(Op.getNode());
6525       }
6526       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6527     }
6528   }
6529 
6530   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6531   // if either of the casts is not free.
6532   if (N0.getOpcode() == ISD::AND &&
6533       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6534       N0.getOperand(1).getOpcode() == ISD::Constant &&
6535       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6536                            N0.getValueType()) ||
6537        !TLI.isZExtFree(N0.getValueType(), VT))) {
6538     SDValue X = N0.getOperand(0).getOperand(0);
6539     if (X.getValueType().bitsLT(VT)) {
6540       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6541     } else if (X.getValueType().bitsGT(VT)) {
6542       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6543     }
6544     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6545     Mask = Mask.zext(VT.getSizeInBits());
6546     SDLoc DL(N);
6547     return DAG.getNode(ISD::AND, DL, VT,
6548                        X, DAG.getConstant(Mask, DL, VT));
6549   }
6550 
6551   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6552   // Only generate vector extloads when 1) they're legal, and 2) they are
6553   // deemed desirable by the target.
6554   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6555       ((!LegalOperations && !VT.isVector() &&
6556         !cast<LoadSDNode>(N0)->isVolatile()) ||
6557        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6558     bool DoXform = true;
6559     SmallVector<SDNode*, 4> SetCCs;
6560     if (!N0.hasOneUse())
6561       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6562     if (VT.isVector())
6563       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6564     if (DoXform) {
6565       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6566       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6567                                        LN0->getChain(),
6568                                        LN0->getBasePtr(), N0.getValueType(),
6569                                        LN0->getMemOperand());
6570       CombineTo(N, ExtLoad);
6571       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6572                                   N0.getValueType(), ExtLoad);
6573       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6574 
6575       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6576                       ISD::ZERO_EXTEND);
6577       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6578     }
6579   }
6580 
6581   // fold (zext (load x)) to multiple smaller zextloads.
6582   // Only on illegal but splittable vectors.
6583   if (SDValue ExtLoad = CombineExtLoad(N))
6584     return ExtLoad;
6585 
6586   // fold (zext (and/or/xor (load x), cst)) ->
6587   //      (and/or/xor (zextload x), (zext cst))
6588   // Unless (and (load x) cst) will match as a zextload already and has
6589   // additional users.
6590   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6591        N0.getOpcode() == ISD::XOR) &&
6592       isa<LoadSDNode>(N0.getOperand(0)) &&
6593       N0.getOperand(1).getOpcode() == ISD::Constant &&
6594       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6595       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6596     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6597     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6598       bool DoXform = true;
6599       SmallVector<SDNode*, 4> SetCCs;
6600       if (!N0.hasOneUse()) {
6601         if (N0.getOpcode() == ISD::AND) {
6602           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6603           auto NarrowLoad = false;
6604           EVT LoadResultTy = AndC->getValueType(0);
6605           EVT ExtVT, LoadedVT;
6606           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6607                                NarrowLoad))
6608             DoXform = false;
6609         }
6610         if (DoXform)
6611           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6612                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6613       }
6614       if (DoXform) {
6615         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6616                                          LN0->getChain(), LN0->getBasePtr(),
6617                                          LN0->getMemoryVT(),
6618                                          LN0->getMemOperand());
6619         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6620         Mask = Mask.zext(VT.getSizeInBits());
6621         SDLoc DL(N);
6622         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6623                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6624         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6625                                     SDLoc(N0.getOperand(0)),
6626                                     N0.getOperand(0).getValueType(), ExtLoad);
6627         CombineTo(N, And);
6628         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6629         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6630                         ISD::ZERO_EXTEND);
6631         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6632       }
6633     }
6634   }
6635 
6636   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6637   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6638   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6639       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6640     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6641     EVT MemVT = LN0->getMemoryVT();
6642     if ((!LegalOperations && !LN0->isVolatile()) ||
6643         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6644       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6645                                        LN0->getChain(),
6646                                        LN0->getBasePtr(), MemVT,
6647                                        LN0->getMemOperand());
6648       CombineTo(N, ExtLoad);
6649       CombineTo(N0.getNode(),
6650                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6651                             ExtLoad),
6652                 ExtLoad.getValue(1));
6653       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6654     }
6655   }
6656 
6657   if (N0.getOpcode() == ISD::SETCC) {
6658     // Only do this before legalize for now.
6659     if (!LegalOperations && VT.isVector() &&
6660         N0.getValueType().getVectorElementType() == MVT::i1) {
6661       EVT N00VT = N0.getOperand(0).getValueType();
6662       if (getSetCCResultType(N00VT) == N0.getValueType())
6663         return SDValue();
6664 
6665       // We know that the # elements of the results is the same as the #
6666       // elements of the compare (and the # elements of the compare result for
6667       // that matter). Check to see that they are the same size. If so, we know
6668       // that the element size of the sext'd result matches the element size of
6669       // the compare operands.
6670       SDLoc DL(N);
6671       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6672       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
6673         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6674         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
6675                                      N0.getOperand(1), N0.getOperand(2));
6676         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
6677       }
6678 
6679       // If the desired elements are smaller or larger than the source
6680       // elements we can use a matching integer vector type and then
6681       // truncate/sign extend.
6682       EVT MatchingElementType = EVT::getIntegerVT(
6683           *DAG.getContext(), N00VT.getScalarSizeInBits());
6684       EVT MatchingVectorType = EVT::getVectorVT(
6685           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
6686       SDValue VsetCC =
6687           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
6688                       N0.getOperand(1), N0.getOperand(2));
6689       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
6690                          VecOnes);
6691     }
6692 
6693     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6694     SDLoc DL(N);
6695     if (SDValue SCC = SimplifySelectCC(
6696             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6697             DAG.getConstant(0, DL, VT),
6698             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6699       return SCC;
6700   }
6701 
6702   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6703   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6704       isa<ConstantSDNode>(N0.getOperand(1)) &&
6705       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6706       N0.hasOneUse()) {
6707     SDValue ShAmt = N0.getOperand(1);
6708     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6709     if (N0.getOpcode() == ISD::SHL) {
6710       SDValue InnerZExt = N0.getOperand(0);
6711       // If the original shl may be shifting out bits, do not perform this
6712       // transformation.
6713       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
6714         InnerZExt.getOperand(0).getValueSizeInBits();
6715       if (ShAmtVal > KnownZeroBits)
6716         return SDValue();
6717     }
6718 
6719     SDLoc DL(N);
6720 
6721     // Ensure that the shift amount is wide enough for the shifted value.
6722     if (VT.getSizeInBits() >= 256)
6723       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6724 
6725     return DAG.getNode(N0.getOpcode(), DL, VT,
6726                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6727                        ShAmt);
6728   }
6729 
6730   return SDValue();
6731 }
6732 
6733 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6734   SDValue N0 = N->getOperand(0);
6735   EVT VT = N->getValueType(0);
6736 
6737   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6738                                               LegalOperations))
6739     return SDValue(Res, 0);
6740 
6741   // fold (aext (aext x)) -> (aext x)
6742   // fold (aext (zext x)) -> (zext x)
6743   // fold (aext (sext x)) -> (sext x)
6744   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6745       N0.getOpcode() == ISD::ZERO_EXTEND ||
6746       N0.getOpcode() == ISD::SIGN_EXTEND)
6747     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6748 
6749   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6750   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6751   if (N0.getOpcode() == ISD::TRUNCATE) {
6752     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6753       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6754       if (NarrowLoad.getNode() != N0.getNode()) {
6755         CombineTo(N0.getNode(), NarrowLoad);
6756         // CombineTo deleted the truncate, if needed, but not what's under it.
6757         AddToWorklist(oye);
6758       }
6759       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6760     }
6761   }
6762 
6763   // fold (aext (truncate x))
6764   if (N0.getOpcode() == ISD::TRUNCATE) {
6765     SDValue TruncOp = N0.getOperand(0);
6766     if (TruncOp.getValueType() == VT)
6767       return TruncOp; // x iff x size == zext size.
6768     if (TruncOp.getValueType().bitsGT(VT))
6769       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6770     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6771   }
6772 
6773   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6774   // if the trunc is not free.
6775   if (N0.getOpcode() == ISD::AND &&
6776       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6777       N0.getOperand(1).getOpcode() == ISD::Constant &&
6778       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6779                           N0.getValueType())) {
6780     SDLoc DL(N);
6781     SDValue X = N0.getOperand(0).getOperand(0);
6782     if (X.getValueType().bitsLT(VT)) {
6783       X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
6784     } else if (X.getValueType().bitsGT(VT)) {
6785       X = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
6786     }
6787     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6788     Mask = Mask.zext(VT.getSizeInBits());
6789     return DAG.getNode(ISD::AND, DL, VT,
6790                        X, DAG.getConstant(Mask, DL, VT));
6791   }
6792 
6793   // fold (aext (load x)) -> (aext (truncate (extload x)))
6794   // None of the supported targets knows how to perform load and any_ext
6795   // on vectors in one instruction.  We only perform this transformation on
6796   // scalars.
6797   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6798       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6799       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6800     bool DoXform = true;
6801     SmallVector<SDNode*, 4> SetCCs;
6802     if (!N0.hasOneUse())
6803       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6804     if (DoXform) {
6805       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6806       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6807                                        LN0->getChain(),
6808                                        LN0->getBasePtr(), N0.getValueType(),
6809                                        LN0->getMemOperand());
6810       CombineTo(N, ExtLoad);
6811       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6812                                   N0.getValueType(), ExtLoad);
6813       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6814       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6815                       ISD::ANY_EXTEND);
6816       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6817     }
6818   }
6819 
6820   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6821   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6822   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6823   if (N0.getOpcode() == ISD::LOAD &&
6824       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6825       N0.hasOneUse()) {
6826     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6827     ISD::LoadExtType ExtType = LN0->getExtensionType();
6828     EVT MemVT = LN0->getMemoryVT();
6829     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6830       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6831                                        VT, LN0->getChain(), LN0->getBasePtr(),
6832                                        MemVT, LN0->getMemOperand());
6833       CombineTo(N, ExtLoad);
6834       CombineTo(N0.getNode(),
6835                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6836                             N0.getValueType(), ExtLoad),
6837                 ExtLoad.getValue(1));
6838       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6839     }
6840   }
6841 
6842   if (N0.getOpcode() == ISD::SETCC) {
6843     // For vectors:
6844     // aext(setcc) -> vsetcc
6845     // aext(setcc) -> truncate(vsetcc)
6846     // aext(setcc) -> aext(vsetcc)
6847     // Only do this before legalize for now.
6848     if (VT.isVector() && !LegalOperations) {
6849       EVT N0VT = N0.getOperand(0).getValueType();
6850         // We know that the # elements of the results is the same as the
6851         // # elements of the compare (and the # elements of the compare result
6852         // for that matter).  Check to see that they are the same size.  If so,
6853         // we know that the element size of the sext'd result matches the
6854         // element size of the compare operands.
6855       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6856         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6857                              N0.getOperand(1),
6858                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6859       // If the desired elements are smaller or larger than the source
6860       // elements we can use a matching integer vector type and then
6861       // truncate/any extend
6862       else {
6863         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6864         SDValue VsetCC =
6865           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6866                         N0.getOperand(1),
6867                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6868         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6869       }
6870     }
6871 
6872     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6873     SDLoc DL(N);
6874     if (SDValue SCC = SimplifySelectCC(
6875             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6876             DAG.getConstant(0, DL, VT),
6877             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6878       return SCC;
6879   }
6880 
6881   return SDValue();
6882 }
6883 
6884 /// See if the specified operand can be simplified with the knowledge that only
6885 /// the bits specified by Mask are used.  If so, return the simpler operand,
6886 /// otherwise return a null SDValue.
6887 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6888   switch (V.getOpcode()) {
6889   default: break;
6890   case ISD::Constant: {
6891     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6892     assert(CV && "Const value should be ConstSDNode.");
6893     const APInt &CVal = CV->getAPIntValue();
6894     APInt NewVal = CVal & Mask;
6895     if (NewVal != CVal)
6896       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6897     break;
6898   }
6899   case ISD::OR:
6900   case ISD::XOR:
6901     // If the LHS or RHS don't contribute bits to the or, drop them.
6902     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6903       return V.getOperand(1);
6904     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6905       return V.getOperand(0);
6906     break;
6907   case ISD::SRL:
6908     // Only look at single-use SRLs.
6909     if (!V.getNode()->hasOneUse())
6910       break;
6911     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6912       // See if we can recursively simplify the LHS.
6913       unsigned Amt = RHSC->getZExtValue();
6914 
6915       // Watch out for shift count overflow though.
6916       if (Amt >= Mask.getBitWidth()) break;
6917       APInt NewMask = Mask << Amt;
6918       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6919         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6920                            SimplifyLHS, V.getOperand(1));
6921     }
6922   }
6923   return SDValue();
6924 }
6925 
6926 /// If the result of a wider load is shifted to right of N  bits and then
6927 /// truncated to a narrower type and where N is a multiple of number of bits of
6928 /// the narrower type, transform it to a narrower load from address + N / num of
6929 /// bits of new type. If the result is to be extended, also fold the extension
6930 /// to form a extending load.
6931 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6932   unsigned Opc = N->getOpcode();
6933 
6934   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6935   SDValue N0 = N->getOperand(0);
6936   EVT VT = N->getValueType(0);
6937   EVT ExtVT = VT;
6938 
6939   // This transformation isn't valid for vector loads.
6940   if (VT.isVector())
6941     return SDValue();
6942 
6943   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6944   // extended to VT.
6945   if (Opc == ISD::SIGN_EXTEND_INREG) {
6946     ExtType = ISD::SEXTLOAD;
6947     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6948   } else if (Opc == ISD::SRL) {
6949     // Another special-case: SRL is basically zero-extending a narrower value.
6950     ExtType = ISD::ZEXTLOAD;
6951     N0 = SDValue(N, 0);
6952     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6953     if (!N01) return SDValue();
6954     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6955                               VT.getSizeInBits() - N01->getZExtValue());
6956   }
6957   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6958     return SDValue();
6959 
6960   unsigned EVTBits = ExtVT.getSizeInBits();
6961 
6962   // Do not generate loads of non-round integer types since these can
6963   // be expensive (and would be wrong if the type is not byte sized).
6964   if (!ExtVT.isRound())
6965     return SDValue();
6966 
6967   unsigned ShAmt = 0;
6968   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6969     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6970       ShAmt = N01->getZExtValue();
6971       // Is the shift amount a multiple of size of VT?
6972       if ((ShAmt & (EVTBits-1)) == 0) {
6973         N0 = N0.getOperand(0);
6974         // Is the load width a multiple of size of VT?
6975         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
6976           return SDValue();
6977       }
6978 
6979       // At this point, we must have a load or else we can't do the transform.
6980       if (!isa<LoadSDNode>(N0)) return SDValue();
6981 
6982       // Because a SRL must be assumed to *need* to zero-extend the high bits
6983       // (as opposed to anyext the high bits), we can't combine the zextload
6984       // lowering of SRL and an sextload.
6985       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6986         return SDValue();
6987 
6988       // If the shift amount is larger than the input type then we're not
6989       // accessing any of the loaded bytes.  If the load was a zextload/extload
6990       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6991       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6992         return SDValue();
6993     }
6994   }
6995 
6996   // If the load is shifted left (and the result isn't shifted back right),
6997   // we can fold the truncate through the shift.
6998   unsigned ShLeftAmt = 0;
6999   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7000       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7001     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7002       ShLeftAmt = N01->getZExtValue();
7003       N0 = N0.getOperand(0);
7004     }
7005   }
7006 
7007   // If we haven't found a load, we can't narrow it.  Don't transform one with
7008   // multiple uses, this would require adding a new load.
7009   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7010     return SDValue();
7011 
7012   // Don't change the width of a volatile load.
7013   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7014   if (LN0->isVolatile())
7015     return SDValue();
7016 
7017   // Verify that we are actually reducing a load width here.
7018   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7019     return SDValue();
7020 
7021   // For the transform to be legal, the load must produce only two values
7022   // (the value loaded and the chain).  Don't transform a pre-increment
7023   // load, for example, which produces an extra value.  Otherwise the
7024   // transformation is not equivalent, and the downstream logic to replace
7025   // uses gets things wrong.
7026   if (LN0->getNumValues() > 2)
7027     return SDValue();
7028 
7029   // If the load that we're shrinking is an extload and we're not just
7030   // discarding the extension we can't simply shrink the load. Bail.
7031   // TODO: It would be possible to merge the extensions in some cases.
7032   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7033       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7034     return SDValue();
7035 
7036   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7037     return SDValue();
7038 
7039   EVT PtrType = N0.getOperand(1).getValueType();
7040 
7041   if (PtrType == MVT::Untyped || PtrType.isExtended())
7042     // It's not possible to generate a constant of extended or untyped type.
7043     return SDValue();
7044 
7045   // For big endian targets, we need to adjust the offset to the pointer to
7046   // load the correct bytes.
7047   if (DAG.getDataLayout().isBigEndian()) {
7048     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7049     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7050     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7051   }
7052 
7053   uint64_t PtrOff = ShAmt / 8;
7054   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7055   SDLoc DL(LN0);
7056   // The original load itself didn't wrap, so an offset within it doesn't.
7057   SDNodeFlags Flags;
7058   Flags.setNoUnsignedWrap(true);
7059   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7060                                PtrType, LN0->getBasePtr(),
7061                                DAG.getConstant(PtrOff, DL, PtrType),
7062                                &Flags);
7063   AddToWorklist(NewPtr.getNode());
7064 
7065   SDValue Load;
7066   if (ExtType == ISD::NON_EXTLOAD)
7067     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7068                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7069                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7070   else
7071     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7072                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7073                           NewAlign, LN0->getMemOperand()->getFlags(),
7074                           LN0->getAAInfo());
7075 
7076   // Replace the old load's chain with the new load's chain.
7077   WorklistRemover DeadNodes(*this);
7078   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7079 
7080   // Shift the result left, if we've swallowed a left shift.
7081   SDValue Result = Load;
7082   if (ShLeftAmt != 0) {
7083     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7084     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7085       ShImmTy = VT;
7086     // If the shift amount is as large as the result size (but, presumably,
7087     // no larger than the source) then the useful bits of the result are
7088     // zero; we can't simply return the shortened shift, because the result
7089     // of that operation is undefined.
7090     SDLoc DL(N0);
7091     if (ShLeftAmt >= VT.getSizeInBits())
7092       Result = DAG.getConstant(0, DL, VT);
7093     else
7094       Result = DAG.getNode(ISD::SHL, DL, VT,
7095                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7096   }
7097 
7098   // Return the new loaded value.
7099   return Result;
7100 }
7101 
7102 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7103   SDValue N0 = N->getOperand(0);
7104   SDValue N1 = N->getOperand(1);
7105   EVT VT = N->getValueType(0);
7106   EVT EVT = cast<VTSDNode>(N1)->getVT();
7107   unsigned VTBits = VT.getScalarSizeInBits();
7108   unsigned EVTBits = EVT.getScalarSizeInBits();
7109 
7110   if (N0.isUndef())
7111     return DAG.getUNDEF(VT);
7112 
7113   // fold (sext_in_reg c1) -> c1
7114   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7115     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7116 
7117   // If the input is already sign extended, just drop the extension.
7118   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7119     return N0;
7120 
7121   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7122   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7123       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7124     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7125                        N0.getOperand(0), N1);
7126 
7127   // fold (sext_in_reg (sext x)) -> (sext x)
7128   // fold (sext_in_reg (aext x)) -> (sext x)
7129   // if x is small enough.
7130   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7131     SDValue N00 = N0.getOperand(0);
7132     if (N00.getScalarValueSizeInBits() <= EVTBits &&
7133         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7134       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7135   }
7136 
7137   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7138   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7139     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7140 
7141   // fold operands of sext_in_reg based on knowledge that the top bits are not
7142   // demanded.
7143   if (SimplifyDemandedBits(SDValue(N, 0)))
7144     return SDValue(N, 0);
7145 
7146   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7147   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7148   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7149     return NarrowLoad;
7150 
7151   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7152   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7153   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7154   if (N0.getOpcode() == ISD::SRL) {
7155     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7156       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7157         // We can turn this into an SRA iff the input to the SRL is already sign
7158         // extended enough.
7159         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7160         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7161           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7162                              N0.getOperand(0), N0.getOperand(1));
7163       }
7164   }
7165 
7166   // fold (sext_inreg (extload x)) -> (sextload x)
7167   if (ISD::isEXTLoad(N0.getNode()) &&
7168       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7169       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7170       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7171        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7172     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7173     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7174                                      LN0->getChain(),
7175                                      LN0->getBasePtr(), EVT,
7176                                      LN0->getMemOperand());
7177     CombineTo(N, ExtLoad);
7178     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7179     AddToWorklist(ExtLoad.getNode());
7180     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7181   }
7182   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7183   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7184       N0.hasOneUse() &&
7185       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7186       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7187        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7188     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7189     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7190                                      LN0->getChain(),
7191                                      LN0->getBasePtr(), EVT,
7192                                      LN0->getMemOperand());
7193     CombineTo(N, ExtLoad);
7194     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7195     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7196   }
7197 
7198   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7199   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7200     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7201                                            N0.getOperand(1), false))
7202       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7203                          BSwap, N1);
7204   }
7205 
7206   return SDValue();
7207 }
7208 
7209 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7210   SDValue N0 = N->getOperand(0);
7211   EVT VT = N->getValueType(0);
7212 
7213   if (N0.isUndef())
7214     return DAG.getUNDEF(VT);
7215 
7216   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7217                                               LegalOperations))
7218     return SDValue(Res, 0);
7219 
7220   return SDValue();
7221 }
7222 
7223 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7224   SDValue N0 = N->getOperand(0);
7225   EVT VT = N->getValueType(0);
7226 
7227   if (N0.isUndef())
7228     return DAG.getUNDEF(VT);
7229 
7230   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7231                                               LegalOperations))
7232     return SDValue(Res, 0);
7233 
7234   return SDValue();
7235 }
7236 
7237 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7238   SDValue N0 = N->getOperand(0);
7239   EVT VT = N->getValueType(0);
7240   bool isLE = DAG.getDataLayout().isLittleEndian();
7241 
7242   // noop truncate
7243   if (N0.getValueType() == N->getValueType(0))
7244     return N0;
7245   // fold (truncate c1) -> c1
7246   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7247     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7248   // fold (truncate (truncate x)) -> (truncate x)
7249   if (N0.getOpcode() == ISD::TRUNCATE)
7250     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7251   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7252   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7253       N0.getOpcode() == ISD::SIGN_EXTEND ||
7254       N0.getOpcode() == ISD::ANY_EXTEND) {
7255     // if the source is smaller than the dest, we still need an extend.
7256     if (N0.getOperand(0).getValueType().bitsLT(VT))
7257       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7258     // if the source is larger than the dest, than we just need the truncate.
7259     if (N0.getOperand(0).getValueType().bitsGT(VT))
7260       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7261     // if the source and dest are the same type, we can drop both the extend
7262     // and the truncate.
7263     return N0.getOperand(0);
7264   }
7265 
7266   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
7267   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
7268     return SDValue();
7269 
7270   // Fold extract-and-trunc into a narrow extract. For example:
7271   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7272   //   i32 y = TRUNCATE(i64 x)
7273   //        -- becomes --
7274   //   v16i8 b = BITCAST (v2i64 val)
7275   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7276   //
7277   // Note: We only run this optimization after type legalization (which often
7278   // creates this pattern) and before operation legalization after which
7279   // we need to be more careful about the vector instructions that we generate.
7280   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7281       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7282 
7283     EVT VecTy = N0.getOperand(0).getValueType();
7284     EVT ExTy = N0.getValueType();
7285     EVT TrTy = N->getValueType(0);
7286 
7287     unsigned NumElem = VecTy.getVectorNumElements();
7288     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7289 
7290     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7291     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7292 
7293     SDValue EltNo = N0->getOperand(1);
7294     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7295       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7296       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7297       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7298 
7299       SDLoc DL(N);
7300       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7301                          DAG.getBitcast(NVT, N0.getOperand(0)),
7302                          DAG.getConstant(Index, DL, IndexTy));
7303     }
7304   }
7305 
7306   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7307   if (N0.getOpcode() == ISD::SELECT) {
7308     EVT SrcVT = N0.getValueType();
7309     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7310         TLI.isTruncateFree(SrcVT, VT)) {
7311       SDLoc SL(N0);
7312       SDValue Cond = N0.getOperand(0);
7313       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7314       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7315       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7316     }
7317   }
7318 
7319   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
7320   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7321       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7322       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7323     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7324       uint64_t Amt = CAmt->getZExtValue();
7325       unsigned Size = VT.getScalarSizeInBits();
7326 
7327       if (Amt < Size) {
7328         SDLoc SL(N);
7329         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7330 
7331         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7332         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7333                            DAG.getConstant(Amt, SL, AmtVT));
7334       }
7335     }
7336   }
7337 
7338   // Fold a series of buildvector, bitcast, and truncate if possible.
7339   // For example fold
7340   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7341   //   (2xi32 (buildvector x, y)).
7342   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7343       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7344       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7345       N0.getOperand(0).hasOneUse()) {
7346 
7347     SDValue BuildVect = N0.getOperand(0);
7348     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7349     EVT TruncVecEltTy = VT.getVectorElementType();
7350 
7351     // Check that the element types match.
7352     if (BuildVectEltTy == TruncVecEltTy) {
7353       // Now we only need to compute the offset of the truncated elements.
7354       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7355       unsigned TruncVecNumElts = VT.getVectorNumElements();
7356       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7357 
7358       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7359              "Invalid number of elements");
7360 
7361       SmallVector<SDValue, 8> Opnds;
7362       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7363         Opnds.push_back(BuildVect.getOperand(i));
7364 
7365       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7366     }
7367   }
7368 
7369   // See if we can simplify the input to this truncate through knowledge that
7370   // only the low bits are being used.
7371   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7372   // Currently we only perform this optimization on scalars because vectors
7373   // may have different active low bits.
7374   if (!VT.isVector()) {
7375     if (SDValue Shorter =
7376             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7377                                                      VT.getSizeInBits())))
7378       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7379   }
7380   // fold (truncate (load x)) -> (smaller load x)
7381   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7382   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7383     if (SDValue Reduced = ReduceLoadWidth(N))
7384       return Reduced;
7385 
7386     // Handle the case where the load remains an extending load even
7387     // after truncation.
7388     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7389       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7390       if (!LN0->isVolatile() &&
7391           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7392         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7393                                          VT, LN0->getChain(), LN0->getBasePtr(),
7394                                          LN0->getMemoryVT(),
7395                                          LN0->getMemOperand());
7396         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7397         return NewLoad;
7398       }
7399     }
7400   }
7401   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7402   // where ... are all 'undef'.
7403   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7404     SmallVector<EVT, 8> VTs;
7405     SDValue V;
7406     unsigned Idx = 0;
7407     unsigned NumDefs = 0;
7408 
7409     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7410       SDValue X = N0.getOperand(i);
7411       if (!X.isUndef()) {
7412         V = X;
7413         Idx = i;
7414         NumDefs++;
7415       }
7416       // Stop if more than one members are non-undef.
7417       if (NumDefs > 1)
7418         break;
7419       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7420                                      VT.getVectorElementType(),
7421                                      X.getValueType().getVectorNumElements()));
7422     }
7423 
7424     if (NumDefs == 0)
7425       return DAG.getUNDEF(VT);
7426 
7427     if (NumDefs == 1) {
7428       assert(V.getNode() && "The single defined operand is empty!");
7429       SmallVector<SDValue, 8> Opnds;
7430       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7431         if (i != Idx) {
7432           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7433           continue;
7434         }
7435         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7436         AddToWorklist(NV.getNode());
7437         Opnds.push_back(NV);
7438       }
7439       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7440     }
7441   }
7442 
7443   // Fold truncate of a bitcast of a vector to an extract of the low vector
7444   // element.
7445   //
7446   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7447   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7448     SDValue VecSrc = N0.getOperand(0);
7449     EVT SrcVT = VecSrc.getValueType();
7450     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7451         (!LegalOperations ||
7452          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7453       SDLoc SL(N);
7454 
7455       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7456       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7457                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7458     }
7459   }
7460 
7461   // Simplify the operands using demanded-bits information.
7462   if (!VT.isVector() &&
7463       SimplifyDemandedBits(SDValue(N, 0)))
7464     return SDValue(N, 0);
7465 
7466   return SDValue();
7467 }
7468 
7469 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7470   SDValue Elt = N->getOperand(i);
7471   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7472     return Elt.getNode();
7473   return Elt.getOperand(Elt.getResNo()).getNode();
7474 }
7475 
7476 /// build_pair (load, load) -> load
7477 /// if load locations are consecutive.
7478 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7479   assert(N->getOpcode() == ISD::BUILD_PAIR);
7480 
7481   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7482   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7483   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7484       LD1->getAddressSpace() != LD2->getAddressSpace())
7485     return SDValue();
7486   EVT LD1VT = LD1->getValueType(0);
7487   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7488   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7489       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7490     unsigned Align = LD1->getAlignment();
7491     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7492         VT.getTypeForEVT(*DAG.getContext()));
7493 
7494     if (NewAlign <= Align &&
7495         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7496       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
7497                          LD1->getPointerInfo(), Align);
7498   }
7499 
7500   return SDValue();
7501 }
7502 
7503 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7504   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7505   // and Lo parts; on big-endian machines it doesn't.
7506   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7507 }
7508 
7509 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7510                                     const TargetLowering &TLI) {
7511   // If this is not a bitcast to an FP type or if the target doesn't have
7512   // IEEE754-compliant FP logic, we're done.
7513   EVT VT = N->getValueType(0);
7514   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7515     return SDValue();
7516 
7517   // TODO: Use splat values for the constant-checking below and remove this
7518   // restriction.
7519   SDValue N0 = N->getOperand(0);
7520   EVT SourceVT = N0.getValueType();
7521   if (SourceVT.isVector())
7522     return SDValue();
7523 
7524   unsigned FPOpcode;
7525   APInt SignMask;
7526   switch (N0.getOpcode()) {
7527   case ISD::AND:
7528     FPOpcode = ISD::FABS;
7529     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7530     break;
7531   case ISD::XOR:
7532     FPOpcode = ISD::FNEG;
7533     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7534     break;
7535   // TODO: ISD::OR --> ISD::FNABS?
7536   default:
7537     return SDValue();
7538   }
7539 
7540   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7541   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7542   SDValue LogicOp0 = N0.getOperand(0);
7543   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7544   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7545       LogicOp0.getOpcode() == ISD::BITCAST &&
7546       LogicOp0->getOperand(0).getValueType() == VT)
7547     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7548 
7549   return SDValue();
7550 }
7551 
7552 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7553   SDValue N0 = N->getOperand(0);
7554   EVT VT = N->getValueType(0);
7555 
7556   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7557   // Only do this before legalize, since afterward the target may be depending
7558   // on the bitconvert.
7559   // First check to see if this is all constant.
7560   if (!LegalTypes &&
7561       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7562       VT.isVector()) {
7563     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7564 
7565     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7566     assert(!DestEltVT.isVector() &&
7567            "Element type of vector ValueType must not be vector!");
7568     if (isSimple)
7569       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7570   }
7571 
7572   // If the input is a constant, let getNode fold it.
7573   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7574     // If we can't allow illegal operations, we need to check that this is just
7575     // a fp -> int or int -> conversion and that the resulting operation will
7576     // be legal.
7577     if (!LegalOperations ||
7578         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7579          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7580         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7581          TLI.isOperationLegal(ISD::Constant, VT)))
7582       return DAG.getBitcast(VT, N0);
7583   }
7584 
7585   // (conv (conv x, t1), t2) -> (conv x, t2)
7586   if (N0.getOpcode() == ISD::BITCAST)
7587     return DAG.getBitcast(VT, N0.getOperand(0));
7588 
7589   // fold (conv (load x)) -> (load (conv*)x)
7590   // If the resultant load doesn't need a higher alignment than the original!
7591   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7592       // Do not change the width of a volatile load.
7593       !cast<LoadSDNode>(N0)->isVolatile() &&
7594       // Do not remove the cast if the types differ in endian layout.
7595       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7596           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7597       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7598       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7599     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7600     unsigned OrigAlign = LN0->getAlignment();
7601 
7602     bool Fast = false;
7603     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7604                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7605         Fast) {
7606       SDValue Load =
7607           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7608                       LN0->getPointerInfo(), OrigAlign,
7609                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7610       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7611       return Load;
7612     }
7613   }
7614 
7615   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7616     return V;
7617 
7618   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7619   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7620   //
7621   // For ppc_fp128:
7622   // fold (bitcast (fneg x)) ->
7623   //     flipbit = signbit
7624   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7625   //
7626   // fold (bitcast (fabs x)) ->
7627   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7628   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7629   // This often reduces constant pool loads.
7630   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7631        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7632       N0.getNode()->hasOneUse() && VT.isInteger() &&
7633       !VT.isVector() && !N0.getValueType().isVector()) {
7634     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7635     AddToWorklist(NewConv.getNode());
7636 
7637     SDLoc DL(N);
7638     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7639       assert(VT.getSizeInBits() == 128);
7640       SDValue SignBit = DAG.getConstant(
7641           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7642       SDValue FlipBit;
7643       if (N0.getOpcode() == ISD::FNEG) {
7644         FlipBit = SignBit;
7645         AddToWorklist(FlipBit.getNode());
7646       } else {
7647         assert(N0.getOpcode() == ISD::FABS);
7648         SDValue Hi =
7649             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7650                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7651                                               SDLoc(NewConv)));
7652         AddToWorklist(Hi.getNode());
7653         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7654         AddToWorklist(FlipBit.getNode());
7655       }
7656       SDValue FlipBits =
7657           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7658       AddToWorklist(FlipBits.getNode());
7659       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7660     }
7661     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7662     if (N0.getOpcode() == ISD::FNEG)
7663       return DAG.getNode(ISD::XOR, DL, VT,
7664                          NewConv, DAG.getConstant(SignBit, DL, VT));
7665     assert(N0.getOpcode() == ISD::FABS);
7666     return DAG.getNode(ISD::AND, DL, VT,
7667                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7668   }
7669 
7670   // fold (bitconvert (fcopysign cst, x)) ->
7671   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7672   // Note that we don't handle (copysign x, cst) because this can always be
7673   // folded to an fneg or fabs.
7674   //
7675   // For ppc_fp128:
7676   // fold (bitcast (fcopysign cst, x)) ->
7677   //     flipbit = (and (extract_element
7678   //                     (xor (bitcast cst), (bitcast x)), 0),
7679   //                    signbit)
7680   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7681   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7682       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7683       VT.isInteger() && !VT.isVector()) {
7684     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
7685     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7686     if (isTypeLegal(IntXVT)) {
7687       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7688       AddToWorklist(X.getNode());
7689 
7690       // If X has a different width than the result/lhs, sext it or truncate it.
7691       unsigned VTWidth = VT.getSizeInBits();
7692       if (OrigXWidth < VTWidth) {
7693         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7694         AddToWorklist(X.getNode());
7695       } else if (OrigXWidth > VTWidth) {
7696         // To get the sign bit in the right place, we have to shift it right
7697         // before truncating.
7698         SDLoc DL(X);
7699         X = DAG.getNode(ISD::SRL, DL,
7700                         X.getValueType(), X,
7701                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7702                                         X.getValueType()));
7703         AddToWorklist(X.getNode());
7704         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7705         AddToWorklist(X.getNode());
7706       }
7707 
7708       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7709         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7710         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7711         AddToWorklist(Cst.getNode());
7712         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7713         AddToWorklist(X.getNode());
7714         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7715         AddToWorklist(XorResult.getNode());
7716         SDValue XorResult64 = DAG.getNode(
7717             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7718             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7719                                   SDLoc(XorResult)));
7720         AddToWorklist(XorResult64.getNode());
7721         SDValue FlipBit =
7722             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7723                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7724         AddToWorklist(FlipBit.getNode());
7725         SDValue FlipBits =
7726             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7727         AddToWorklist(FlipBits.getNode());
7728         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7729       }
7730       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7731       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7732                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7733       AddToWorklist(X.getNode());
7734 
7735       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7736       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7737                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7738       AddToWorklist(Cst.getNode());
7739 
7740       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7741     }
7742   }
7743 
7744   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7745   if (N0.getOpcode() == ISD::BUILD_PAIR)
7746     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7747       return CombineLD;
7748 
7749   // Remove double bitcasts from shuffles - this is often a legacy of
7750   // XformToShuffleWithZero being used to combine bitmaskings (of
7751   // float vectors bitcast to integer vectors) into shuffles.
7752   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7753   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7754       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7755       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7756       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7757     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7758 
7759     // If operands are a bitcast, peek through if it casts the original VT.
7760     // If operands are a constant, just bitcast back to original VT.
7761     auto PeekThroughBitcast = [&](SDValue Op) {
7762       if (Op.getOpcode() == ISD::BITCAST &&
7763           Op.getOperand(0).getValueType() == VT)
7764         return SDValue(Op.getOperand(0));
7765       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7766           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7767         return DAG.getBitcast(VT, Op);
7768       return SDValue();
7769     };
7770 
7771     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7772     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7773     if (!(SV0 && SV1))
7774       return SDValue();
7775 
7776     int MaskScale =
7777         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7778     SmallVector<int, 8> NewMask;
7779     for (int M : SVN->getMask())
7780       for (int i = 0; i != MaskScale; ++i)
7781         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7782 
7783     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7784     if (!LegalMask) {
7785       std::swap(SV0, SV1);
7786       ShuffleVectorSDNode::commuteMask(NewMask);
7787       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7788     }
7789 
7790     if (LegalMask)
7791       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7792   }
7793 
7794   return SDValue();
7795 }
7796 
7797 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7798   EVT VT = N->getValueType(0);
7799   return CombineConsecutiveLoads(N, VT);
7800 }
7801 
7802 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7803 /// operands. DstEltVT indicates the destination element value type.
7804 SDValue DAGCombiner::
7805 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7806   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7807 
7808   // If this is already the right type, we're done.
7809   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7810 
7811   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7812   unsigned DstBitSize = DstEltVT.getSizeInBits();
7813 
7814   // If this is a conversion of N elements of one type to N elements of another
7815   // type, convert each element.  This handles FP<->INT cases.
7816   if (SrcBitSize == DstBitSize) {
7817     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7818                               BV->getValueType(0).getVectorNumElements());
7819 
7820     // Due to the FP element handling below calling this routine recursively,
7821     // we can end up with a scalar-to-vector node here.
7822     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7823       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7824                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7825 
7826     SmallVector<SDValue, 8> Ops;
7827     for (SDValue Op : BV->op_values()) {
7828       // If the vector element type is not legal, the BUILD_VECTOR operands
7829       // are promoted and implicitly truncated.  Make that explicit here.
7830       if (Op.getValueType() != SrcEltVT)
7831         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7832       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7833       AddToWorklist(Ops.back().getNode());
7834     }
7835     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7836   }
7837 
7838   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7839   // handle annoying details of growing/shrinking FP values, we convert them to
7840   // int first.
7841   if (SrcEltVT.isFloatingPoint()) {
7842     // Convert the input float vector to a int vector where the elements are the
7843     // same sizes.
7844     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7845     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7846     SrcEltVT = IntVT;
7847   }
7848 
7849   // Now we know the input is an integer vector.  If the output is a FP type,
7850   // convert to integer first, then to FP of the right size.
7851   if (DstEltVT.isFloatingPoint()) {
7852     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7853     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7854 
7855     // Next, convert to FP elements of the same size.
7856     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7857   }
7858 
7859   SDLoc DL(BV);
7860 
7861   // Okay, we know the src/dst types are both integers of differing types.
7862   // Handling growing first.
7863   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7864   if (SrcBitSize < DstBitSize) {
7865     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7866 
7867     SmallVector<SDValue, 8> Ops;
7868     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7869          i += NumInputsPerOutput) {
7870       bool isLE = DAG.getDataLayout().isLittleEndian();
7871       APInt NewBits = APInt(DstBitSize, 0);
7872       bool EltIsUndef = true;
7873       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7874         // Shift the previously computed bits over.
7875         NewBits <<= SrcBitSize;
7876         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7877         if (Op.isUndef()) continue;
7878         EltIsUndef = false;
7879 
7880         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7881                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7882       }
7883 
7884       if (EltIsUndef)
7885         Ops.push_back(DAG.getUNDEF(DstEltVT));
7886       else
7887         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7888     }
7889 
7890     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7891     return DAG.getBuildVector(VT, DL, Ops);
7892   }
7893 
7894   // Finally, this must be the case where we are shrinking elements: each input
7895   // turns into multiple outputs.
7896   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7897   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7898                             NumOutputsPerInput*BV->getNumOperands());
7899   SmallVector<SDValue, 8> Ops;
7900 
7901   for (const SDValue &Op : BV->op_values()) {
7902     if (Op.isUndef()) {
7903       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7904       continue;
7905     }
7906 
7907     APInt OpVal = cast<ConstantSDNode>(Op)->
7908                   getAPIntValue().zextOrTrunc(SrcBitSize);
7909 
7910     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7911       APInt ThisVal = OpVal.trunc(DstBitSize);
7912       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7913       OpVal = OpVal.lshr(DstBitSize);
7914     }
7915 
7916     // For big endian targets, swap the order of the pieces of each element.
7917     if (DAG.getDataLayout().isBigEndian())
7918       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7919   }
7920 
7921   return DAG.getBuildVector(VT, DL, Ops);
7922 }
7923 
7924 /// Try to perform FMA combining on a given FADD node.
7925 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7926   SDValue N0 = N->getOperand(0);
7927   SDValue N1 = N->getOperand(1);
7928   EVT VT = N->getValueType(0);
7929   SDLoc SL(N);
7930 
7931   const TargetOptions &Options = DAG.getTarget().Options;
7932   bool AllowFusion =
7933       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7934 
7935   // Floating-point multiply-add with intermediate rounding.
7936   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7937 
7938   // Floating-point multiply-add without intermediate rounding.
7939   bool HasFMA =
7940       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7941       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7942 
7943   // No valid opcode, do not combine.
7944   if (!HasFMAD && !HasFMA)
7945     return SDValue();
7946 
7947   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7948   ;
7949   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7950     return SDValue();
7951 
7952   // Always prefer FMAD to FMA for precision.
7953   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7954   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7955   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7956 
7957   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7958   // prefer to fold the multiply with fewer uses.
7959   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7960       N1.getOpcode() == ISD::FMUL) {
7961     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7962       std::swap(N0, N1);
7963   }
7964 
7965   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7966   if (N0.getOpcode() == ISD::FMUL &&
7967       (Aggressive || N0->hasOneUse())) {
7968     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7969                        N0.getOperand(0), N0.getOperand(1), N1);
7970   }
7971 
7972   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7973   // Note: Commutes FADD operands.
7974   if (N1.getOpcode() == ISD::FMUL &&
7975       (Aggressive || N1->hasOneUse())) {
7976     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7977                        N1.getOperand(0), N1.getOperand(1), N0);
7978   }
7979 
7980   // Look through FP_EXTEND nodes to do more combining.
7981   if (AllowFusion && LookThroughFPExt) {
7982     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7983     if (N0.getOpcode() == ISD::FP_EXTEND) {
7984       SDValue N00 = N0.getOperand(0);
7985       if (N00.getOpcode() == ISD::FMUL)
7986         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7987                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7988                                        N00.getOperand(0)),
7989                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7990                                        N00.getOperand(1)), N1);
7991     }
7992 
7993     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7994     // Note: Commutes FADD operands.
7995     if (N1.getOpcode() == ISD::FP_EXTEND) {
7996       SDValue N10 = N1.getOperand(0);
7997       if (N10.getOpcode() == ISD::FMUL)
7998         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7999                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8000                                        N10.getOperand(0)),
8001                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8002                                        N10.getOperand(1)), N0);
8003     }
8004   }
8005 
8006   // More folding opportunities when target permits.
8007   if ((AllowFusion || HasFMAD)  && Aggressive) {
8008     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8009     if (N0.getOpcode() == PreferredFusedOpcode &&
8010         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8011       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8012                          N0.getOperand(0), N0.getOperand(1),
8013                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8014                                      N0.getOperand(2).getOperand(0),
8015                                      N0.getOperand(2).getOperand(1),
8016                                      N1));
8017     }
8018 
8019     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8020     if (N1->getOpcode() == PreferredFusedOpcode &&
8021         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8022       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8023                          N1.getOperand(0), N1.getOperand(1),
8024                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8025                                      N1.getOperand(2).getOperand(0),
8026                                      N1.getOperand(2).getOperand(1),
8027                                      N0));
8028     }
8029 
8030     if (AllowFusion && LookThroughFPExt) {
8031       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8032       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8033       auto FoldFAddFMAFPExtFMul = [&] (
8034           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8035         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8036                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8037                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8038                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8039                                        Z));
8040       };
8041       if (N0.getOpcode() == PreferredFusedOpcode) {
8042         SDValue N02 = N0.getOperand(2);
8043         if (N02.getOpcode() == ISD::FP_EXTEND) {
8044           SDValue N020 = N02.getOperand(0);
8045           if (N020.getOpcode() == ISD::FMUL)
8046             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8047                                         N020.getOperand(0), N020.getOperand(1),
8048                                         N1);
8049         }
8050       }
8051 
8052       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8053       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8054       // FIXME: This turns two single-precision and one double-precision
8055       // operation into two double-precision operations, which might not be
8056       // interesting for all targets, especially GPUs.
8057       auto FoldFAddFPExtFMAFMul = [&] (
8058           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8059         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8060                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8061                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8062                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8063                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8064                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8065                                        Z));
8066       };
8067       if (N0.getOpcode() == ISD::FP_EXTEND) {
8068         SDValue N00 = N0.getOperand(0);
8069         if (N00.getOpcode() == PreferredFusedOpcode) {
8070           SDValue N002 = N00.getOperand(2);
8071           if (N002.getOpcode() == ISD::FMUL)
8072             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8073                                         N002.getOperand(0), N002.getOperand(1),
8074                                         N1);
8075         }
8076       }
8077 
8078       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8079       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
8080       if (N1.getOpcode() == PreferredFusedOpcode) {
8081         SDValue N12 = N1.getOperand(2);
8082         if (N12.getOpcode() == ISD::FP_EXTEND) {
8083           SDValue N120 = N12.getOperand(0);
8084           if (N120.getOpcode() == ISD::FMUL)
8085             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8086                                         N120.getOperand(0), N120.getOperand(1),
8087                                         N0);
8088         }
8089       }
8090 
8091       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8092       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8093       // FIXME: This turns two single-precision and one double-precision
8094       // operation into two double-precision operations, which might not be
8095       // interesting for all targets, especially GPUs.
8096       if (N1.getOpcode() == ISD::FP_EXTEND) {
8097         SDValue N10 = N1.getOperand(0);
8098         if (N10.getOpcode() == PreferredFusedOpcode) {
8099           SDValue N102 = N10.getOperand(2);
8100           if (N102.getOpcode() == ISD::FMUL)
8101             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8102                                         N102.getOperand(0), N102.getOperand(1),
8103                                         N0);
8104         }
8105       }
8106     }
8107   }
8108 
8109   return SDValue();
8110 }
8111 
8112 /// Try to perform FMA combining on a given FSUB node.
8113 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8114   SDValue N0 = N->getOperand(0);
8115   SDValue N1 = N->getOperand(1);
8116   EVT VT = N->getValueType(0);
8117   SDLoc SL(N);
8118 
8119   const TargetOptions &Options = DAG.getTarget().Options;
8120   bool AllowFusion =
8121       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8122 
8123   // Floating-point multiply-add with intermediate rounding.
8124   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8125 
8126   // Floating-point multiply-add without intermediate rounding.
8127   bool HasFMA =
8128       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8129       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8130 
8131   // No valid opcode, do not combine.
8132   if (!HasFMAD && !HasFMA)
8133     return SDValue();
8134 
8135   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8136   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8137     return SDValue();
8138 
8139   // Always prefer FMAD to FMA for precision.
8140   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8141   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8142   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8143 
8144   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8145   if (N0.getOpcode() == ISD::FMUL &&
8146       (Aggressive || N0->hasOneUse())) {
8147     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8148                        N0.getOperand(0), N0.getOperand(1),
8149                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8150   }
8151 
8152   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8153   // Note: Commutes FSUB operands.
8154   if (N1.getOpcode() == ISD::FMUL &&
8155       (Aggressive || N1->hasOneUse()))
8156     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8157                        DAG.getNode(ISD::FNEG, SL, VT,
8158                                    N1.getOperand(0)),
8159                        N1.getOperand(1), N0);
8160 
8161   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8162   if (N0.getOpcode() == ISD::FNEG &&
8163       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8164       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8165     SDValue N00 = N0.getOperand(0).getOperand(0);
8166     SDValue N01 = N0.getOperand(0).getOperand(1);
8167     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8168                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8169                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8170   }
8171 
8172   // Look through FP_EXTEND nodes to do more combining.
8173   if (AllowFusion && LookThroughFPExt) {
8174     // fold (fsub (fpext (fmul x, y)), z)
8175     //   -> (fma (fpext x), (fpext y), (fneg z))
8176     if (N0.getOpcode() == ISD::FP_EXTEND) {
8177       SDValue N00 = N0.getOperand(0);
8178       if (N00.getOpcode() == ISD::FMUL)
8179         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8180                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8181                                        N00.getOperand(0)),
8182                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8183                                        N00.getOperand(1)),
8184                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8185     }
8186 
8187     // fold (fsub x, (fpext (fmul y, z)))
8188     //   -> (fma (fneg (fpext y)), (fpext z), x)
8189     // Note: Commutes FSUB operands.
8190     if (N1.getOpcode() == ISD::FP_EXTEND) {
8191       SDValue N10 = N1.getOperand(0);
8192       if (N10.getOpcode() == ISD::FMUL)
8193         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8194                            DAG.getNode(ISD::FNEG, SL, VT,
8195                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8196                                                    N10.getOperand(0))),
8197                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8198                                        N10.getOperand(1)),
8199                            N0);
8200     }
8201 
8202     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8203     //   -> (fneg (fma (fpext x), (fpext y), z))
8204     // Note: This could be removed with appropriate canonicalization of the
8205     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8206     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8207     // from implementing the canonicalization in visitFSUB.
8208     if (N0.getOpcode() == ISD::FP_EXTEND) {
8209       SDValue N00 = N0.getOperand(0);
8210       if (N00.getOpcode() == ISD::FNEG) {
8211         SDValue N000 = N00.getOperand(0);
8212         if (N000.getOpcode() == ISD::FMUL) {
8213           return DAG.getNode(ISD::FNEG, SL, VT,
8214                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8215                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8216                                                      N000.getOperand(0)),
8217                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8218                                                      N000.getOperand(1)),
8219                                          N1));
8220         }
8221       }
8222     }
8223 
8224     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8225     //   -> (fneg (fma (fpext x)), (fpext y), z)
8226     // Note: This could be removed with appropriate canonicalization of the
8227     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8228     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8229     // from implementing the canonicalization in visitFSUB.
8230     if (N0.getOpcode() == ISD::FNEG) {
8231       SDValue N00 = N0.getOperand(0);
8232       if (N00.getOpcode() == ISD::FP_EXTEND) {
8233         SDValue N000 = N00.getOperand(0);
8234         if (N000.getOpcode() == ISD::FMUL) {
8235           return DAG.getNode(ISD::FNEG, SL, VT,
8236                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8237                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8238                                                      N000.getOperand(0)),
8239                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8240                                                      N000.getOperand(1)),
8241                                          N1));
8242         }
8243       }
8244     }
8245 
8246   }
8247 
8248   // More folding opportunities when target permits.
8249   if ((AllowFusion || HasFMAD) && Aggressive) {
8250     // fold (fsub (fma x, y, (fmul u, v)), z)
8251     //   -> (fma x, y (fma u, v, (fneg z)))
8252     if (N0.getOpcode() == PreferredFusedOpcode &&
8253         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8254       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8255                          N0.getOperand(0), N0.getOperand(1),
8256                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8257                                      N0.getOperand(2).getOperand(0),
8258                                      N0.getOperand(2).getOperand(1),
8259                                      DAG.getNode(ISD::FNEG, SL, VT,
8260                                                  N1)));
8261     }
8262 
8263     // fold (fsub x, (fma y, z, (fmul u, v)))
8264     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8265     if (N1.getOpcode() == PreferredFusedOpcode &&
8266         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8267       SDValue N20 = N1.getOperand(2).getOperand(0);
8268       SDValue N21 = N1.getOperand(2).getOperand(1);
8269       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8270                          DAG.getNode(ISD::FNEG, SL, VT,
8271                                      N1.getOperand(0)),
8272                          N1.getOperand(1),
8273                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8274                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8275 
8276                                      N21, N0));
8277     }
8278 
8279     if (AllowFusion && LookThroughFPExt) {
8280       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8281       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8282       if (N0.getOpcode() == PreferredFusedOpcode) {
8283         SDValue N02 = N0.getOperand(2);
8284         if (N02.getOpcode() == ISD::FP_EXTEND) {
8285           SDValue N020 = N02.getOperand(0);
8286           if (N020.getOpcode() == ISD::FMUL)
8287             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8288                                N0.getOperand(0), N0.getOperand(1),
8289                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8290                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8291                                                        N020.getOperand(0)),
8292                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8293                                                        N020.getOperand(1)),
8294                                            DAG.getNode(ISD::FNEG, SL, VT,
8295                                                        N1)));
8296         }
8297       }
8298 
8299       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8300       //   -> (fma (fpext x), (fpext y),
8301       //           (fma (fpext u), (fpext v), (fneg z)))
8302       // FIXME: This turns two single-precision and one double-precision
8303       // operation into two double-precision operations, which might not be
8304       // interesting for all targets, especially GPUs.
8305       if (N0.getOpcode() == ISD::FP_EXTEND) {
8306         SDValue N00 = N0.getOperand(0);
8307         if (N00.getOpcode() == PreferredFusedOpcode) {
8308           SDValue N002 = N00.getOperand(2);
8309           if (N002.getOpcode() == ISD::FMUL)
8310             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8311                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8312                                            N00.getOperand(0)),
8313                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8314                                            N00.getOperand(1)),
8315                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8316                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8317                                                        N002.getOperand(0)),
8318                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8319                                                        N002.getOperand(1)),
8320                                            DAG.getNode(ISD::FNEG, SL, VT,
8321                                                        N1)));
8322         }
8323       }
8324 
8325       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8326       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8327       if (N1.getOpcode() == PreferredFusedOpcode &&
8328         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8329         SDValue N120 = N1.getOperand(2).getOperand(0);
8330         if (N120.getOpcode() == ISD::FMUL) {
8331           SDValue N1200 = N120.getOperand(0);
8332           SDValue N1201 = N120.getOperand(1);
8333           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8334                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8335                              N1.getOperand(1),
8336                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8337                                          DAG.getNode(ISD::FNEG, SL, VT,
8338                                              DAG.getNode(ISD::FP_EXTEND, SL,
8339                                                          VT, N1200)),
8340                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8341                                                      N1201),
8342                                          N0));
8343         }
8344       }
8345 
8346       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8347       //   -> (fma (fneg (fpext y)), (fpext z),
8348       //           (fma (fneg (fpext u)), (fpext v), x))
8349       // FIXME: This turns two single-precision and one double-precision
8350       // operation into two double-precision operations, which might not be
8351       // interesting for all targets, especially GPUs.
8352       if (N1.getOpcode() == ISD::FP_EXTEND &&
8353         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8354         SDValue N100 = N1.getOperand(0).getOperand(0);
8355         SDValue N101 = N1.getOperand(0).getOperand(1);
8356         SDValue N102 = N1.getOperand(0).getOperand(2);
8357         if (N102.getOpcode() == ISD::FMUL) {
8358           SDValue N1020 = N102.getOperand(0);
8359           SDValue N1021 = N102.getOperand(1);
8360           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8361                              DAG.getNode(ISD::FNEG, SL, VT,
8362                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8363                                                      N100)),
8364                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8365                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8366                                          DAG.getNode(ISD::FNEG, SL, VT,
8367                                              DAG.getNode(ISD::FP_EXTEND, SL,
8368                                                          VT, N1020)),
8369                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8370                                                      N1021),
8371                                          N0));
8372         }
8373       }
8374     }
8375   }
8376 
8377   return SDValue();
8378 }
8379 
8380 /// Try to perform FMA combining on a given FMUL node.
8381 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8382   SDValue N0 = N->getOperand(0);
8383   SDValue N1 = N->getOperand(1);
8384   EVT VT = N->getValueType(0);
8385   SDLoc SL(N);
8386 
8387   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8388 
8389   const TargetOptions &Options = DAG.getTarget().Options;
8390   bool AllowFusion =
8391       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8392 
8393   // Floating-point multiply-add with intermediate rounding.
8394   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8395 
8396   // Floating-point multiply-add without intermediate rounding.
8397   bool HasFMA =
8398       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8399       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8400 
8401   // No valid opcode, do not combine.
8402   if (!HasFMAD && !HasFMA)
8403     return SDValue();
8404 
8405   // Always prefer FMAD to FMA for precision.
8406   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8407   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8408 
8409   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8410   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8411   auto FuseFADD = [&](SDValue X, SDValue Y) {
8412     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8413       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8414       if (XC1 && XC1->isExactlyValue(+1.0))
8415         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8416       if (XC1 && XC1->isExactlyValue(-1.0))
8417         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8418                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8419     }
8420     return SDValue();
8421   };
8422 
8423   if (SDValue FMA = FuseFADD(N0, N1))
8424     return FMA;
8425   if (SDValue FMA = FuseFADD(N1, N0))
8426     return FMA;
8427 
8428   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8429   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8430   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8431   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8432   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8433     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8434       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8435       if (XC0 && XC0->isExactlyValue(+1.0))
8436         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8437                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8438                            Y);
8439       if (XC0 && XC0->isExactlyValue(-1.0))
8440         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8441                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8442                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8443 
8444       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8445       if (XC1 && XC1->isExactlyValue(+1.0))
8446         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8447                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8448       if (XC1 && XC1->isExactlyValue(-1.0))
8449         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8450     }
8451     return SDValue();
8452   };
8453 
8454   if (SDValue FMA = FuseFSUB(N0, N1))
8455     return FMA;
8456   if (SDValue FMA = FuseFSUB(N1, N0))
8457     return FMA;
8458 
8459   return SDValue();
8460 }
8461 
8462 SDValue DAGCombiner::visitFADD(SDNode *N) {
8463   SDValue N0 = N->getOperand(0);
8464   SDValue N1 = N->getOperand(1);
8465   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8466   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8467   EVT VT = N->getValueType(0);
8468   SDLoc DL(N);
8469   const TargetOptions &Options = DAG.getTarget().Options;
8470   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8471 
8472   // fold vector ops
8473   if (VT.isVector())
8474     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8475       return FoldedVOp;
8476 
8477   // fold (fadd c1, c2) -> c1 + c2
8478   if (N0CFP && N1CFP)
8479     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8480 
8481   // canonicalize constant to RHS
8482   if (N0CFP && !N1CFP)
8483     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8484 
8485   // fold (fadd A, (fneg B)) -> (fsub A, B)
8486   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8487       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8488     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8489                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8490 
8491   // fold (fadd (fneg A), B) -> (fsub B, A)
8492   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8493       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8494     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8495                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8496 
8497   // FIXME: Auto-upgrade the target/function-level option.
8498   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8499     // fold (fadd A, 0) -> A
8500     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8501       if (N1C->isZero())
8502         return N0;
8503   }
8504 
8505   // If 'unsafe math' is enabled, fold lots of things.
8506   if (Options.UnsafeFPMath) {
8507     // No FP constant should be created after legalization as Instruction
8508     // Selection pass has a hard time dealing with FP constants.
8509     bool AllowNewConst = (Level < AfterLegalizeDAG);
8510 
8511     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8512     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8513         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8514       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8515                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8516                                      Flags),
8517                          Flags);
8518 
8519     // If allowed, fold (fadd (fneg x), x) -> 0.0
8520     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8521       return DAG.getConstantFP(0.0, DL, VT);
8522 
8523     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8524     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8525       return DAG.getConstantFP(0.0, DL, VT);
8526 
8527     // We can fold chains of FADD's of the same value into multiplications.
8528     // This transform is not safe in general because we are reducing the number
8529     // of rounding steps.
8530     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8531       if (N0.getOpcode() == ISD::FMUL) {
8532         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8533         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8534 
8535         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8536         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8537           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8538                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8539           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8540         }
8541 
8542         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8543         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8544             N1.getOperand(0) == N1.getOperand(1) &&
8545             N0.getOperand(0) == N1.getOperand(0)) {
8546           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8547                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8548           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8549         }
8550       }
8551 
8552       if (N1.getOpcode() == ISD::FMUL) {
8553         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8554         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8555 
8556         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8557         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8558           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8559                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8560           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8561         }
8562 
8563         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8564         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8565             N0.getOperand(0) == N0.getOperand(1) &&
8566             N1.getOperand(0) == N0.getOperand(0)) {
8567           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8568                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8569           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8570         }
8571       }
8572 
8573       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8574         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8575         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8576         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8577             (N0.getOperand(0) == N1)) {
8578           return DAG.getNode(ISD::FMUL, DL, VT,
8579                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8580         }
8581       }
8582 
8583       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8584         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8585         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8586         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8587             N1.getOperand(0) == N0) {
8588           return DAG.getNode(ISD::FMUL, DL, VT,
8589                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8590         }
8591       }
8592 
8593       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8594       if (AllowNewConst &&
8595           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8596           N0.getOperand(0) == N0.getOperand(1) &&
8597           N1.getOperand(0) == N1.getOperand(1) &&
8598           N0.getOperand(0) == N1.getOperand(0)) {
8599         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8600                            DAG.getConstantFP(4.0, DL, VT), Flags);
8601       }
8602     }
8603   } // enable-unsafe-fp-math
8604 
8605   // FADD -> FMA combines:
8606   if (SDValue Fused = visitFADDForFMACombine(N)) {
8607     AddToWorklist(Fused.getNode());
8608     return Fused;
8609   }
8610   return SDValue();
8611 }
8612 
8613 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8614   SDValue N0 = N->getOperand(0);
8615   SDValue N1 = N->getOperand(1);
8616   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8617   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8618   EVT VT = N->getValueType(0);
8619   SDLoc DL(N);
8620   const TargetOptions &Options = DAG.getTarget().Options;
8621   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8622 
8623   // fold vector ops
8624   if (VT.isVector())
8625     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8626       return FoldedVOp;
8627 
8628   // fold (fsub c1, c2) -> c1-c2
8629   if (N0CFP && N1CFP)
8630     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
8631 
8632   // fold (fsub A, (fneg B)) -> (fadd A, B)
8633   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8634     return DAG.getNode(ISD::FADD, DL, VT, N0,
8635                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8636 
8637   // FIXME: Auto-upgrade the target/function-level option.
8638   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8639     // (fsub 0, B) -> -B
8640     if (N0CFP && N0CFP->isZero()) {
8641       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8642         return GetNegatedExpression(N1, DAG, LegalOperations);
8643       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8644         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
8645     }
8646   }
8647 
8648   // If 'unsafe math' is enabled, fold lots of things.
8649   if (Options.UnsafeFPMath) {
8650     // (fsub A, 0) -> A
8651     if (N1CFP && N1CFP->isZero())
8652       return N0;
8653 
8654     // (fsub x, x) -> 0.0
8655     if (N0 == N1)
8656       return DAG.getConstantFP(0.0f, DL, VT);
8657 
8658     // (fsub x, (fadd x, y)) -> (fneg y)
8659     // (fsub x, (fadd y, x)) -> (fneg y)
8660     if (N1.getOpcode() == ISD::FADD) {
8661       SDValue N10 = N1->getOperand(0);
8662       SDValue N11 = N1->getOperand(1);
8663 
8664       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8665         return GetNegatedExpression(N11, DAG, LegalOperations);
8666 
8667       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8668         return GetNegatedExpression(N10, DAG, LegalOperations);
8669     }
8670   }
8671 
8672   // FSUB -> FMA combines:
8673   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8674     AddToWorklist(Fused.getNode());
8675     return Fused;
8676   }
8677 
8678   return SDValue();
8679 }
8680 
8681 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8682   SDValue N0 = N->getOperand(0);
8683   SDValue N1 = N->getOperand(1);
8684   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8685   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8686   EVT VT = N->getValueType(0);
8687   SDLoc DL(N);
8688   const TargetOptions &Options = DAG.getTarget().Options;
8689   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8690 
8691   // fold vector ops
8692   if (VT.isVector()) {
8693     // This just handles C1 * C2 for vectors. Other vector folds are below.
8694     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8695       return FoldedVOp;
8696   }
8697 
8698   // fold (fmul c1, c2) -> c1*c2
8699   if (N0CFP && N1CFP)
8700     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8701 
8702   // canonicalize constant to RHS
8703   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8704      !isConstantFPBuildVectorOrConstantFP(N1))
8705     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8706 
8707   // fold (fmul A, 1.0) -> A
8708   if (N1CFP && N1CFP->isExactlyValue(1.0))
8709     return N0;
8710 
8711   if (Options.UnsafeFPMath) {
8712     // fold (fmul A, 0) -> 0
8713     if (N1CFP && N1CFP->isZero())
8714       return N1;
8715 
8716     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8717     if (N0.getOpcode() == ISD::FMUL) {
8718       // Fold scalars or any vector constants (not just splats).
8719       // This fold is done in general by InstCombine, but extra fmul insts
8720       // may have been generated during lowering.
8721       SDValue N00 = N0.getOperand(0);
8722       SDValue N01 = N0.getOperand(1);
8723       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8724       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8725       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8726 
8727       // Check 1: Make sure that the first operand of the inner multiply is NOT
8728       // a constant. Otherwise, we may induce infinite looping.
8729       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8730         // Check 2: Make sure that the second operand of the inner multiply and
8731         // the second operand of the outer multiply are constants.
8732         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8733             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8734           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8735           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8736         }
8737       }
8738     }
8739 
8740     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8741     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8742     // during an early run of DAGCombiner can prevent folding with fmuls
8743     // inserted during lowering.
8744     if (N0.getOpcode() == ISD::FADD &&
8745         (N0.getOperand(0) == N0.getOperand(1)) &&
8746         N0.hasOneUse()) {
8747       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8748       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8749       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8750     }
8751   }
8752 
8753   // fold (fmul X, 2.0) -> (fadd X, X)
8754   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8755     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8756 
8757   // fold (fmul X, -1.0) -> (fneg X)
8758   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8759     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8760       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8761 
8762   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8763   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8764     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8765       // Both can be negated for free, check to see if at least one is cheaper
8766       // negated.
8767       if (LHSNeg == 2 || RHSNeg == 2)
8768         return DAG.getNode(ISD::FMUL, DL, VT,
8769                            GetNegatedExpression(N0, DAG, LegalOperations),
8770                            GetNegatedExpression(N1, DAG, LegalOperations),
8771                            Flags);
8772     }
8773   }
8774 
8775   // FMUL -> FMA combines:
8776   if (SDValue Fused = visitFMULForFMACombine(N)) {
8777     AddToWorklist(Fused.getNode());
8778     return Fused;
8779   }
8780 
8781   return SDValue();
8782 }
8783 
8784 SDValue DAGCombiner::visitFMA(SDNode *N) {
8785   SDValue N0 = N->getOperand(0);
8786   SDValue N1 = N->getOperand(1);
8787   SDValue N2 = N->getOperand(2);
8788   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8789   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8790   EVT VT = N->getValueType(0);
8791   SDLoc DL(N);
8792   const TargetOptions &Options = DAG.getTarget().Options;
8793 
8794   // Constant fold FMA.
8795   if (isa<ConstantFPSDNode>(N0) &&
8796       isa<ConstantFPSDNode>(N1) &&
8797       isa<ConstantFPSDNode>(N2)) {
8798     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
8799   }
8800 
8801   if (Options.UnsafeFPMath) {
8802     if (N0CFP && N0CFP->isZero())
8803       return N2;
8804     if (N1CFP && N1CFP->isZero())
8805       return N2;
8806   }
8807   // TODO: The FMA node should have flags that propagate to these nodes.
8808   if (N0CFP && N0CFP->isExactlyValue(1.0))
8809     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8810   if (N1CFP && N1CFP->isExactlyValue(1.0))
8811     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8812 
8813   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8814   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8815      !isConstantFPBuildVectorOrConstantFP(N1))
8816     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8817 
8818   // TODO: FMA nodes should have flags that propagate to the created nodes.
8819   // For now, create a Flags object for use with all unsafe math transforms.
8820   SDNodeFlags Flags;
8821   Flags.setUnsafeAlgebra(true);
8822 
8823   if (Options.UnsafeFPMath) {
8824     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8825     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8826         isConstantFPBuildVectorOrConstantFP(N1) &&
8827         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8828       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8829                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
8830                                      &Flags), &Flags);
8831     }
8832 
8833     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8834     if (N0.getOpcode() == ISD::FMUL &&
8835         isConstantFPBuildVectorOrConstantFP(N1) &&
8836         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8837       return DAG.getNode(ISD::FMA, DL, VT,
8838                          N0.getOperand(0),
8839                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
8840                                      &Flags),
8841                          N2);
8842     }
8843   }
8844 
8845   // (fma x, 1, y) -> (fadd x, y)
8846   // (fma x, -1, y) -> (fadd (fneg x), y)
8847   if (N1CFP) {
8848     if (N1CFP->isExactlyValue(1.0))
8849       // TODO: The FMA node should have flags that propagate to this node.
8850       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
8851 
8852     if (N1CFP->isExactlyValue(-1.0) &&
8853         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8854       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
8855       AddToWorklist(RHSNeg.getNode());
8856       // TODO: The FMA node should have flags that propagate to this node.
8857       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
8858     }
8859   }
8860 
8861   if (Options.UnsafeFPMath) {
8862     // (fma x, c, x) -> (fmul x, (c+1))
8863     if (N1CFP && N0 == N2) {
8864       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8865                          DAG.getNode(ISD::FADD, DL, VT, N1,
8866                                      DAG.getConstantFP(1.0, DL, VT), &Flags),
8867                          &Flags);
8868     }
8869 
8870     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8871     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8872       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8873                          DAG.getNode(ISD::FADD, DL, VT, N1,
8874                                      DAG.getConstantFP(-1.0, DL, VT), &Flags),
8875                          &Flags);
8876     }
8877   }
8878 
8879   return SDValue();
8880 }
8881 
8882 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8883 // reciprocal.
8884 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8885 // Notice that this is not always beneficial. One reason is different target
8886 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8887 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8888 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8889 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8890   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8891   const SDNodeFlags *Flags = N->getFlags();
8892   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8893     return SDValue();
8894 
8895   // Skip if current node is a reciprocal.
8896   SDValue N0 = N->getOperand(0);
8897   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8898   if (N0CFP && N0CFP->isExactlyValue(1.0))
8899     return SDValue();
8900 
8901   // Exit early if the target does not want this transform or if there can't
8902   // possibly be enough uses of the divisor to make the transform worthwhile.
8903   SDValue N1 = N->getOperand(1);
8904   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8905   if (!MinUses || N1->use_size() < MinUses)
8906     return SDValue();
8907 
8908   // Find all FDIV users of the same divisor.
8909   // Use a set because duplicates may be present in the user list.
8910   SetVector<SDNode *> Users;
8911   for (auto *U : N1->uses()) {
8912     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8913       // This division is eligible for optimization only if global unsafe math
8914       // is enabled or if this division allows reciprocal formation.
8915       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8916         Users.insert(U);
8917     }
8918   }
8919 
8920   // Now that we have the actual number of divisor uses, make sure it meets
8921   // the minimum threshold specified by the target.
8922   if (Users.size() < MinUses)
8923     return SDValue();
8924 
8925   EVT VT = N->getValueType(0);
8926   SDLoc DL(N);
8927   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8928   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8929 
8930   // Dividend / Divisor -> Dividend * Reciprocal
8931   for (auto *U : Users) {
8932     SDValue Dividend = U->getOperand(0);
8933     if (Dividend != FPOne) {
8934       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8935                                     Reciprocal, Flags);
8936       CombineTo(U, NewNode);
8937     } else if (U != Reciprocal.getNode()) {
8938       // In the absence of fast-math-flags, this user node is always the
8939       // same node as Reciprocal, but with FMF they may be different nodes.
8940       CombineTo(U, Reciprocal);
8941     }
8942   }
8943   return SDValue(N, 0);  // N was replaced.
8944 }
8945 
8946 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8947   SDValue N0 = N->getOperand(0);
8948   SDValue N1 = N->getOperand(1);
8949   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8950   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8951   EVT VT = N->getValueType(0);
8952   SDLoc DL(N);
8953   const TargetOptions &Options = DAG.getTarget().Options;
8954   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8955 
8956   // fold vector ops
8957   if (VT.isVector())
8958     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8959       return FoldedVOp;
8960 
8961   // fold (fdiv c1, c2) -> c1/c2
8962   if (N0CFP && N1CFP)
8963     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8964 
8965   if (Options.UnsafeFPMath) {
8966     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8967     if (N1CFP) {
8968       // Compute the reciprocal 1.0 / c2.
8969       const APFloat &N1APF = N1CFP->getValueAPF();
8970       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8971       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8972       // Only do the transform if the reciprocal is a legal fp immediate that
8973       // isn't too nasty (eg NaN, denormal, ...).
8974       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8975           (!LegalOperations ||
8976            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8977            // backend)... we should handle this gracefully after Legalize.
8978            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8979            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8980            TLI.isFPImmLegal(Recip, VT)))
8981         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8982                            DAG.getConstantFP(Recip, DL, VT), Flags);
8983     }
8984 
8985     // If this FDIV is part of a reciprocal square root, it may be folded
8986     // into a target-specific square root estimate instruction.
8987     if (N1.getOpcode() == ISD::FSQRT) {
8988       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
8989         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8990       }
8991     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8992                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8993       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8994                                           Flags)) {
8995         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8996         AddToWorklist(RV.getNode());
8997         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8998       }
8999     } else if (N1.getOpcode() == ISD::FP_ROUND &&
9000                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9001       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9002                                           Flags)) {
9003         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9004         AddToWorklist(RV.getNode());
9005         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9006       }
9007     } else if (N1.getOpcode() == ISD::FMUL) {
9008       // Look through an FMUL. Even though this won't remove the FDIV directly,
9009       // it's still worthwhile to get rid of the FSQRT if possible.
9010       SDValue SqrtOp;
9011       SDValue OtherOp;
9012       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9013         SqrtOp = N1.getOperand(0);
9014         OtherOp = N1.getOperand(1);
9015       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9016         SqrtOp = N1.getOperand(1);
9017         OtherOp = N1.getOperand(0);
9018       }
9019       if (SqrtOp.getNode()) {
9020         // We found a FSQRT, so try to make this fold:
9021         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9022         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9023           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9024           AddToWorklist(RV.getNode());
9025           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9026         }
9027       }
9028     }
9029 
9030     // Fold into a reciprocal estimate and multiply instead of a real divide.
9031     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9032       AddToWorklist(RV.getNode());
9033       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9034     }
9035   }
9036 
9037   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9038   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9039     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9040       // Both can be negated for free, check to see if at least one is cheaper
9041       // negated.
9042       if (LHSNeg == 2 || RHSNeg == 2)
9043         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9044                            GetNegatedExpression(N0, DAG, LegalOperations),
9045                            GetNegatedExpression(N1, DAG, LegalOperations),
9046                            Flags);
9047     }
9048   }
9049 
9050   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9051     return CombineRepeatedDivisors;
9052 
9053   return SDValue();
9054 }
9055 
9056 SDValue DAGCombiner::visitFREM(SDNode *N) {
9057   SDValue N0 = N->getOperand(0);
9058   SDValue N1 = N->getOperand(1);
9059   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9060   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9061   EVT VT = N->getValueType(0);
9062 
9063   // fold (frem c1, c2) -> fmod(c1,c2)
9064   if (N0CFP && N1CFP)
9065     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9066                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
9067 
9068   return SDValue();
9069 }
9070 
9071 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9072   if (!DAG.getTarget().Options.UnsafeFPMath)
9073     return SDValue();
9074 
9075   SDValue N0 = N->getOperand(0);
9076   if (TLI.isFsqrtCheap(N0, DAG))
9077     return SDValue();
9078 
9079   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9080   // For now, create a Flags object for use with all unsafe math transforms.
9081   SDNodeFlags Flags;
9082   Flags.setUnsafeAlgebra(true);
9083   return buildSqrtEstimate(N0, &Flags);
9084 }
9085 
9086 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9087 /// copysign(x, fp_round(y)) -> copysign(x, y)
9088 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9089   SDValue N1 = N->getOperand(1);
9090   if ((N1.getOpcode() == ISD::FP_EXTEND ||
9091        N1.getOpcode() == ISD::FP_ROUND)) {
9092     // Do not optimize out type conversion of f128 type yet.
9093     // For some targets like x86_64, configuration is changed to keep one f128
9094     // value in one SSE register, but instruction selection cannot handle
9095     // FCOPYSIGN on SSE registers yet.
9096     EVT N1VT = N1->getValueType(0);
9097     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9098     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9099   }
9100   return false;
9101 }
9102 
9103 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9104   SDValue N0 = N->getOperand(0);
9105   SDValue N1 = N->getOperand(1);
9106   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9107   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9108   EVT VT = N->getValueType(0);
9109 
9110   if (N0CFP && N1CFP) // Constant fold
9111     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9112 
9113   if (N1CFP) {
9114     const APFloat &V = N1CFP->getValueAPF();
9115     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
9116     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9117     if (!V.isNegative()) {
9118       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9119         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9120     } else {
9121       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9122         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9123                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9124     }
9125   }
9126 
9127   // copysign(fabs(x), y) -> copysign(x, y)
9128   // copysign(fneg(x), y) -> copysign(x, y)
9129   // copysign(copysign(x,z), y) -> copysign(x, y)
9130   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9131       N0.getOpcode() == ISD::FCOPYSIGN)
9132     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9133 
9134   // copysign(x, abs(y)) -> abs(x)
9135   if (N1.getOpcode() == ISD::FABS)
9136     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9137 
9138   // copysign(x, copysign(y,z)) -> copysign(x, z)
9139   if (N1.getOpcode() == ISD::FCOPYSIGN)
9140     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9141 
9142   // copysign(x, fp_extend(y)) -> copysign(x, y)
9143   // copysign(x, fp_round(y)) -> copysign(x, y)
9144   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9145     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9146 
9147   return SDValue();
9148 }
9149 
9150 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9151   SDValue N0 = N->getOperand(0);
9152   EVT VT = N->getValueType(0);
9153   EVT OpVT = N0.getValueType();
9154 
9155   // fold (sint_to_fp c1) -> c1fp
9156   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9157       // ...but only if the target supports immediate floating-point values
9158       (!LegalOperations ||
9159        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9160     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9161 
9162   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9163   // but UINT_TO_FP is legal on this target, try to convert.
9164   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9165       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9166     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9167     if (DAG.SignBitIsZero(N0))
9168       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9169   }
9170 
9171   // The next optimizations are desirable only if SELECT_CC can be lowered.
9172   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9173     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9174     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9175         !VT.isVector() &&
9176         (!LegalOperations ||
9177          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9178       SDLoc DL(N);
9179       SDValue Ops[] =
9180         { N0.getOperand(0), N0.getOperand(1),
9181           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9182           N0.getOperand(2) };
9183       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9184     }
9185 
9186     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9187     //      (select_cc x, y, 1.0, 0.0,, cc)
9188     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9189         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9190         (!LegalOperations ||
9191          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9192       SDLoc DL(N);
9193       SDValue Ops[] =
9194         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9195           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9196           N0.getOperand(0).getOperand(2) };
9197       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9198     }
9199   }
9200 
9201   return SDValue();
9202 }
9203 
9204 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9205   SDValue N0 = N->getOperand(0);
9206   EVT VT = N->getValueType(0);
9207   EVT OpVT = N0.getValueType();
9208 
9209   // fold (uint_to_fp c1) -> c1fp
9210   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9211       // ...but only if the target supports immediate floating-point values
9212       (!LegalOperations ||
9213        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9214     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9215 
9216   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9217   // but SINT_TO_FP is legal on this target, try to convert.
9218   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9219       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9220     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9221     if (DAG.SignBitIsZero(N0))
9222       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9223   }
9224 
9225   // The next optimizations are desirable only if SELECT_CC can be lowered.
9226   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9227     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9228 
9229     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9230         (!LegalOperations ||
9231          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9232       SDLoc DL(N);
9233       SDValue Ops[] =
9234         { N0.getOperand(0), N0.getOperand(1),
9235           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9236           N0.getOperand(2) };
9237       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9238     }
9239   }
9240 
9241   return SDValue();
9242 }
9243 
9244 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9245 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9246   SDValue N0 = N->getOperand(0);
9247   EVT VT = N->getValueType(0);
9248 
9249   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9250     return SDValue();
9251 
9252   SDValue Src = N0.getOperand(0);
9253   EVT SrcVT = Src.getValueType();
9254   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9255   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9256 
9257   // We can safely assume the conversion won't overflow the output range,
9258   // because (for example) (uint8_t)18293.f is undefined behavior.
9259 
9260   // Since we can assume the conversion won't overflow, our decision as to
9261   // whether the input will fit in the float should depend on the minimum
9262   // of the input range and output range.
9263 
9264   // This means this is also safe for a signed input and unsigned output, since
9265   // a negative input would lead to undefined behavior.
9266   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9267   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9268   unsigned ActualSize = std::min(InputSize, OutputSize);
9269   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9270 
9271   // We can only fold away the float conversion if the input range can be
9272   // represented exactly in the float range.
9273   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9274     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9275       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9276                                                        : ISD::ZERO_EXTEND;
9277       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9278     }
9279     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9280       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9281     return DAG.getBitcast(VT, Src);
9282   }
9283   return SDValue();
9284 }
9285 
9286 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9287   SDValue N0 = N->getOperand(0);
9288   EVT VT = N->getValueType(0);
9289 
9290   // fold (fp_to_sint c1fp) -> c1
9291   if (isConstantFPBuildVectorOrConstantFP(N0))
9292     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9293 
9294   return FoldIntToFPToInt(N, DAG);
9295 }
9296 
9297 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9298   SDValue N0 = N->getOperand(0);
9299   EVT VT = N->getValueType(0);
9300 
9301   // fold (fp_to_uint c1fp) -> c1
9302   if (isConstantFPBuildVectorOrConstantFP(N0))
9303     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9304 
9305   return FoldIntToFPToInt(N, DAG);
9306 }
9307 
9308 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9309   SDValue N0 = N->getOperand(0);
9310   SDValue N1 = N->getOperand(1);
9311   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9312   EVT VT = N->getValueType(0);
9313 
9314   // fold (fp_round c1fp) -> c1fp
9315   if (N0CFP)
9316     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9317 
9318   // fold (fp_round (fp_extend x)) -> x
9319   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9320     return N0.getOperand(0);
9321 
9322   // fold (fp_round (fp_round x)) -> (fp_round x)
9323   if (N0.getOpcode() == ISD::FP_ROUND) {
9324     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9325     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9326 
9327     // Skip this folding if it results in an fp_round from f80 to f16.
9328     //
9329     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9330     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9331     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9332     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9333     // x86.
9334     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9335       return SDValue();
9336 
9337     // If the first fp_round isn't a value preserving truncation, it might
9338     // introduce a tie in the second fp_round, that wouldn't occur in the
9339     // single-step fp_round we want to fold to.
9340     // In other words, double rounding isn't the same as rounding.
9341     // Also, this is a value preserving truncation iff both fp_round's are.
9342     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9343       SDLoc DL(N);
9344       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9345                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9346     }
9347   }
9348 
9349   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9350   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9351     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9352                               N0.getOperand(0), N1);
9353     AddToWorklist(Tmp.getNode());
9354     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9355                        Tmp, N0.getOperand(1));
9356   }
9357 
9358   return SDValue();
9359 }
9360 
9361 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9362   SDValue N0 = N->getOperand(0);
9363   EVT VT = N->getValueType(0);
9364   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9365   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9366 
9367   // fold (fp_round_inreg c1fp) -> c1fp
9368   if (N0CFP && isTypeLegal(EVT)) {
9369     SDLoc DL(N);
9370     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9371     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9372   }
9373 
9374   return SDValue();
9375 }
9376 
9377 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9378   SDValue N0 = N->getOperand(0);
9379   EVT VT = N->getValueType(0);
9380 
9381   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9382   if (N->hasOneUse() &&
9383       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9384     return SDValue();
9385 
9386   // fold (fp_extend c1fp) -> c1fp
9387   if (isConstantFPBuildVectorOrConstantFP(N0))
9388     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9389 
9390   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9391   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9392       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9393     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9394 
9395   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9396   // value of X.
9397   if (N0.getOpcode() == ISD::FP_ROUND
9398       && N0.getNode()->getConstantOperandVal(1) == 1) {
9399     SDValue In = N0.getOperand(0);
9400     if (In.getValueType() == VT) return In;
9401     if (VT.bitsLT(In.getValueType()))
9402       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9403                          In, N0.getOperand(1));
9404     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9405   }
9406 
9407   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9408   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9409        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9410     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9411     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9412                                      LN0->getChain(),
9413                                      LN0->getBasePtr(), N0.getValueType(),
9414                                      LN0->getMemOperand());
9415     CombineTo(N, ExtLoad);
9416     CombineTo(N0.getNode(),
9417               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9418                           N0.getValueType(), ExtLoad,
9419                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9420               ExtLoad.getValue(1));
9421     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9422   }
9423 
9424   return SDValue();
9425 }
9426 
9427 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9428   SDValue N0 = N->getOperand(0);
9429   EVT VT = N->getValueType(0);
9430 
9431   // fold (fceil c1) -> fceil(c1)
9432   if (isConstantFPBuildVectorOrConstantFP(N0))
9433     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9434 
9435   return SDValue();
9436 }
9437 
9438 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9439   SDValue N0 = N->getOperand(0);
9440   EVT VT = N->getValueType(0);
9441 
9442   // fold (ftrunc c1) -> ftrunc(c1)
9443   if (isConstantFPBuildVectorOrConstantFP(N0))
9444     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9445 
9446   return SDValue();
9447 }
9448 
9449 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9450   SDValue N0 = N->getOperand(0);
9451   EVT VT = N->getValueType(0);
9452 
9453   // fold (ffloor c1) -> ffloor(c1)
9454   if (isConstantFPBuildVectorOrConstantFP(N0))
9455     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9456 
9457   return SDValue();
9458 }
9459 
9460 // FIXME: FNEG and FABS have a lot in common; refactor.
9461 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9462   SDValue N0 = N->getOperand(0);
9463   EVT VT = N->getValueType(0);
9464 
9465   // Constant fold FNEG.
9466   if (isConstantFPBuildVectorOrConstantFP(N0))
9467     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9468 
9469   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9470                          &DAG.getTarget().Options))
9471     return GetNegatedExpression(N0, DAG, LegalOperations);
9472 
9473   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9474   // constant pool values.
9475   if (!TLI.isFNegFree(VT) &&
9476       N0.getOpcode() == ISD::BITCAST &&
9477       N0.getNode()->hasOneUse()) {
9478     SDValue Int = N0.getOperand(0);
9479     EVT IntVT = Int.getValueType();
9480     if (IntVT.isInteger() && !IntVT.isVector()) {
9481       APInt SignMask;
9482       if (N0.getValueType().isVector()) {
9483         // For a vector, get a mask such as 0x80... per scalar element
9484         // and splat it.
9485         SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits());
9486         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9487       } else {
9488         // For a scalar, just generate 0x80...
9489         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9490       }
9491       SDLoc DL0(N0);
9492       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9493                         DAG.getConstant(SignMask, DL0, IntVT));
9494       AddToWorklist(Int.getNode());
9495       return DAG.getBitcast(VT, Int);
9496     }
9497   }
9498 
9499   // (fneg (fmul c, x)) -> (fmul -c, x)
9500   if (N0.getOpcode() == ISD::FMUL &&
9501       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9502     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9503     if (CFP1) {
9504       APFloat CVal = CFP1->getValueAPF();
9505       CVal.changeSign();
9506       if (Level >= AfterLegalizeDAG &&
9507           (TLI.isFPImmLegal(CVal, VT) ||
9508            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9509         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9510                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9511                                        N0.getOperand(1)),
9512                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9513     }
9514   }
9515 
9516   return SDValue();
9517 }
9518 
9519 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9520   SDValue N0 = N->getOperand(0);
9521   SDValue N1 = N->getOperand(1);
9522   EVT VT = N->getValueType(0);
9523   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9524   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9525 
9526   if (N0CFP && N1CFP) {
9527     const APFloat &C0 = N0CFP->getValueAPF();
9528     const APFloat &C1 = N1CFP->getValueAPF();
9529     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9530   }
9531 
9532   // Canonicalize to constant on RHS.
9533   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9534      !isConstantFPBuildVectorOrConstantFP(N1))
9535     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9536 
9537   return SDValue();
9538 }
9539 
9540 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9541   SDValue N0 = N->getOperand(0);
9542   SDValue N1 = N->getOperand(1);
9543   EVT VT = N->getValueType(0);
9544   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9545   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9546 
9547   if (N0CFP && N1CFP) {
9548     const APFloat &C0 = N0CFP->getValueAPF();
9549     const APFloat &C1 = N1CFP->getValueAPF();
9550     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9551   }
9552 
9553   // Canonicalize to constant on RHS.
9554   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9555      !isConstantFPBuildVectorOrConstantFP(N1))
9556     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9557 
9558   return SDValue();
9559 }
9560 
9561 SDValue DAGCombiner::visitFABS(SDNode *N) {
9562   SDValue N0 = N->getOperand(0);
9563   EVT VT = N->getValueType(0);
9564 
9565   // fold (fabs c1) -> fabs(c1)
9566   if (isConstantFPBuildVectorOrConstantFP(N0))
9567     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9568 
9569   // fold (fabs (fabs x)) -> (fabs x)
9570   if (N0.getOpcode() == ISD::FABS)
9571     return N->getOperand(0);
9572 
9573   // fold (fabs (fneg x)) -> (fabs x)
9574   // fold (fabs (fcopysign x, y)) -> (fabs x)
9575   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9576     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9577 
9578   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9579   // constant pool values.
9580   if (!TLI.isFAbsFree(VT) &&
9581       N0.getOpcode() == ISD::BITCAST &&
9582       N0.getNode()->hasOneUse()) {
9583     SDValue Int = N0.getOperand(0);
9584     EVT IntVT = Int.getValueType();
9585     if (IntVT.isInteger() && !IntVT.isVector()) {
9586       APInt SignMask;
9587       if (N0.getValueType().isVector()) {
9588         // For a vector, get a mask such as 0x7f... per scalar element
9589         // and splat it.
9590         SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits());
9591         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9592       } else {
9593         // For a scalar, just generate 0x7f...
9594         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9595       }
9596       SDLoc DL(N0);
9597       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9598                         DAG.getConstant(SignMask, DL, IntVT));
9599       AddToWorklist(Int.getNode());
9600       return DAG.getBitcast(N->getValueType(0), Int);
9601     }
9602   }
9603 
9604   return SDValue();
9605 }
9606 
9607 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9608   SDValue Chain = N->getOperand(0);
9609   SDValue N1 = N->getOperand(1);
9610   SDValue N2 = N->getOperand(2);
9611 
9612   // If N is a constant we could fold this into a fallthrough or unconditional
9613   // branch. However that doesn't happen very often in normal code, because
9614   // Instcombine/SimplifyCFG should have handled the available opportunities.
9615   // If we did this folding here, it would be necessary to update the
9616   // MachineBasicBlock CFG, which is awkward.
9617 
9618   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9619   // on the target.
9620   if (N1.getOpcode() == ISD::SETCC &&
9621       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9622                                    N1.getOperand(0).getValueType())) {
9623     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9624                        Chain, N1.getOperand(2),
9625                        N1.getOperand(0), N1.getOperand(1), N2);
9626   }
9627 
9628   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9629       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9630        (N1.getOperand(0).hasOneUse() &&
9631         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9632     SDNode *Trunc = nullptr;
9633     if (N1.getOpcode() == ISD::TRUNCATE) {
9634       // Look pass the truncate.
9635       Trunc = N1.getNode();
9636       N1 = N1.getOperand(0);
9637     }
9638 
9639     // Match this pattern so that we can generate simpler code:
9640     //
9641     //   %a = ...
9642     //   %b = and i32 %a, 2
9643     //   %c = srl i32 %b, 1
9644     //   brcond i32 %c ...
9645     //
9646     // into
9647     //
9648     //   %a = ...
9649     //   %b = and i32 %a, 2
9650     //   %c = setcc eq %b, 0
9651     //   brcond %c ...
9652     //
9653     // This applies only when the AND constant value has one bit set and the
9654     // SRL constant is equal to the log2 of the AND constant. The back-end is
9655     // smart enough to convert the result into a TEST/JMP sequence.
9656     SDValue Op0 = N1.getOperand(0);
9657     SDValue Op1 = N1.getOperand(1);
9658 
9659     if (Op0.getOpcode() == ISD::AND &&
9660         Op1.getOpcode() == ISD::Constant) {
9661       SDValue AndOp1 = Op0.getOperand(1);
9662 
9663       if (AndOp1.getOpcode() == ISD::Constant) {
9664         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9665 
9666         if (AndConst.isPowerOf2() &&
9667             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9668           SDLoc DL(N);
9669           SDValue SetCC =
9670             DAG.getSetCC(DL,
9671                          getSetCCResultType(Op0.getValueType()),
9672                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9673                          ISD::SETNE);
9674 
9675           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9676                                           MVT::Other, Chain, SetCC, N2);
9677           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9678           // will convert it back to (X & C1) >> C2.
9679           CombineTo(N, NewBRCond, false);
9680           // Truncate is dead.
9681           if (Trunc)
9682             deleteAndRecombine(Trunc);
9683           // Replace the uses of SRL with SETCC
9684           WorklistRemover DeadNodes(*this);
9685           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9686           deleteAndRecombine(N1.getNode());
9687           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9688         }
9689       }
9690     }
9691 
9692     if (Trunc)
9693       // Restore N1 if the above transformation doesn't match.
9694       N1 = N->getOperand(1);
9695   }
9696 
9697   // Transform br(xor(x, y)) -> br(x != y)
9698   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9699   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9700     SDNode *TheXor = N1.getNode();
9701     SDValue Op0 = TheXor->getOperand(0);
9702     SDValue Op1 = TheXor->getOperand(1);
9703     if (Op0.getOpcode() == Op1.getOpcode()) {
9704       // Avoid missing important xor optimizations.
9705       if (SDValue Tmp = visitXOR(TheXor)) {
9706         if (Tmp.getNode() != TheXor) {
9707           DEBUG(dbgs() << "\nReplacing.8 ";
9708                 TheXor->dump(&DAG);
9709                 dbgs() << "\nWith: ";
9710                 Tmp.getNode()->dump(&DAG);
9711                 dbgs() << '\n');
9712           WorklistRemover DeadNodes(*this);
9713           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9714           deleteAndRecombine(TheXor);
9715           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9716                              MVT::Other, Chain, Tmp, N2);
9717         }
9718 
9719         // visitXOR has changed XOR's operands or replaced the XOR completely,
9720         // bail out.
9721         return SDValue(N, 0);
9722       }
9723     }
9724 
9725     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9726       bool Equal = false;
9727       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9728           Op0.getOpcode() == ISD::XOR) {
9729         TheXor = Op0.getNode();
9730         Equal = true;
9731       }
9732 
9733       EVT SetCCVT = N1.getValueType();
9734       if (LegalTypes)
9735         SetCCVT = getSetCCResultType(SetCCVT);
9736       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9737                                    SetCCVT,
9738                                    Op0, Op1,
9739                                    Equal ? ISD::SETEQ : ISD::SETNE);
9740       // Replace the uses of XOR with SETCC
9741       WorklistRemover DeadNodes(*this);
9742       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9743       deleteAndRecombine(N1.getNode());
9744       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9745                          MVT::Other, Chain, SetCC, N2);
9746     }
9747   }
9748 
9749   return SDValue();
9750 }
9751 
9752 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9753 //
9754 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9755   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9756   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9757 
9758   // If N is a constant we could fold this into a fallthrough or unconditional
9759   // branch. However that doesn't happen very often in normal code, because
9760   // Instcombine/SimplifyCFG should have handled the available opportunities.
9761   // If we did this folding here, it would be necessary to update the
9762   // MachineBasicBlock CFG, which is awkward.
9763 
9764   // Use SimplifySetCC to simplify SETCC's.
9765   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9766                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9767                                false);
9768   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9769 
9770   // fold to a simpler setcc
9771   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9772     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9773                        N->getOperand(0), Simp.getOperand(2),
9774                        Simp.getOperand(0), Simp.getOperand(1),
9775                        N->getOperand(4));
9776 
9777   return SDValue();
9778 }
9779 
9780 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9781 /// and that N may be folded in the load / store addressing mode.
9782 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9783                                     SelectionDAG &DAG,
9784                                     const TargetLowering &TLI) {
9785   EVT VT;
9786   unsigned AS;
9787 
9788   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9789     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9790       return false;
9791     VT = LD->getMemoryVT();
9792     AS = LD->getAddressSpace();
9793   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9794     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9795       return false;
9796     VT = ST->getMemoryVT();
9797     AS = ST->getAddressSpace();
9798   } else
9799     return false;
9800 
9801   TargetLowering::AddrMode AM;
9802   if (N->getOpcode() == ISD::ADD) {
9803     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9804     if (Offset)
9805       // [reg +/- imm]
9806       AM.BaseOffs = Offset->getSExtValue();
9807     else
9808       // [reg +/- reg]
9809       AM.Scale = 1;
9810   } else if (N->getOpcode() == ISD::SUB) {
9811     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9812     if (Offset)
9813       // [reg +/- imm]
9814       AM.BaseOffs = -Offset->getSExtValue();
9815     else
9816       // [reg +/- reg]
9817       AM.Scale = 1;
9818   } else
9819     return false;
9820 
9821   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9822                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9823 }
9824 
9825 /// Try turning a load/store into a pre-indexed load/store when the base
9826 /// pointer is an add or subtract and it has other uses besides the load/store.
9827 /// After the transformation, the new indexed load/store has effectively folded
9828 /// the add/subtract in and all of its other uses are redirected to the
9829 /// new load/store.
9830 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9831   if (Level < AfterLegalizeDAG)
9832     return false;
9833 
9834   bool isLoad = true;
9835   SDValue Ptr;
9836   EVT VT;
9837   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9838     if (LD->isIndexed())
9839       return false;
9840     VT = LD->getMemoryVT();
9841     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9842         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9843       return false;
9844     Ptr = LD->getBasePtr();
9845   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9846     if (ST->isIndexed())
9847       return false;
9848     VT = ST->getMemoryVT();
9849     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9850         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9851       return false;
9852     Ptr = ST->getBasePtr();
9853     isLoad = false;
9854   } else {
9855     return false;
9856   }
9857 
9858   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9859   // out.  There is no reason to make this a preinc/predec.
9860   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9861       Ptr.getNode()->hasOneUse())
9862     return false;
9863 
9864   // Ask the target to do addressing mode selection.
9865   SDValue BasePtr;
9866   SDValue Offset;
9867   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9868   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9869     return false;
9870 
9871   // Backends without true r+i pre-indexed forms may need to pass a
9872   // constant base with a variable offset so that constant coercion
9873   // will work with the patterns in canonical form.
9874   bool Swapped = false;
9875   if (isa<ConstantSDNode>(BasePtr)) {
9876     std::swap(BasePtr, Offset);
9877     Swapped = true;
9878   }
9879 
9880   // Don't create a indexed load / store with zero offset.
9881   if (isNullConstant(Offset))
9882     return false;
9883 
9884   // Try turning it into a pre-indexed load / store except when:
9885   // 1) The new base ptr is a frame index.
9886   // 2) If N is a store and the new base ptr is either the same as or is a
9887   //    predecessor of the value being stored.
9888   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9889   //    that would create a cycle.
9890   // 4) All uses are load / store ops that use it as old base ptr.
9891 
9892   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9893   // (plus the implicit offset) to a register to preinc anyway.
9894   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9895     return false;
9896 
9897   // Check #2.
9898   if (!isLoad) {
9899     SDValue Val = cast<StoreSDNode>(N)->getValue();
9900     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9901       return false;
9902   }
9903 
9904   // Caches for hasPredecessorHelper.
9905   SmallPtrSet<const SDNode *, 32> Visited;
9906   SmallVector<const SDNode *, 16> Worklist;
9907   Worklist.push_back(N);
9908 
9909   // If the offset is a constant, there may be other adds of constants that
9910   // can be folded with this one. We should do this to avoid having to keep
9911   // a copy of the original base pointer.
9912   SmallVector<SDNode *, 16> OtherUses;
9913   if (isa<ConstantSDNode>(Offset))
9914     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9915                               UE = BasePtr.getNode()->use_end();
9916          UI != UE; ++UI) {
9917       SDUse &Use = UI.getUse();
9918       // Skip the use that is Ptr and uses of other results from BasePtr's
9919       // node (important for nodes that return multiple results).
9920       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9921         continue;
9922 
9923       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9924         continue;
9925 
9926       if (Use.getUser()->getOpcode() != ISD::ADD &&
9927           Use.getUser()->getOpcode() != ISD::SUB) {
9928         OtherUses.clear();
9929         break;
9930       }
9931 
9932       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9933       if (!isa<ConstantSDNode>(Op1)) {
9934         OtherUses.clear();
9935         break;
9936       }
9937 
9938       // FIXME: In some cases, we can be smarter about this.
9939       if (Op1.getValueType() != Offset.getValueType()) {
9940         OtherUses.clear();
9941         break;
9942       }
9943 
9944       OtherUses.push_back(Use.getUser());
9945     }
9946 
9947   if (Swapped)
9948     std::swap(BasePtr, Offset);
9949 
9950   // Now check for #3 and #4.
9951   bool RealUse = false;
9952 
9953   for (SDNode *Use : Ptr.getNode()->uses()) {
9954     if (Use == N)
9955       continue;
9956     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9957       return false;
9958 
9959     // If Ptr may be folded in addressing mode of other use, then it's
9960     // not profitable to do this transformation.
9961     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9962       RealUse = true;
9963   }
9964 
9965   if (!RealUse)
9966     return false;
9967 
9968   SDValue Result;
9969   if (isLoad)
9970     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9971                                 BasePtr, Offset, AM);
9972   else
9973     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9974                                  BasePtr, Offset, AM);
9975   ++PreIndexedNodes;
9976   ++NodesCombined;
9977   DEBUG(dbgs() << "\nReplacing.4 ";
9978         N->dump(&DAG);
9979         dbgs() << "\nWith: ";
9980         Result.getNode()->dump(&DAG);
9981         dbgs() << '\n');
9982   WorklistRemover DeadNodes(*this);
9983   if (isLoad) {
9984     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9985     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9986   } else {
9987     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9988   }
9989 
9990   // Finally, since the node is now dead, remove it from the graph.
9991   deleteAndRecombine(N);
9992 
9993   if (Swapped)
9994     std::swap(BasePtr, Offset);
9995 
9996   // Replace other uses of BasePtr that can be updated to use Ptr
9997   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9998     unsigned OffsetIdx = 1;
9999     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
10000       OffsetIdx = 0;
10001     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10002            BasePtr.getNode() && "Expected BasePtr operand");
10003 
10004     // We need to replace ptr0 in the following expression:
10005     //   x0 * offset0 + y0 * ptr0 = t0
10006     // knowing that
10007     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10008     //
10009     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10010     // indexed load/store and the expresion that needs to be re-written.
10011     //
10012     // Therefore, we have:
10013     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10014 
10015     ConstantSDNode *CN =
10016       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
10017     int X0, X1, Y0, Y1;
10018     const APInt &Offset0 = CN->getAPIntValue();
10019     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10020 
10021     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10022     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10023     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10024     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10025 
10026     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10027 
10028     APInt CNV = Offset0;
10029     if (X0 < 0) CNV = -CNV;
10030     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10031     else CNV = CNV - Offset1;
10032 
10033     SDLoc DL(OtherUses[i]);
10034 
10035     // We can now generate the new expression.
10036     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10037     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10038 
10039     SDValue NewUse = DAG.getNode(Opcode,
10040                                  DL,
10041                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10042     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10043     deleteAndRecombine(OtherUses[i]);
10044   }
10045 
10046   // Replace the uses of Ptr with uses of the updated base value.
10047   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10048   deleteAndRecombine(Ptr.getNode());
10049 
10050   return true;
10051 }
10052 
10053 /// Try to combine a load/store with a add/sub of the base pointer node into a
10054 /// post-indexed load/store. The transformation folded the add/subtract into the
10055 /// new indexed load/store effectively and all of its uses are redirected to the
10056 /// new load/store.
10057 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10058   if (Level < AfterLegalizeDAG)
10059     return false;
10060 
10061   bool isLoad = true;
10062   SDValue Ptr;
10063   EVT VT;
10064   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10065     if (LD->isIndexed())
10066       return false;
10067     VT = LD->getMemoryVT();
10068     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10069         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10070       return false;
10071     Ptr = LD->getBasePtr();
10072   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10073     if (ST->isIndexed())
10074       return false;
10075     VT = ST->getMemoryVT();
10076     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10077         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10078       return false;
10079     Ptr = ST->getBasePtr();
10080     isLoad = false;
10081   } else {
10082     return false;
10083   }
10084 
10085   if (Ptr.getNode()->hasOneUse())
10086     return false;
10087 
10088   for (SDNode *Op : Ptr.getNode()->uses()) {
10089     if (Op == N ||
10090         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10091       continue;
10092 
10093     SDValue BasePtr;
10094     SDValue Offset;
10095     ISD::MemIndexedMode AM = ISD::UNINDEXED;
10096     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10097       // Don't create a indexed load / store with zero offset.
10098       if (isNullConstant(Offset))
10099         continue;
10100 
10101       // Try turning it into a post-indexed load / store except when
10102       // 1) All uses are load / store ops that use it as base ptr (and
10103       //    it may be folded as addressing mmode).
10104       // 2) Op must be independent of N, i.e. Op is neither a predecessor
10105       //    nor a successor of N. Otherwise, if Op is folded that would
10106       //    create a cycle.
10107 
10108       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10109         continue;
10110 
10111       // Check for #1.
10112       bool TryNext = false;
10113       for (SDNode *Use : BasePtr.getNode()->uses()) {
10114         if (Use == Ptr.getNode())
10115           continue;
10116 
10117         // If all the uses are load / store addresses, then don't do the
10118         // transformation.
10119         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10120           bool RealUse = false;
10121           for (SDNode *UseUse : Use->uses()) {
10122             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10123               RealUse = true;
10124           }
10125 
10126           if (!RealUse) {
10127             TryNext = true;
10128             break;
10129           }
10130         }
10131       }
10132 
10133       if (TryNext)
10134         continue;
10135 
10136       // Check for #2
10137       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10138         SDValue Result = isLoad
10139           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10140                                BasePtr, Offset, AM)
10141           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10142                                 BasePtr, Offset, AM);
10143         ++PostIndexedNodes;
10144         ++NodesCombined;
10145         DEBUG(dbgs() << "\nReplacing.5 ";
10146               N->dump(&DAG);
10147               dbgs() << "\nWith: ";
10148               Result.getNode()->dump(&DAG);
10149               dbgs() << '\n');
10150         WorklistRemover DeadNodes(*this);
10151         if (isLoad) {
10152           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10153           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10154         } else {
10155           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10156         }
10157 
10158         // Finally, since the node is now dead, remove it from the graph.
10159         deleteAndRecombine(N);
10160 
10161         // Replace the uses of Use with uses of the updated base value.
10162         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10163                                       Result.getValue(isLoad ? 1 : 0));
10164         deleteAndRecombine(Op);
10165         return true;
10166       }
10167     }
10168   }
10169 
10170   return false;
10171 }
10172 
10173 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10174 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10175   ISD::MemIndexedMode AM = LD->getAddressingMode();
10176   assert(AM != ISD::UNINDEXED);
10177   SDValue BP = LD->getOperand(1);
10178   SDValue Inc = LD->getOperand(2);
10179 
10180   // Some backends use TargetConstants for load offsets, but don't expect
10181   // TargetConstants in general ADD nodes. We can convert these constants into
10182   // regular Constants (if the constant is not opaque).
10183   assert((Inc.getOpcode() != ISD::TargetConstant ||
10184           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10185          "Cannot split out indexing using opaque target constants");
10186   if (Inc.getOpcode() == ISD::TargetConstant) {
10187     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10188     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10189                           ConstInc->getValueType(0));
10190   }
10191 
10192   unsigned Opc =
10193       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10194   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10195 }
10196 
10197 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10198   LoadSDNode *LD  = cast<LoadSDNode>(N);
10199   SDValue Chain = LD->getChain();
10200   SDValue Ptr   = LD->getBasePtr();
10201 
10202   // If load is not volatile and there are no uses of the loaded value (and
10203   // the updated indexed value in case of indexed loads), change uses of the
10204   // chain value into uses of the chain input (i.e. delete the dead load).
10205   if (!LD->isVolatile()) {
10206     if (N->getValueType(1) == MVT::Other) {
10207       // Unindexed loads.
10208       if (!N->hasAnyUseOfValue(0)) {
10209         // It's not safe to use the two value CombineTo variant here. e.g.
10210         // v1, chain2 = load chain1, loc
10211         // v2, chain3 = load chain2, loc
10212         // v3         = add v2, c
10213         // Now we replace use of chain2 with chain1.  This makes the second load
10214         // isomorphic to the one we are deleting, and thus makes this load live.
10215         DEBUG(dbgs() << "\nReplacing.6 ";
10216               N->dump(&DAG);
10217               dbgs() << "\nWith chain: ";
10218               Chain.getNode()->dump(&DAG);
10219               dbgs() << "\n");
10220         WorklistRemover DeadNodes(*this);
10221         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10222 
10223         if (N->use_empty())
10224           deleteAndRecombine(N);
10225 
10226         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10227       }
10228     } else {
10229       // Indexed loads.
10230       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10231 
10232       // If this load has an opaque TargetConstant offset, then we cannot split
10233       // the indexing into an add/sub directly (that TargetConstant may not be
10234       // valid for a different type of node, and we cannot convert an opaque
10235       // target constant into a regular constant).
10236       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10237                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10238 
10239       if (!N->hasAnyUseOfValue(0) &&
10240           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10241         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10242         SDValue Index;
10243         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10244           Index = SplitIndexingFromLoad(LD);
10245           // Try to fold the base pointer arithmetic into subsequent loads and
10246           // stores.
10247           AddUsersToWorklist(N);
10248         } else
10249           Index = DAG.getUNDEF(N->getValueType(1));
10250         DEBUG(dbgs() << "\nReplacing.7 ";
10251               N->dump(&DAG);
10252               dbgs() << "\nWith: ";
10253               Undef.getNode()->dump(&DAG);
10254               dbgs() << " and 2 other values\n");
10255         WorklistRemover DeadNodes(*this);
10256         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10257         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10258         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10259         deleteAndRecombine(N);
10260         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10261       }
10262     }
10263   }
10264 
10265   // If this load is directly stored, replace the load value with the stored
10266   // value.
10267   // TODO: Handle store large -> read small portion.
10268   // TODO: Handle TRUNCSTORE/LOADEXT
10269   if (OptLevel != CodeGenOpt::None &&
10270       ISD::isNormalLoad(N) && !LD->isVolatile()) {
10271     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10272       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10273       if (PrevST->getBasePtr() == Ptr &&
10274           PrevST->getValue().getValueType() == N->getValueType(0))
10275       return CombineTo(N, Chain.getOperand(1), Chain);
10276     }
10277   }
10278 
10279   // Try to infer better alignment information than the load already has.
10280   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10281     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10282       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10283         SDValue NewLoad = DAG.getExtLoad(
10284             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10285             LD->getPointerInfo(), LD->getMemoryVT(), Align,
10286             LD->getMemOperand()->getFlags(), LD->getAAInfo());
10287         if (NewLoad.getNode() != N)
10288           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10289       }
10290     }
10291   }
10292 
10293   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10294                                                   : DAG.getSubtarget().useAA();
10295 #ifndef NDEBUG
10296   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10297       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10298     UseAA = false;
10299 #endif
10300   if (UseAA && LD->isUnindexed()) {
10301     // Walk up chain skipping non-aliasing memory nodes.
10302     SDValue BetterChain = FindBetterChain(N, Chain);
10303 
10304     // If there is a better chain.
10305     if (Chain != BetterChain) {
10306       SDValue ReplLoad;
10307 
10308       // Replace the chain to void dependency.
10309       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10310         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10311                                BetterChain, Ptr, LD->getMemOperand());
10312       } else {
10313         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10314                                   LD->getValueType(0),
10315                                   BetterChain, Ptr, LD->getMemoryVT(),
10316                                   LD->getMemOperand());
10317       }
10318 
10319       // Create token factor to keep old chain connected.
10320       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10321                                   MVT::Other, Chain, ReplLoad.getValue(1));
10322 
10323       // Make sure the new and old chains are cleaned up.
10324       AddToWorklist(Token.getNode());
10325 
10326       // Replace uses with load result and token factor. Don't add users
10327       // to work list.
10328       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10329     }
10330   }
10331 
10332   // Try transforming N to an indexed load.
10333   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10334     return SDValue(N, 0);
10335 
10336   // Try to slice up N to more direct loads if the slices are mapped to
10337   // different register banks or pairing can take place.
10338   if (SliceUpLoad(N))
10339     return SDValue(N, 0);
10340 
10341   return SDValue();
10342 }
10343 
10344 namespace {
10345 /// \brief Helper structure used to slice a load in smaller loads.
10346 /// Basically a slice is obtained from the following sequence:
10347 /// Origin = load Ty1, Base
10348 /// Shift = srl Ty1 Origin, CstTy Amount
10349 /// Inst = trunc Shift to Ty2
10350 ///
10351 /// Then, it will be rewriten into:
10352 /// Slice = load SliceTy, Base + SliceOffset
10353 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10354 ///
10355 /// SliceTy is deduced from the number of bits that are actually used to
10356 /// build Inst.
10357 struct LoadedSlice {
10358   /// \brief Helper structure used to compute the cost of a slice.
10359   struct Cost {
10360     /// Are we optimizing for code size.
10361     bool ForCodeSize;
10362     /// Various cost.
10363     unsigned Loads;
10364     unsigned Truncates;
10365     unsigned CrossRegisterBanksCopies;
10366     unsigned ZExts;
10367     unsigned Shift;
10368 
10369     Cost(bool ForCodeSize = false)
10370         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10371           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10372 
10373     /// \brief Get the cost of one isolated slice.
10374     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10375         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10376           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10377       EVT TruncType = LS.Inst->getValueType(0);
10378       EVT LoadedType = LS.getLoadedType();
10379       if (TruncType != LoadedType &&
10380           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10381         ZExts = 1;
10382     }
10383 
10384     /// \brief Account for slicing gain in the current cost.
10385     /// Slicing provide a few gains like removing a shift or a
10386     /// truncate. This method allows to grow the cost of the original
10387     /// load with the gain from this slice.
10388     void addSliceGain(const LoadedSlice &LS) {
10389       // Each slice saves a truncate.
10390       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10391       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10392                               LS.Inst->getValueType(0)))
10393         ++Truncates;
10394       // If there is a shift amount, this slice gets rid of it.
10395       if (LS.Shift)
10396         ++Shift;
10397       // If this slice can merge a cross register bank copy, account for it.
10398       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10399         ++CrossRegisterBanksCopies;
10400     }
10401 
10402     Cost &operator+=(const Cost &RHS) {
10403       Loads += RHS.Loads;
10404       Truncates += RHS.Truncates;
10405       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10406       ZExts += RHS.ZExts;
10407       Shift += RHS.Shift;
10408       return *this;
10409     }
10410 
10411     bool operator==(const Cost &RHS) const {
10412       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10413              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10414              ZExts == RHS.ZExts && Shift == RHS.Shift;
10415     }
10416 
10417     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10418 
10419     bool operator<(const Cost &RHS) const {
10420       // Assume cross register banks copies are as expensive as loads.
10421       // FIXME: Do we want some more target hooks?
10422       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10423       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10424       // Unless we are optimizing for code size, consider the
10425       // expensive operation first.
10426       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10427         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10428       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10429              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10430     }
10431 
10432     bool operator>(const Cost &RHS) const { return RHS < *this; }
10433 
10434     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10435 
10436     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10437   };
10438   // The last instruction that represent the slice. This should be a
10439   // truncate instruction.
10440   SDNode *Inst;
10441   // The original load instruction.
10442   LoadSDNode *Origin;
10443   // The right shift amount in bits from the original load.
10444   unsigned Shift;
10445   // The DAG from which Origin came from.
10446   // This is used to get some contextual information about legal types, etc.
10447   SelectionDAG *DAG;
10448 
10449   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10450               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10451       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10452 
10453   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10454   /// \return Result is \p BitWidth and has used bits set to 1 and
10455   ///         not used bits set to 0.
10456   APInt getUsedBits() const {
10457     // Reproduce the trunc(lshr) sequence:
10458     // - Start from the truncated value.
10459     // - Zero extend to the desired bit width.
10460     // - Shift left.
10461     assert(Origin && "No original load to compare against.");
10462     unsigned BitWidth = Origin->getValueSizeInBits(0);
10463     assert(Inst && "This slice is not bound to an instruction");
10464     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10465            "Extracted slice is bigger than the whole type!");
10466     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10467     UsedBits.setAllBits();
10468     UsedBits = UsedBits.zext(BitWidth);
10469     UsedBits <<= Shift;
10470     return UsedBits;
10471   }
10472 
10473   /// \brief Get the size of the slice to be loaded in bytes.
10474   unsigned getLoadedSize() const {
10475     unsigned SliceSize = getUsedBits().countPopulation();
10476     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10477     return SliceSize / 8;
10478   }
10479 
10480   /// \brief Get the type that will be loaded for this slice.
10481   /// Note: This may not be the final type for the slice.
10482   EVT getLoadedType() const {
10483     assert(DAG && "Missing context");
10484     LLVMContext &Ctxt = *DAG->getContext();
10485     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10486   }
10487 
10488   /// \brief Get the alignment of the load used for this slice.
10489   unsigned getAlignment() const {
10490     unsigned Alignment = Origin->getAlignment();
10491     unsigned Offset = getOffsetFromBase();
10492     if (Offset != 0)
10493       Alignment = MinAlign(Alignment, Alignment + Offset);
10494     return Alignment;
10495   }
10496 
10497   /// \brief Check if this slice can be rewritten with legal operations.
10498   bool isLegal() const {
10499     // An invalid slice is not legal.
10500     if (!Origin || !Inst || !DAG)
10501       return false;
10502 
10503     // Offsets are for indexed load only, we do not handle that.
10504     if (!Origin->getOffset().isUndef())
10505       return false;
10506 
10507     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10508 
10509     // Check that the type is legal.
10510     EVT SliceType = getLoadedType();
10511     if (!TLI.isTypeLegal(SliceType))
10512       return false;
10513 
10514     // Check that the load is legal for this type.
10515     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10516       return false;
10517 
10518     // Check that the offset can be computed.
10519     // 1. Check its type.
10520     EVT PtrType = Origin->getBasePtr().getValueType();
10521     if (PtrType == MVT::Untyped || PtrType.isExtended())
10522       return false;
10523 
10524     // 2. Check that it fits in the immediate.
10525     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10526       return false;
10527 
10528     // 3. Check that the computation is legal.
10529     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10530       return false;
10531 
10532     // Check that the zext is legal if it needs one.
10533     EVT TruncateType = Inst->getValueType(0);
10534     if (TruncateType != SliceType &&
10535         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10536       return false;
10537 
10538     return true;
10539   }
10540 
10541   /// \brief Get the offset in bytes of this slice in the original chunk of
10542   /// bits.
10543   /// \pre DAG != nullptr.
10544   uint64_t getOffsetFromBase() const {
10545     assert(DAG && "Missing context.");
10546     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10547     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10548     uint64_t Offset = Shift / 8;
10549     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10550     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10551            "The size of the original loaded type is not a multiple of a"
10552            " byte.");
10553     // If Offset is bigger than TySizeInBytes, it means we are loading all
10554     // zeros. This should have been optimized before in the process.
10555     assert(TySizeInBytes > Offset &&
10556            "Invalid shift amount for given loaded size");
10557     if (IsBigEndian)
10558       Offset = TySizeInBytes - Offset - getLoadedSize();
10559     return Offset;
10560   }
10561 
10562   /// \brief Generate the sequence of instructions to load the slice
10563   /// represented by this object and redirect the uses of this slice to
10564   /// this new sequence of instructions.
10565   /// \pre this->Inst && this->Origin are valid Instructions and this
10566   /// object passed the legal check: LoadedSlice::isLegal returned true.
10567   /// \return The last instruction of the sequence used to load the slice.
10568   SDValue loadSlice() const {
10569     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10570     const SDValue &OldBaseAddr = Origin->getBasePtr();
10571     SDValue BaseAddr = OldBaseAddr;
10572     // Get the offset in that chunk of bytes w.r.t. the endianess.
10573     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10574     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10575     if (Offset) {
10576       // BaseAddr = BaseAddr + Offset.
10577       EVT ArithType = BaseAddr.getValueType();
10578       SDLoc DL(Origin);
10579       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10580                               DAG->getConstant(Offset, DL, ArithType));
10581     }
10582 
10583     // Create the type of the loaded slice according to its size.
10584     EVT SliceType = getLoadedType();
10585 
10586     // Create the load for the slice.
10587     SDValue LastInst =
10588         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10589                      Origin->getPointerInfo().getWithOffset(Offset),
10590                      getAlignment(), Origin->getMemOperand()->getFlags());
10591     // If the final type is not the same as the loaded type, this means that
10592     // we have to pad with zero. Create a zero extend for that.
10593     EVT FinalType = Inst->getValueType(0);
10594     if (SliceType != FinalType)
10595       LastInst =
10596           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10597     return LastInst;
10598   }
10599 
10600   /// \brief Check if this slice can be merged with an expensive cross register
10601   /// bank copy. E.g.,
10602   /// i = load i32
10603   /// f = bitcast i32 i to float
10604   bool canMergeExpensiveCrossRegisterBankCopy() const {
10605     if (!Inst || !Inst->hasOneUse())
10606       return false;
10607     SDNode *Use = *Inst->use_begin();
10608     if (Use->getOpcode() != ISD::BITCAST)
10609       return false;
10610     assert(DAG && "Missing context");
10611     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10612     EVT ResVT = Use->getValueType(0);
10613     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10614     const TargetRegisterClass *ArgRC =
10615         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10616     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10617       return false;
10618 
10619     // At this point, we know that we perform a cross-register-bank copy.
10620     // Check if it is expensive.
10621     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10622     // Assume bitcasts are cheap, unless both register classes do not
10623     // explicitly share a common sub class.
10624     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10625       return false;
10626 
10627     // Check if it will be merged with the load.
10628     // 1. Check the alignment constraint.
10629     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10630         ResVT.getTypeForEVT(*DAG->getContext()));
10631 
10632     if (RequiredAlignment > getAlignment())
10633       return false;
10634 
10635     // 2. Check that the load is a legal operation for that type.
10636     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10637       return false;
10638 
10639     // 3. Check that we do not have a zext in the way.
10640     if (Inst->getValueType(0) != getLoadedType())
10641       return false;
10642 
10643     return true;
10644   }
10645 };
10646 }
10647 
10648 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10649 /// \p UsedBits looks like 0..0 1..1 0..0.
10650 static bool areUsedBitsDense(const APInt &UsedBits) {
10651   // If all the bits are one, this is dense!
10652   if (UsedBits.isAllOnesValue())
10653     return true;
10654 
10655   // Get rid of the unused bits on the right.
10656   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10657   // Get rid of the unused bits on the left.
10658   if (NarrowedUsedBits.countLeadingZeros())
10659     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10660   // Check that the chunk of bits is completely used.
10661   return NarrowedUsedBits.isAllOnesValue();
10662 }
10663 
10664 /// \brief Check whether or not \p First and \p Second are next to each other
10665 /// in memory. This means that there is no hole between the bits loaded
10666 /// by \p First and the bits loaded by \p Second.
10667 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10668                                      const LoadedSlice &Second) {
10669   assert(First.Origin == Second.Origin && First.Origin &&
10670          "Unable to match different memory origins.");
10671   APInt UsedBits = First.getUsedBits();
10672   assert((UsedBits & Second.getUsedBits()) == 0 &&
10673          "Slices are not supposed to overlap.");
10674   UsedBits |= Second.getUsedBits();
10675   return areUsedBitsDense(UsedBits);
10676 }
10677 
10678 /// \brief Adjust the \p GlobalLSCost according to the target
10679 /// paring capabilities and the layout of the slices.
10680 /// \pre \p GlobalLSCost should account for at least as many loads as
10681 /// there is in the slices in \p LoadedSlices.
10682 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10683                                  LoadedSlice::Cost &GlobalLSCost) {
10684   unsigned NumberOfSlices = LoadedSlices.size();
10685   // If there is less than 2 elements, no pairing is possible.
10686   if (NumberOfSlices < 2)
10687     return;
10688 
10689   // Sort the slices so that elements that are likely to be next to each
10690   // other in memory are next to each other in the list.
10691   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10692             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10693     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10694     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10695   });
10696   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10697   // First (resp. Second) is the first (resp. Second) potentially candidate
10698   // to be placed in a paired load.
10699   const LoadedSlice *First = nullptr;
10700   const LoadedSlice *Second = nullptr;
10701   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10702                 // Set the beginning of the pair.
10703                                                            First = Second) {
10704 
10705     Second = &LoadedSlices[CurrSlice];
10706 
10707     // If First is NULL, it means we start a new pair.
10708     // Get to the next slice.
10709     if (!First)
10710       continue;
10711 
10712     EVT LoadedType = First->getLoadedType();
10713 
10714     // If the types of the slices are different, we cannot pair them.
10715     if (LoadedType != Second->getLoadedType())
10716       continue;
10717 
10718     // Check if the target supplies paired loads for this type.
10719     unsigned RequiredAlignment = 0;
10720     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10721       // move to the next pair, this type is hopeless.
10722       Second = nullptr;
10723       continue;
10724     }
10725     // Check if we meet the alignment requirement.
10726     if (RequiredAlignment > First->getAlignment())
10727       continue;
10728 
10729     // Check that both loads are next to each other in memory.
10730     if (!areSlicesNextToEachOther(*First, *Second))
10731       continue;
10732 
10733     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10734     --GlobalLSCost.Loads;
10735     // Move to the next pair.
10736     Second = nullptr;
10737   }
10738 }
10739 
10740 /// \brief Check the profitability of all involved LoadedSlice.
10741 /// Currently, it is considered profitable if there is exactly two
10742 /// involved slices (1) which are (2) next to each other in memory, and
10743 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10744 ///
10745 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10746 /// the elements themselves.
10747 ///
10748 /// FIXME: When the cost model will be mature enough, we can relax
10749 /// constraints (1) and (2).
10750 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10751                                 const APInt &UsedBits, bool ForCodeSize) {
10752   unsigned NumberOfSlices = LoadedSlices.size();
10753   if (StressLoadSlicing)
10754     return NumberOfSlices > 1;
10755 
10756   // Check (1).
10757   if (NumberOfSlices != 2)
10758     return false;
10759 
10760   // Check (2).
10761   if (!areUsedBitsDense(UsedBits))
10762     return false;
10763 
10764   // Check (3).
10765   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10766   // The original code has one big load.
10767   OrigCost.Loads = 1;
10768   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10769     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10770     // Accumulate the cost of all the slices.
10771     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10772     GlobalSlicingCost += SliceCost;
10773 
10774     // Account as cost in the original configuration the gain obtained
10775     // with the current slices.
10776     OrigCost.addSliceGain(LS);
10777   }
10778 
10779   // If the target supports paired load, adjust the cost accordingly.
10780   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10781   return OrigCost > GlobalSlicingCost;
10782 }
10783 
10784 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10785 /// operations, split it in the various pieces being extracted.
10786 ///
10787 /// This sort of thing is introduced by SROA.
10788 /// This slicing takes care not to insert overlapping loads.
10789 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10790 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10791   if (Level < AfterLegalizeDAG)
10792     return false;
10793 
10794   LoadSDNode *LD = cast<LoadSDNode>(N);
10795   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10796       !LD->getValueType(0).isInteger())
10797     return false;
10798 
10799   // Keep track of already used bits to detect overlapping values.
10800   // In that case, we will just abort the transformation.
10801   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10802 
10803   SmallVector<LoadedSlice, 4> LoadedSlices;
10804 
10805   // Check if this load is used as several smaller chunks of bits.
10806   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10807   // of computation for each trunc.
10808   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10809        UI != UIEnd; ++UI) {
10810     // Skip the uses of the chain.
10811     if (UI.getUse().getResNo() != 0)
10812       continue;
10813 
10814     SDNode *User = *UI;
10815     unsigned Shift = 0;
10816 
10817     // Check if this is a trunc(lshr).
10818     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10819         isa<ConstantSDNode>(User->getOperand(1))) {
10820       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10821       User = *User->use_begin();
10822     }
10823 
10824     // At this point, User is a Truncate, iff we encountered, trunc or
10825     // trunc(lshr).
10826     if (User->getOpcode() != ISD::TRUNCATE)
10827       return false;
10828 
10829     // The width of the type must be a power of 2 and greater than 8-bits.
10830     // Otherwise the load cannot be represented in LLVM IR.
10831     // Moreover, if we shifted with a non-8-bits multiple, the slice
10832     // will be across several bytes. We do not support that.
10833     unsigned Width = User->getValueSizeInBits(0);
10834     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10835       return 0;
10836 
10837     // Build the slice for this chain of computations.
10838     LoadedSlice LS(User, LD, Shift, &DAG);
10839     APInt CurrentUsedBits = LS.getUsedBits();
10840 
10841     // Check if this slice overlaps with another.
10842     if ((CurrentUsedBits & UsedBits) != 0)
10843       return false;
10844     // Update the bits used globally.
10845     UsedBits |= CurrentUsedBits;
10846 
10847     // Check if the new slice would be legal.
10848     if (!LS.isLegal())
10849       return false;
10850 
10851     // Record the slice.
10852     LoadedSlices.push_back(LS);
10853   }
10854 
10855   // Abort slicing if it does not seem to be profitable.
10856   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10857     return false;
10858 
10859   ++SlicedLoads;
10860 
10861   // Rewrite each chain to use an independent load.
10862   // By construction, each chain can be represented by a unique load.
10863 
10864   // Prepare the argument for the new token factor for all the slices.
10865   SmallVector<SDValue, 8> ArgChains;
10866   for (SmallVectorImpl<LoadedSlice>::const_iterator
10867            LSIt = LoadedSlices.begin(),
10868            LSItEnd = LoadedSlices.end();
10869        LSIt != LSItEnd; ++LSIt) {
10870     SDValue SliceInst = LSIt->loadSlice();
10871     CombineTo(LSIt->Inst, SliceInst, true);
10872     if (SliceInst.getOpcode() != ISD::LOAD)
10873       SliceInst = SliceInst.getOperand(0);
10874     assert(SliceInst->getOpcode() == ISD::LOAD &&
10875            "It takes more than a zext to get to the loaded slice!!");
10876     ArgChains.push_back(SliceInst.getValue(1));
10877   }
10878 
10879   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10880                               ArgChains);
10881   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10882   return true;
10883 }
10884 
10885 /// Check to see if V is (and load (ptr), imm), where the load is having
10886 /// specific bytes cleared out.  If so, return the byte size being masked out
10887 /// and the shift amount.
10888 static std::pair<unsigned, unsigned>
10889 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10890   std::pair<unsigned, unsigned> Result(0, 0);
10891 
10892   // Check for the structure we're looking for.
10893   if (V->getOpcode() != ISD::AND ||
10894       !isa<ConstantSDNode>(V->getOperand(1)) ||
10895       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10896     return Result;
10897 
10898   // Check the chain and pointer.
10899   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10900   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10901 
10902   // The store should be chained directly to the load or be an operand of a
10903   // tokenfactor.
10904   if (LD == Chain.getNode())
10905     ; // ok.
10906   else if (Chain->getOpcode() != ISD::TokenFactor)
10907     return Result; // Fail.
10908   else {
10909     bool isOk = false;
10910     for (const SDValue &ChainOp : Chain->op_values())
10911       if (ChainOp.getNode() == LD) {
10912         isOk = true;
10913         break;
10914       }
10915     if (!isOk) return Result;
10916   }
10917 
10918   // This only handles simple types.
10919   if (V.getValueType() != MVT::i16 &&
10920       V.getValueType() != MVT::i32 &&
10921       V.getValueType() != MVT::i64)
10922     return Result;
10923 
10924   // Check the constant mask.  Invert it so that the bits being masked out are
10925   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10926   // follow the sign bit for uniformity.
10927   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10928   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10929   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10930   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10931   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10932   if (NotMaskLZ == 64) return Result;  // All zero mask.
10933 
10934   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10935   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10936     return Result;
10937 
10938   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10939   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10940     NotMaskLZ -= 64-V.getValueSizeInBits();
10941 
10942   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10943   switch (MaskedBytes) {
10944   case 1:
10945   case 2:
10946   case 4: break;
10947   default: return Result; // All one mask, or 5-byte mask.
10948   }
10949 
10950   // Verify that the first bit starts at a multiple of mask so that the access
10951   // is aligned the same as the access width.
10952   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10953 
10954   Result.first = MaskedBytes;
10955   Result.second = NotMaskTZ/8;
10956   return Result;
10957 }
10958 
10959 
10960 /// Check to see if IVal is something that provides a value as specified by
10961 /// MaskInfo. If so, replace the specified store with a narrower store of
10962 /// truncated IVal.
10963 static SDNode *
10964 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10965                                 SDValue IVal, StoreSDNode *St,
10966                                 DAGCombiner *DC) {
10967   unsigned NumBytes = MaskInfo.first;
10968   unsigned ByteShift = MaskInfo.second;
10969   SelectionDAG &DAG = DC->getDAG();
10970 
10971   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10972   // that uses this.  If not, this is not a replacement.
10973   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10974                                   ByteShift*8, (ByteShift+NumBytes)*8);
10975   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10976 
10977   // Check that it is legal on the target to do this.  It is legal if the new
10978   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10979   // legalization.
10980   MVT VT = MVT::getIntegerVT(NumBytes*8);
10981   if (!DC->isTypeLegal(VT))
10982     return nullptr;
10983 
10984   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10985   // shifted by ByteShift and truncated down to NumBytes.
10986   if (ByteShift) {
10987     SDLoc DL(IVal);
10988     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10989                        DAG.getConstant(ByteShift*8, DL,
10990                                     DC->getShiftAmountTy(IVal.getValueType())));
10991   }
10992 
10993   // Figure out the offset for the store and the alignment of the access.
10994   unsigned StOffset;
10995   unsigned NewAlign = St->getAlignment();
10996 
10997   if (DAG.getDataLayout().isLittleEndian())
10998     StOffset = ByteShift;
10999   else
11000     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11001 
11002   SDValue Ptr = St->getBasePtr();
11003   if (StOffset) {
11004     SDLoc DL(IVal);
11005     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11006                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11007     NewAlign = MinAlign(NewAlign, StOffset);
11008   }
11009 
11010   // Truncate down to the new size.
11011   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11012 
11013   ++OpsNarrowed;
11014   return DAG
11015       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11016                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11017       .getNode();
11018 }
11019 
11020 
11021 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11022 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11023 /// narrowing the load and store if it would end up being a win for performance
11024 /// or code size.
11025 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11026   StoreSDNode *ST  = cast<StoreSDNode>(N);
11027   if (ST->isVolatile())
11028     return SDValue();
11029 
11030   SDValue Chain = ST->getChain();
11031   SDValue Value = ST->getValue();
11032   SDValue Ptr   = ST->getBasePtr();
11033   EVT VT = Value.getValueType();
11034 
11035   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11036     return SDValue();
11037 
11038   unsigned Opc = Value.getOpcode();
11039 
11040   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11041   // is a byte mask indicating a consecutive number of bytes, check to see if
11042   // Y is known to provide just those bytes.  If so, we try to replace the
11043   // load + replace + store sequence with a single (narrower) store, which makes
11044   // the load dead.
11045   if (Opc == ISD::OR) {
11046     std::pair<unsigned, unsigned> MaskedLoad;
11047     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11048     if (MaskedLoad.first)
11049       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11050                                                   Value.getOperand(1), ST,this))
11051         return SDValue(NewST, 0);
11052 
11053     // Or is commutative, so try swapping X and Y.
11054     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11055     if (MaskedLoad.first)
11056       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11057                                                   Value.getOperand(0), ST,this))
11058         return SDValue(NewST, 0);
11059   }
11060 
11061   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11062       Value.getOperand(1).getOpcode() != ISD::Constant)
11063     return SDValue();
11064 
11065   SDValue N0 = Value.getOperand(0);
11066   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11067       Chain == SDValue(N0.getNode(), 1)) {
11068     LoadSDNode *LD = cast<LoadSDNode>(N0);
11069     if (LD->getBasePtr() != Ptr ||
11070         LD->getPointerInfo().getAddrSpace() !=
11071         ST->getPointerInfo().getAddrSpace())
11072       return SDValue();
11073 
11074     // Find the type to narrow it the load / op / store to.
11075     SDValue N1 = Value.getOperand(1);
11076     unsigned BitWidth = N1.getValueSizeInBits();
11077     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11078     if (Opc == ISD::AND)
11079       Imm ^= APInt::getAllOnesValue(BitWidth);
11080     if (Imm == 0 || Imm.isAllOnesValue())
11081       return SDValue();
11082     unsigned ShAmt = Imm.countTrailingZeros();
11083     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11084     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11085     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11086     // The narrowing should be profitable, the load/store operation should be
11087     // legal (or custom) and the store size should be equal to the NewVT width.
11088     while (NewBW < BitWidth &&
11089            (NewVT.getStoreSizeInBits() != NewBW ||
11090             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11091             !TLI.isNarrowingProfitable(VT, NewVT))) {
11092       NewBW = NextPowerOf2(NewBW);
11093       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11094     }
11095     if (NewBW >= BitWidth)
11096       return SDValue();
11097 
11098     // If the lsb changed does not start at the type bitwidth boundary,
11099     // start at the previous one.
11100     if (ShAmt % NewBW)
11101       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11102     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11103                                    std::min(BitWidth, ShAmt + NewBW));
11104     if ((Imm & Mask) == Imm) {
11105       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11106       if (Opc == ISD::AND)
11107         NewImm ^= APInt::getAllOnesValue(NewBW);
11108       uint64_t PtrOff = ShAmt / 8;
11109       // For big endian targets, we need to adjust the offset to the pointer to
11110       // load the correct bytes.
11111       if (DAG.getDataLayout().isBigEndian())
11112         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11113 
11114       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11115       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11116       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11117         return SDValue();
11118 
11119       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11120                                    Ptr.getValueType(), Ptr,
11121                                    DAG.getConstant(PtrOff, SDLoc(LD),
11122                                                    Ptr.getValueType()));
11123       SDValue NewLD =
11124           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11125                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11126                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
11127       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11128                                    DAG.getConstant(NewImm, SDLoc(Value),
11129                                                    NewVT));
11130       SDValue NewST =
11131           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11132                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11133 
11134       AddToWorklist(NewPtr.getNode());
11135       AddToWorklist(NewLD.getNode());
11136       AddToWorklist(NewVal.getNode());
11137       WorklistRemover DeadNodes(*this);
11138       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11139       ++OpsNarrowed;
11140       return NewST;
11141     }
11142   }
11143 
11144   return SDValue();
11145 }
11146 
11147 /// For a given floating point load / store pair, if the load value isn't used
11148 /// by any other operations, then consider transforming the pair to integer
11149 /// load / store operations if the target deems the transformation profitable.
11150 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11151   StoreSDNode *ST  = cast<StoreSDNode>(N);
11152   SDValue Chain = ST->getChain();
11153   SDValue Value = ST->getValue();
11154   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11155       Value.hasOneUse() &&
11156       Chain == SDValue(Value.getNode(), 1)) {
11157     LoadSDNode *LD = cast<LoadSDNode>(Value);
11158     EVT VT = LD->getMemoryVT();
11159     if (!VT.isFloatingPoint() ||
11160         VT != ST->getMemoryVT() ||
11161         LD->isNonTemporal() ||
11162         ST->isNonTemporal() ||
11163         LD->getPointerInfo().getAddrSpace() != 0 ||
11164         ST->getPointerInfo().getAddrSpace() != 0)
11165       return SDValue();
11166 
11167     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11168     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11169         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11170         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11171         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11172       return SDValue();
11173 
11174     unsigned LDAlign = LD->getAlignment();
11175     unsigned STAlign = ST->getAlignment();
11176     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11177     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11178     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11179       return SDValue();
11180 
11181     SDValue NewLD =
11182         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11183                     LD->getPointerInfo(), LDAlign);
11184 
11185     SDValue NewST =
11186         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11187                      ST->getPointerInfo(), STAlign);
11188 
11189     AddToWorklist(NewLD.getNode());
11190     AddToWorklist(NewST.getNode());
11191     WorklistRemover DeadNodes(*this);
11192     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11193     ++LdStFP2Int;
11194     return NewST;
11195   }
11196 
11197   return SDValue();
11198 }
11199 
11200 namespace {
11201 /// Helper struct to parse and store a memory address as base + index + offset.
11202 /// We ignore sign extensions when it is safe to do so.
11203 /// The following two expressions are not equivalent. To differentiate we need
11204 /// to store whether there was a sign extension involved in the index
11205 /// computation.
11206 ///  (load (i64 add (i64 copyfromreg %c)
11207 ///                 (i64 signextend (add (i8 load %index)
11208 ///                                      (i8 1))))
11209 /// vs
11210 ///
11211 /// (load (i64 add (i64 copyfromreg %c)
11212 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11213 ///                                         (i32 1)))))
11214 struct BaseIndexOffset {
11215   SDValue Base;
11216   SDValue Index;
11217   int64_t Offset;
11218   bool IsIndexSignExt;
11219 
11220   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11221 
11222   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11223                   bool IsIndexSignExt) :
11224     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11225 
11226   bool equalBaseIndex(const BaseIndexOffset &Other) {
11227     return Other.Base == Base && Other.Index == Index &&
11228       Other.IsIndexSignExt == IsIndexSignExt;
11229   }
11230 
11231   /// Parses tree in Ptr for base, index, offset addresses.
11232   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11233     bool IsIndexSignExt = false;
11234 
11235     // Split up a folded GlobalAddress+Offset into its component parts.
11236     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11237       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11238         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11239                                                     SDLoc(GA),
11240                                                     GA->getValueType(0),
11241                                                     /*Offset=*/0,
11242                                                     /*isTargetGA=*/false,
11243                                                     GA->getTargetFlags()),
11244                                SDValue(),
11245                                GA->getOffset(),
11246                                IsIndexSignExt);
11247       }
11248 
11249     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11250     // instruction, then it could be just the BASE or everything else we don't
11251     // know how to handle. Just use Ptr as BASE and give up.
11252     if (Ptr->getOpcode() != ISD::ADD)
11253       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11254 
11255     // We know that we have at least an ADD instruction. Try to pattern match
11256     // the simple case of BASE + OFFSET.
11257     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11258       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11259       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11260                               IsIndexSignExt);
11261     }
11262 
11263     // Inside a loop the current BASE pointer is calculated using an ADD and a
11264     // MUL instruction. In this case Ptr is the actual BASE pointer.
11265     // (i64 add (i64 %array_ptr)
11266     //          (i64 mul (i64 %induction_var)
11267     //                   (i64 %element_size)))
11268     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11269       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11270 
11271     // Look at Base + Index + Offset cases.
11272     SDValue Base = Ptr->getOperand(0);
11273     SDValue IndexOffset = Ptr->getOperand(1);
11274 
11275     // Skip signextends.
11276     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11277       IndexOffset = IndexOffset->getOperand(0);
11278       IsIndexSignExt = true;
11279     }
11280 
11281     // Either the case of Base + Index (no offset) or something else.
11282     if (IndexOffset->getOpcode() != ISD::ADD)
11283       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11284 
11285     // Now we have the case of Base + Index + offset.
11286     SDValue Index = IndexOffset->getOperand(0);
11287     SDValue Offset = IndexOffset->getOperand(1);
11288 
11289     if (!isa<ConstantSDNode>(Offset))
11290       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11291 
11292     // Ignore signextends.
11293     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11294       Index = Index->getOperand(0);
11295       IsIndexSignExt = true;
11296     } else IsIndexSignExt = false;
11297 
11298     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11299     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11300   }
11301 };
11302 } // namespace
11303 
11304 // This is a helper function for visitMUL to check the profitability
11305 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11306 // MulNode is the original multiply, AddNode is (add x, c1),
11307 // and ConstNode is c2.
11308 //
11309 // If the (add x, c1) has multiple uses, we could increase
11310 // the number of adds if we make this transformation.
11311 // It would only be worth doing this if we can remove a
11312 // multiply in the process. Check for that here.
11313 // To illustrate:
11314 //     (A + c1) * c3
11315 //     (A + c2) * c3
11316 // We're checking for cases where we have common "c3 * A" expressions.
11317 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11318                                               SDValue &AddNode,
11319                                               SDValue &ConstNode) {
11320   APInt Val;
11321 
11322   // If the add only has one use, this would be OK to do.
11323   if (AddNode.getNode()->hasOneUse())
11324     return true;
11325 
11326   // Walk all the users of the constant with which we're multiplying.
11327   for (SDNode *Use : ConstNode->uses()) {
11328 
11329     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11330       continue;
11331 
11332     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11333       SDNode *OtherOp;
11334       SDNode *MulVar = AddNode.getOperand(0).getNode();
11335 
11336       // OtherOp is what we're multiplying against the constant.
11337       if (Use->getOperand(0) == ConstNode)
11338         OtherOp = Use->getOperand(1).getNode();
11339       else
11340         OtherOp = Use->getOperand(0).getNode();
11341 
11342       // Check to see if multiply is with the same operand of our "add".
11343       //
11344       //     ConstNode  = CONST
11345       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11346       //     ...
11347       //     AddNode  = (A + c1)  <-- MulVar is A.
11348       //         = AddNode * ConstNode   <-- current visiting instruction.
11349       //
11350       // If we make this transformation, we will have a common
11351       // multiply (ConstNode * A) that we can save.
11352       if (OtherOp == MulVar)
11353         return true;
11354 
11355       // Now check to see if a future expansion will give us a common
11356       // multiply.
11357       //
11358       //     ConstNode  = CONST
11359       //     AddNode    = (A + c1)
11360       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11361       //     ...
11362       //     OtherOp = (A + c2)
11363       //     Use     = OtherOp * ConstNode <-- visiting Use.
11364       //
11365       // If we make this transformation, we will have a common
11366       // multiply (CONST * A) after we also do the same transformation
11367       // to the "t2" instruction.
11368       if (OtherOp->getOpcode() == ISD::ADD &&
11369           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11370           OtherOp->getOperand(0).getNode() == MulVar)
11371         return true;
11372     }
11373   }
11374 
11375   // Didn't find a case where this would be profitable.
11376   return false;
11377 }
11378 
11379 SDValue DAGCombiner::getMergedConstantVectorStore(
11380     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11381     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11382   SmallVector<SDValue, 8> BuildVector;
11383 
11384   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11385     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11386     Chains.push_back(St->getChain());
11387     BuildVector.push_back(St->getValue());
11388   }
11389 
11390   return DAG.getBuildVector(Ty, SL, BuildVector);
11391 }
11392 
11393 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11394                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11395                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11396   // Make sure we have something to merge.
11397   if (NumStores < 2)
11398     return false;
11399 
11400   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11401   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11402   unsigned LatestNodeUsed = 0;
11403 
11404   for (unsigned i=0; i < NumStores; ++i) {
11405     // Find a chain for the new wide-store operand. Notice that some
11406     // of the store nodes that we found may not be selected for inclusion
11407     // in the wide store. The chain we use needs to be the chain of the
11408     // latest store node which is *used* and replaced by the wide store.
11409     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11410       LatestNodeUsed = i;
11411   }
11412 
11413   SmallVector<SDValue, 8> Chains;
11414 
11415   // The latest Node in the DAG.
11416   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11417   SDLoc DL(StoreNodes[0].MemNode);
11418 
11419   SDValue StoredVal;
11420   if (UseVector) {
11421     bool IsVec = MemVT.isVector();
11422     unsigned Elts = NumStores;
11423     if (IsVec) {
11424       // When merging vector stores, get the total number of elements.
11425       Elts *= MemVT.getVectorNumElements();
11426     }
11427     // Get the type for the merged vector store.
11428     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11429     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11430 
11431     if (IsConstantSrc) {
11432       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11433     } else {
11434       SmallVector<SDValue, 8> Ops;
11435       for (unsigned i = 0; i < NumStores; ++i) {
11436         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11437         SDValue Val = St->getValue();
11438         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11439         if (Val.getValueType() != MemVT)
11440           return false;
11441         Ops.push_back(Val);
11442         Chains.push_back(St->getChain());
11443       }
11444 
11445       // Build the extracted vector elements back into a vector.
11446       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11447                               DL, Ty, Ops);    }
11448   } else {
11449     // We should always use a vector store when merging extracted vector
11450     // elements, so this path implies a store of constants.
11451     assert(IsConstantSrc && "Merged vector elements should use vector store");
11452 
11453     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11454     APInt StoreInt(SizeInBits, 0);
11455 
11456     // Construct a single integer constant which is made of the smaller
11457     // constant inputs.
11458     bool IsLE = DAG.getDataLayout().isLittleEndian();
11459     for (unsigned i = 0; i < NumStores; ++i) {
11460       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11461       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11462       Chains.push_back(St->getChain());
11463 
11464       SDValue Val = St->getValue();
11465       StoreInt <<= ElementSizeBytes * 8;
11466       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11467         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11468       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11469         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11470       } else {
11471         llvm_unreachable("Invalid constant element type");
11472       }
11473     }
11474 
11475     // Create the new Load and Store operations.
11476     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11477     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11478   }
11479 
11480   assert(!Chains.empty());
11481 
11482   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11483   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11484                                   FirstInChain->getBasePtr(),
11485                                   FirstInChain->getPointerInfo(),
11486                                   FirstInChain->getAlignment());
11487 
11488   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11489                                                   : DAG.getSubtarget().useAA();
11490   if (UseAA) {
11491     // Replace all merged stores with the new store.
11492     for (unsigned i = 0; i < NumStores; ++i)
11493       CombineTo(StoreNodes[i].MemNode, NewStore);
11494   } else {
11495     // Replace the last store with the new store.
11496     CombineTo(LatestOp, NewStore);
11497     // Erase all other stores.
11498     for (unsigned i = 0; i < NumStores; ++i) {
11499       if (StoreNodes[i].MemNode == LatestOp)
11500         continue;
11501       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11502       // ReplaceAllUsesWith will replace all uses that existed when it was
11503       // called, but graph optimizations may cause new ones to appear. For
11504       // example, the case in pr14333 looks like
11505       //
11506       //  St's chain -> St -> another store -> X
11507       //
11508       // And the only difference from St to the other store is the chain.
11509       // When we change it's chain to be St's chain they become identical,
11510       // get CSEed and the net result is that X is now a use of St.
11511       // Since we know that St is redundant, just iterate.
11512       while (!St->use_empty())
11513         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11514       deleteAndRecombine(St);
11515     }
11516   }
11517 
11518   StoreNodes.erase(StoreNodes.begin() + NumStores, StoreNodes.end());
11519   return true;
11520 }
11521 
11522 void DAGCombiner::getStoreMergeAndAliasCandidates(
11523     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11524     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11525   // This holds the base pointer, index, and the offset in bytes from the base
11526   // pointer.
11527   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11528 
11529   // We must have a base and an offset.
11530   if (!BasePtr.Base.getNode())
11531     return;
11532 
11533   // Do not handle stores to undef base pointers.
11534   if (BasePtr.Base.isUndef())
11535     return;
11536 
11537   // Walk up the chain and look for nodes with offsets from the same
11538   // base pointer. Stop when reaching an instruction with a different kind
11539   // or instruction which has a different base pointer.
11540   EVT MemVT = St->getMemoryVT();
11541   unsigned Seq = 0;
11542   StoreSDNode *Index = St;
11543 
11544 
11545   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11546                                                   : DAG.getSubtarget().useAA();
11547 
11548   if (UseAA) {
11549     // Look at other users of the same chain. Stores on the same chain do not
11550     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11551     // to be on the same chain, so don't bother looking at adjacent chains.
11552 
11553     SDValue Chain = St->getChain();
11554     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11555       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11556         if (I.getOperandNo() != 0)
11557           continue;
11558 
11559         if (OtherST->isVolatile() || OtherST->isIndexed())
11560           continue;
11561 
11562         if (OtherST->getMemoryVT() != MemVT)
11563           continue;
11564 
11565         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11566 
11567         if (Ptr.equalBaseIndex(BasePtr))
11568           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11569       }
11570     }
11571 
11572     return;
11573   }
11574 
11575   while (Index) {
11576     // If the chain has more than one use, then we can't reorder the mem ops.
11577     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11578       break;
11579 
11580     // Find the base pointer and offset for this memory node.
11581     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11582 
11583     // Check that the base pointer is the same as the original one.
11584     if (!Ptr.equalBaseIndex(BasePtr))
11585       break;
11586 
11587     // The memory operands must not be volatile.
11588     if (Index->isVolatile() || Index->isIndexed())
11589       break;
11590 
11591     // No truncation.
11592     if (Index->isTruncatingStore())
11593       break;
11594 
11595     // The stored memory type must be the same.
11596     if (Index->getMemoryVT() != MemVT)
11597       break;
11598 
11599     // We do not allow under-aligned stores in order to prevent
11600     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11601     // be irrelevant here; what MATTERS is that we not move memory
11602     // operations that potentially overlap past each-other.
11603     if (Index->getAlignment() < MemVT.getStoreSize())
11604       break;
11605 
11606     // We found a potential memory operand to merge.
11607     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11608 
11609     // Find the next memory operand in the chain. If the next operand in the
11610     // chain is a store then move up and continue the scan with the next
11611     // memory operand. If the next operand is a load save it and use alias
11612     // information to check if it interferes with anything.
11613     SDNode *NextInChain = Index->getChain().getNode();
11614     while (1) {
11615       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11616         // We found a store node. Use it for the next iteration.
11617         Index = STn;
11618         break;
11619       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11620         if (Ldn->isVolatile()) {
11621           Index = nullptr;
11622           break;
11623         }
11624 
11625         // Save the load node for later. Continue the scan.
11626         AliasLoadNodes.push_back(Ldn);
11627         NextInChain = Ldn->getChain().getNode();
11628         continue;
11629       } else {
11630         Index = nullptr;
11631         break;
11632       }
11633     }
11634   }
11635 }
11636 
11637 // We need to check that merging these stores does not cause a loop
11638 // in the DAG. Any store candidate may depend on another candidate
11639 // indirectly through its operand (we already consider dependencies
11640 // through the chain). Check in parallel by searching up from
11641 // non-chain operands of candidates.
11642 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11643     SmallVectorImpl<MemOpLink> &StoreNodes) {
11644   SmallPtrSet<const SDNode *, 16> Visited;
11645   SmallVector<const SDNode *, 8> Worklist;
11646   // search ops of store candidates
11647   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11648     SDNode *n = StoreNodes[i].MemNode;
11649     // Potential loops may happen only through non-chain operands
11650     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11651       Worklist.push_back(n->getOperand(j).getNode());
11652   }
11653   // search through DAG. We can stop early if we find a storenode
11654   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11655     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11656       return false;
11657   }
11658   return true;
11659 }
11660 
11661 bool DAGCombiner::MergeConsecutiveStores(
11662     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes) {
11663   if (OptLevel == CodeGenOpt::None)
11664     return false;
11665 
11666   EVT MemVT = St->getMemoryVT();
11667   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11668   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11669       Attribute::NoImplicitFloat);
11670 
11671   // This function cannot currently deal with non-byte-sized memory sizes.
11672   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11673     return false;
11674 
11675   if (!MemVT.isSimple())
11676     return false;
11677 
11678   // Perform an early exit check. Do not bother looking at stored values that
11679   // are not constants, loads, or extracted vector elements.
11680   SDValue StoredVal = St->getValue();
11681   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11682   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11683                        isa<ConstantFPSDNode>(StoredVal);
11684   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11685                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11686 
11687   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11688     return false;
11689 
11690   // Don't merge vectors into wider vectors if the source data comes from loads.
11691   // TODO: This restriction can be lifted by using logic similar to the
11692   // ExtractVecSrc case.
11693   if (MemVT.isVector() && IsLoadSrc)
11694     return false;
11695 
11696   // Only look at ends of store sequences.
11697   SDValue Chain = SDValue(St, 0);
11698   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11699     return false;
11700 
11701   // Save the LoadSDNodes that we find in the chain.
11702   // We need to make sure that these nodes do not interfere with
11703   // any of the store nodes.
11704   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11705 
11706   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11707 
11708   // Check if there is anything to merge.
11709   if (StoreNodes.size() < 2)
11710     return false;
11711 
11712   // only do dependence check in AA case
11713   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11714                                                   : DAG.getSubtarget().useAA();
11715   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11716     return false;
11717 
11718   // Sort the memory operands according to their distance from the
11719   // base pointer.  As a secondary criteria: make sure stores coming
11720   // later in the code come first in the list. This is important for
11721   // the non-UseAA case, because we're merging stores into the FINAL
11722   // store along a chain which potentially contains aliasing stores.
11723   // Thus, if there are multiple stores to the same address, the last
11724   // one can be considered for merging but not the others.
11725   std::sort(StoreNodes.begin(), StoreNodes.end(),
11726             [](MemOpLink LHS, MemOpLink RHS) {
11727     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11728            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11729             LHS.SequenceNum < RHS.SequenceNum);
11730   });
11731 
11732   // Scan the memory operations on the chain and find the first non-consecutive
11733   // store memory address.
11734   unsigned LastConsecutiveStore = 0;
11735   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11736   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11737 
11738     // Check that the addresses are consecutive starting from the second
11739     // element in the list of stores.
11740     if (i > 0) {
11741       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11742       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11743         break;
11744     }
11745 
11746     // Check if this store interferes with any of the loads that we found.
11747     // If we find a load that alias with this store. Stop the sequence.
11748     if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) {
11749           return isAlias(Ldn, StoreNodes[i].MemNode);
11750         }))
11751       break;
11752 
11753     // Mark this node as useful.
11754     LastConsecutiveStore = i;
11755   }
11756 
11757   // The node with the lowest store address.
11758   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11759   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11760   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11761   LLVMContext &Context = *DAG.getContext();
11762   const DataLayout &DL = DAG.getDataLayout();
11763 
11764   // Store the constants into memory as one consecutive store.
11765   if (IsConstantSrc) {
11766     unsigned LastLegalType = 0;
11767     unsigned LastLegalVectorType = 0;
11768     bool NonZero = false;
11769     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11770       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11771       SDValue StoredVal = St->getValue();
11772 
11773       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11774         NonZero |= !C->isNullValue();
11775       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11776         NonZero |= !C->getConstantFPValue()->isNullValue();
11777       } else {
11778         // Non-constant.
11779         break;
11780       }
11781 
11782       // Find a legal type for the constant store.
11783       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11784       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11785       bool IsFast;
11786       if (TLI.isTypeLegal(StoreTy) &&
11787           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11788                                  FirstStoreAlign, &IsFast) && IsFast) {
11789         LastLegalType = i+1;
11790       // Or check whether a truncstore is legal.
11791       } else if (TLI.getTypeAction(Context, StoreTy) ==
11792                  TargetLowering::TypePromoteInteger) {
11793         EVT LegalizedStoredValueTy =
11794           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11795         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11796             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11797                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11798             IsFast) {
11799           LastLegalType = i + 1;
11800         }
11801       }
11802 
11803       // We only use vectors if the constant is known to be zero or the target
11804       // allows it and the function is not marked with the noimplicitfloat
11805       // attribute.
11806       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11807                                                         FirstStoreAS)) &&
11808           !NoVectors) {
11809         // Find a legal type for the vector store.
11810         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11811         if (TLI.isTypeLegal(Ty) &&
11812             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11813                                    FirstStoreAlign, &IsFast) && IsFast)
11814           LastLegalVectorType = i + 1;
11815       }
11816     }
11817 
11818     // Check if we found a legal integer type to store.
11819     if (LastLegalType == 0 && LastLegalVectorType == 0)
11820       return false;
11821 
11822     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11823     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11824 
11825     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11826                                            true, UseVector);
11827   }
11828 
11829   // When extracting multiple vector elements, try to store them
11830   // in one vector store rather than a sequence of scalar stores.
11831   if (IsExtractVecSrc) {
11832     unsigned NumStoresToMerge = 0;
11833     bool IsVec = MemVT.isVector();
11834     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11835       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11836       unsigned StoreValOpcode = St->getValue().getOpcode();
11837       // This restriction could be loosened.
11838       // Bail out if any stored values are not elements extracted from a vector.
11839       // It should be possible to handle mixed sources, but load sources need
11840       // more careful handling (see the block of code below that handles
11841       // consecutive loads).
11842       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11843           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11844         return false;
11845 
11846       // Find a legal type for the vector store.
11847       unsigned Elts = i + 1;
11848       if (IsVec) {
11849         // When merging vector stores, get the total number of elements.
11850         Elts *= MemVT.getVectorNumElements();
11851       }
11852       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11853       bool IsFast;
11854       if (TLI.isTypeLegal(Ty) &&
11855           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11856                                  FirstStoreAlign, &IsFast) && IsFast)
11857         NumStoresToMerge = i + 1;
11858     }
11859 
11860     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11861                                            false, true);
11862   }
11863 
11864   // Below we handle the case of multiple consecutive stores that
11865   // come from multiple consecutive loads. We merge them into a single
11866   // wide load and a single wide store.
11867 
11868   // Look for load nodes which are used by the stored values.
11869   SmallVector<MemOpLink, 8> LoadNodes;
11870 
11871   // Find acceptable loads. Loads need to have the same chain (token factor),
11872   // must not be zext, volatile, indexed, and they must be consecutive.
11873   BaseIndexOffset LdBasePtr;
11874   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11875     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11876     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11877     if (!Ld) break;
11878 
11879     // Loads must only have one use.
11880     if (!Ld->hasNUsesOfValue(1, 0))
11881       break;
11882 
11883     // The memory operands must not be volatile.
11884     if (Ld->isVolatile() || Ld->isIndexed())
11885       break;
11886 
11887     // We do not accept ext loads.
11888     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11889       break;
11890 
11891     // The stored memory type must be the same.
11892     if (Ld->getMemoryVT() != MemVT)
11893       break;
11894 
11895     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11896     // If this is not the first ptr that we check.
11897     if (LdBasePtr.Base.getNode()) {
11898       // The base ptr must be the same.
11899       if (!LdPtr.equalBaseIndex(LdBasePtr))
11900         break;
11901     } else {
11902       // Check that all other base pointers are the same as this one.
11903       LdBasePtr = LdPtr;
11904     }
11905 
11906     // We found a potential memory operand to merge.
11907     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11908   }
11909 
11910   if (LoadNodes.size() < 2)
11911     return false;
11912 
11913   // If we have load/store pair instructions and we only have two values,
11914   // don't bother.
11915   unsigned RequiredAlignment;
11916   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11917       St->getAlignment() >= RequiredAlignment)
11918     return false;
11919 
11920   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11921   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11922   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11923 
11924   // Scan the memory operations on the chain and find the first non-consecutive
11925   // load memory address. These variables hold the index in the store node
11926   // array.
11927   unsigned LastConsecutiveLoad = 0;
11928   // This variable refers to the size and not index in the array.
11929   unsigned LastLegalVectorType = 0;
11930   unsigned LastLegalIntegerType = 0;
11931   StartAddress = LoadNodes[0].OffsetFromBase;
11932   SDValue FirstChain = FirstLoad->getChain();
11933   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11934     // All loads must share the same chain.
11935     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11936       break;
11937 
11938     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11939     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11940       break;
11941     LastConsecutiveLoad = i;
11942     // Find a legal type for the vector store.
11943     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11944     bool IsFastSt, IsFastLd;
11945     if (TLI.isTypeLegal(StoreTy) &&
11946         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11947                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11948         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11949                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11950       LastLegalVectorType = i + 1;
11951     }
11952 
11953     // Find a legal type for the integer store.
11954     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11955     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11956     if (TLI.isTypeLegal(StoreTy) &&
11957         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11958                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11959         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11960                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11961       LastLegalIntegerType = i + 1;
11962     // Or check whether a truncstore and extload is legal.
11963     else if (TLI.getTypeAction(Context, StoreTy) ==
11964              TargetLowering::TypePromoteInteger) {
11965       EVT LegalizedStoredValueTy =
11966         TLI.getTypeToTransformTo(Context, StoreTy);
11967       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11968           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11969           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11970           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11971           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11972                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11973           IsFastSt &&
11974           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11975                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11976           IsFastLd)
11977         LastLegalIntegerType = i+1;
11978     }
11979   }
11980 
11981   // Only use vector types if the vector type is larger than the integer type.
11982   // If they are the same, use integers.
11983   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11984   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11985 
11986   // We add +1 here because the LastXXX variables refer to location while
11987   // the NumElem refers to array/index size.
11988   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11989   NumElem = std::min(LastLegalType, NumElem);
11990 
11991   if (NumElem < 2)
11992     return false;
11993 
11994   // Collect the chains from all merged stores.
11995   SmallVector<SDValue, 8> MergeStoreChains;
11996   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11997 
11998   // The latest Node in the DAG.
11999   unsigned LatestNodeUsed = 0;
12000   for (unsigned i=1; i<NumElem; ++i) {
12001     // Find a chain for the new wide-store operand. Notice that some
12002     // of the store nodes that we found may not be selected for inclusion
12003     // in the wide store. The chain we use needs to be the chain of the
12004     // latest store node which is *used* and replaced by the wide store.
12005     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
12006       LatestNodeUsed = i;
12007 
12008     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
12009   }
12010 
12011   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
12012 
12013   // Find if it is better to use vectors or integers to load and store
12014   // to memory.
12015   EVT JointMemOpVT;
12016   if (UseVectorTy) {
12017     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12018   } else {
12019     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12020     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12021   }
12022 
12023   SDLoc LoadDL(LoadNodes[0].MemNode);
12024   SDLoc StoreDL(StoreNodes[0].MemNode);
12025 
12026   // The merged loads are required to have the same incoming chain, so
12027   // using the first's chain is acceptable.
12028   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12029                                 FirstLoad->getBasePtr(),
12030                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
12031 
12032   SDValue NewStoreChain =
12033     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
12034 
12035   SDValue NewStore =
12036       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12037                    FirstInChain->getPointerInfo(), FirstStoreAlign);
12038 
12039   // Transfer chain users from old loads to the new load.
12040   for (unsigned i = 0; i < NumElem; ++i) {
12041     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12042     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12043                                   SDValue(NewLoad.getNode(), 1));
12044   }
12045 
12046   if (UseAA) {
12047     // Replace the all stores with the new store.
12048     for (unsigned i = 0; i < NumElem; ++i)
12049       CombineTo(StoreNodes[i].MemNode, NewStore);
12050   } else {
12051     // Replace the last store with the new store.
12052     CombineTo(LatestOp, NewStore);
12053     // Erase all other stores.
12054     for (unsigned i = 0; i < NumElem; ++i) {
12055       // Remove all Store nodes.
12056       if (StoreNodes[i].MemNode == LatestOp)
12057         continue;
12058       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12059       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
12060       deleteAndRecombine(St);
12061     }
12062   }
12063 
12064   StoreNodes.erase(StoreNodes.begin() + NumElem, StoreNodes.end());
12065   return true;
12066 }
12067 
12068 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12069   SDLoc SL(ST);
12070   SDValue ReplStore;
12071 
12072   // Replace the chain to avoid dependency.
12073   if (ST->isTruncatingStore()) {
12074     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12075                                   ST->getBasePtr(), ST->getMemoryVT(),
12076                                   ST->getMemOperand());
12077   } else {
12078     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12079                              ST->getMemOperand());
12080   }
12081 
12082   // Create token to keep both nodes around.
12083   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12084                               MVT::Other, ST->getChain(), ReplStore);
12085 
12086   // Make sure the new and old chains are cleaned up.
12087   AddToWorklist(Token.getNode());
12088 
12089   // Don't add users to work list.
12090   return CombineTo(ST, Token, false);
12091 }
12092 
12093 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12094   SDValue Value = ST->getValue();
12095   if (Value.getOpcode() == ISD::TargetConstantFP)
12096     return SDValue();
12097 
12098   SDLoc DL(ST);
12099 
12100   SDValue Chain = ST->getChain();
12101   SDValue Ptr = ST->getBasePtr();
12102 
12103   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12104 
12105   // NOTE: If the original store is volatile, this transform must not increase
12106   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12107   // processor operation but an i64 (which is not legal) requires two.  So the
12108   // transform should not be done in this case.
12109 
12110   SDValue Tmp;
12111   switch (CFP->getSimpleValueType(0).SimpleTy) {
12112   default:
12113     llvm_unreachable("Unknown FP type");
12114   case MVT::f16:    // We don't do this for these yet.
12115   case MVT::f80:
12116   case MVT::f128:
12117   case MVT::ppcf128:
12118     return SDValue();
12119   case MVT::f32:
12120     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12121         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12122       ;
12123       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12124                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12125                             MVT::i32);
12126       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12127     }
12128 
12129     return SDValue();
12130   case MVT::f64:
12131     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12132          !ST->isVolatile()) ||
12133         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12134       ;
12135       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12136                             getZExtValue(), SDLoc(CFP), MVT::i64);
12137       return DAG.getStore(Chain, DL, Tmp,
12138                           Ptr, ST->getMemOperand());
12139     }
12140 
12141     if (!ST->isVolatile() &&
12142         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12143       // Many FP stores are not made apparent until after legalize, e.g. for
12144       // argument passing.  Since this is so common, custom legalize the
12145       // 64-bit integer store into two 32-bit stores.
12146       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12147       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12148       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12149       if (DAG.getDataLayout().isBigEndian())
12150         std::swap(Lo, Hi);
12151 
12152       unsigned Alignment = ST->getAlignment();
12153       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12154       AAMDNodes AAInfo = ST->getAAInfo();
12155 
12156       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12157                                  ST->getAlignment(), MMOFlags, AAInfo);
12158       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12159                         DAG.getConstant(4, DL, Ptr.getValueType()));
12160       Alignment = MinAlign(Alignment, 4U);
12161       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12162                                  ST->getPointerInfo().getWithOffset(4),
12163                                  Alignment, MMOFlags, AAInfo);
12164       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12165                          St0, St1);
12166     }
12167 
12168     return SDValue();
12169   }
12170 }
12171 
12172 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12173   StoreSDNode *ST  = cast<StoreSDNode>(N);
12174   SDValue Chain = ST->getChain();
12175   SDValue Value = ST->getValue();
12176   SDValue Ptr   = ST->getBasePtr();
12177 
12178   // If this is a store of a bit convert, store the input value if the
12179   // resultant store does not need a higher alignment than the original.
12180   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12181       ST->isUnindexed()) {
12182     EVT SVT = Value.getOperand(0).getValueType();
12183     if (((!LegalOperations && !ST->isVolatile()) ||
12184          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12185         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12186       unsigned OrigAlign = ST->getAlignment();
12187       bool Fast = false;
12188       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12189                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12190           Fast) {
12191         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12192                             ST->getPointerInfo(), OrigAlign,
12193                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12194       }
12195     }
12196   }
12197 
12198   // Turn 'store undef, Ptr' -> nothing.
12199   if (Value.isUndef() && ST->isUnindexed())
12200     return Chain;
12201 
12202   // Try to infer better alignment information than the store already has.
12203   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12204     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12205       if (Align > ST->getAlignment()) {
12206         SDValue NewStore =
12207             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12208                               ST->getMemoryVT(), Align,
12209                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12210         if (NewStore.getNode() != N)
12211           return CombineTo(ST, NewStore, true);
12212       }
12213     }
12214   }
12215 
12216   // Try transforming a pair floating point load / store ops to integer
12217   // load / store ops.
12218   if (SDValue NewST = TransformFPLoadStorePair(N))
12219     return NewST;
12220 
12221   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12222                                                   : DAG.getSubtarget().useAA();
12223 #ifndef NDEBUG
12224   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12225       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12226     UseAA = false;
12227 #endif
12228   if (UseAA && ST->isUnindexed()) {
12229     // FIXME: We should do this even without AA enabled. AA will just allow
12230     // FindBetterChain to work in more situations. The problem with this is that
12231     // any combine that expects memory operations to be on consecutive chains
12232     // first needs to be updated to look for users of the same chain.
12233 
12234     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12235     // adjacent stores.
12236     if (findBetterNeighborChains(ST)) {
12237       // replaceStoreChain uses CombineTo, which handled all of the worklist
12238       // manipulation. Return the original node to not do anything else.
12239       return SDValue(ST, 0);
12240     }
12241     Chain = ST->getChain();
12242   }
12243 
12244   // Try transforming N to an indexed store.
12245   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12246     return SDValue(N, 0);
12247 
12248   // FIXME: is there such a thing as a truncating indexed store?
12249   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12250       Value.getValueType().isInteger()) {
12251     // See if we can simplify the input to this truncstore with knowledge that
12252     // only the low bits are being used.  For example:
12253     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12254     SDValue Shorter = GetDemandedBits(
12255         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12256                                     ST->getMemoryVT().getScalarSizeInBits()));
12257     AddToWorklist(Value.getNode());
12258     if (Shorter.getNode())
12259       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12260                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12261 
12262     // Otherwise, see if we can simplify the operation with
12263     // SimplifyDemandedBits, which only works if the value has a single use.
12264     if (SimplifyDemandedBits(
12265             Value,
12266             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12267                                  ST->getMemoryVT().getScalarSizeInBits())))
12268       return SDValue(N, 0);
12269   }
12270 
12271   // If this is a load followed by a store to the same location, then the store
12272   // is dead/noop.
12273   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12274     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12275         ST->isUnindexed() && !ST->isVolatile() &&
12276         // There can't be any side effects between the load and store, such as
12277         // a call or store.
12278         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12279       // The store is dead, remove it.
12280       return Chain;
12281     }
12282   }
12283 
12284   // If this is a store followed by a store with the same value to the same
12285   // location, then the store is dead/noop.
12286   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12287     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12288         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12289         ST1->isUnindexed() && !ST1->isVolatile()) {
12290       // The store is dead, remove it.
12291       return Chain;
12292     }
12293   }
12294 
12295   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12296   // truncating store.  We can do this even if this is already a truncstore.
12297   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12298       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12299       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12300                             ST->getMemoryVT())) {
12301     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12302                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12303   }
12304 
12305   // Only perform this optimization before the types are legal, because we
12306   // don't want to perform this optimization on every DAGCombine invocation.
12307   if (!LegalTypes) {
12308     for (;;) {
12309       // There can be multiple store sequences on the same chain.
12310       // Keep trying to merge store sequences until we are unable to do so
12311       // or until we merge the last store on the chain.
12312       SmallVector<MemOpLink, 8> StoreNodes;
12313       bool Changed = MergeConsecutiveStores(ST, StoreNodes);
12314       if (!Changed) break;
12315 
12316       if (any_of(StoreNodes,
12317                  [ST](const MemOpLink &Link) { return Link.MemNode == ST; })) {
12318         // ST has been merged and no longer exists.
12319         return SDValue(N, 0);
12320       }
12321     }
12322   }
12323 
12324   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12325   //
12326   // Make sure to do this only after attempting to merge stores in order to
12327   //  avoid changing the types of some subset of stores due to visit order,
12328   //  preventing their merging.
12329   if (isa<ConstantFPSDNode>(Value)) {
12330     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12331       return NewSt;
12332   }
12333 
12334   if (SDValue NewSt = splitMergedValStore(ST))
12335     return NewSt;
12336 
12337   return ReduceLoadOpStoreWidth(N);
12338 }
12339 
12340 /// For the instruction sequence of store below, F and I values
12341 /// are bundled together as an i64 value before being stored into memory.
12342 /// Sometimes it is more efficent to generate separate stores for F and I,
12343 /// which can remove the bitwise instructions or sink them to colder places.
12344 ///
12345 ///   (store (or (zext (bitcast F to i32) to i64),
12346 ///              (shl (zext I to i64), 32)), addr)  -->
12347 ///   (store F, addr) and (store I, addr+4)
12348 ///
12349 /// Similarly, splitting for other merged store can also be beneficial, like:
12350 /// For pair of {i32, i32}, i64 store --> two i32 stores.
12351 /// For pair of {i32, i16}, i64 store --> two i32 stores.
12352 /// For pair of {i16, i16}, i32 store --> two i16 stores.
12353 /// For pair of {i16, i8},  i32 store --> two i16 stores.
12354 /// For pair of {i8, i8},   i16 store --> two i8 stores.
12355 ///
12356 /// We allow each target to determine specifically which kind of splitting is
12357 /// supported.
12358 ///
12359 /// The store patterns are commonly seen from the simple code snippet below
12360 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
12361 ///   void goo(const std::pair<int, float> &);
12362 ///   hoo() {
12363 ///     ...
12364 ///     goo(std::make_pair(tmp, ftmp));
12365 ///     ...
12366 ///   }
12367 ///
12368 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
12369   if (OptLevel == CodeGenOpt::None)
12370     return SDValue();
12371 
12372   SDValue Val = ST->getValue();
12373   SDLoc DL(ST);
12374 
12375   // Match OR operand.
12376   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
12377     return SDValue();
12378 
12379   // Match SHL operand and get Lower and Higher parts of Val.
12380   SDValue Op1 = Val.getOperand(0);
12381   SDValue Op2 = Val.getOperand(1);
12382   SDValue Lo, Hi;
12383   if (Op1.getOpcode() != ISD::SHL) {
12384     std::swap(Op1, Op2);
12385     if (Op1.getOpcode() != ISD::SHL)
12386       return SDValue();
12387   }
12388   Lo = Op2;
12389   Hi = Op1.getOperand(0);
12390   if (!Op1.hasOneUse())
12391     return SDValue();
12392 
12393   // Match shift amount to HalfValBitSize.
12394   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
12395   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
12396   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
12397     return SDValue();
12398 
12399   // Lo and Hi are zero-extended from int with size less equal than 32
12400   // to i64.
12401   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
12402       !Lo.getOperand(0).getValueType().isScalarInteger() ||
12403       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
12404       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
12405       !Hi.getOperand(0).getValueType().isScalarInteger() ||
12406       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
12407     return SDValue();
12408 
12409   if (!TLI.isMultiStoresCheaperThanBitsMerge(Lo.getOperand(0),
12410                                              Hi.getOperand(0)))
12411     return SDValue();
12412 
12413   // Start to split store.
12414   unsigned Alignment = ST->getAlignment();
12415   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12416   AAMDNodes AAInfo = ST->getAAInfo();
12417 
12418   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
12419   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
12420   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
12421   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
12422 
12423   SDValue Chain = ST->getChain();
12424   SDValue Ptr = ST->getBasePtr();
12425   // Lower value store.
12426   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12427                              ST->getAlignment(), MMOFlags, AAInfo);
12428   Ptr =
12429       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12430                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
12431   // Higher value store.
12432   SDValue St1 =
12433       DAG.getStore(St0, DL, Hi, Ptr,
12434                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
12435                    Alignment / 2, MMOFlags, AAInfo);
12436   return St1;
12437 }
12438 
12439 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12440   SDValue InVec = N->getOperand(0);
12441   SDValue InVal = N->getOperand(1);
12442   SDValue EltNo = N->getOperand(2);
12443   SDLoc DL(N);
12444 
12445   // If the inserted element is an UNDEF, just use the input vector.
12446   if (InVal.isUndef())
12447     return InVec;
12448 
12449   EVT VT = InVec.getValueType();
12450 
12451   // If we can't generate a legal BUILD_VECTOR, exit
12452   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12453     return SDValue();
12454 
12455   // Check that we know which element is being inserted
12456   if (!isa<ConstantSDNode>(EltNo))
12457     return SDValue();
12458   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12459 
12460   // Canonicalize insert_vector_elt dag nodes.
12461   // Example:
12462   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12463   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12464   //
12465   // Do this only if the child insert_vector node has one use; also
12466   // do this only if indices are both constants and Idx1 < Idx0.
12467   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12468       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12469     unsigned OtherElt =
12470       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12471     if (Elt < OtherElt) {
12472       // Swap nodes.
12473       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
12474                                   InVec.getOperand(0), InVal, EltNo);
12475       AddToWorklist(NewOp.getNode());
12476       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12477                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12478     }
12479   }
12480 
12481   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12482   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12483   // vector elements.
12484   SmallVector<SDValue, 8> Ops;
12485   // Do not combine these two vectors if the output vector will not replace
12486   // the input vector.
12487   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12488     Ops.append(InVec.getNode()->op_begin(),
12489                InVec.getNode()->op_end());
12490   } else if (InVec.isUndef()) {
12491     unsigned NElts = VT.getVectorNumElements();
12492     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12493   } else {
12494     return SDValue();
12495   }
12496 
12497   // Insert the element
12498   if (Elt < Ops.size()) {
12499     // All the operands of BUILD_VECTOR must have the same type;
12500     // we enforce that here.
12501     EVT OpVT = Ops[0].getValueType();
12502     if (InVal.getValueType() != OpVT)
12503       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12504                 DAG.getNode(ISD::ANY_EXTEND, DL, OpVT, InVal) :
12505                 DAG.getNode(ISD::TRUNCATE, DL, OpVT, InVal);
12506     Ops[Elt] = InVal;
12507   }
12508 
12509   // Return the new vector
12510   return DAG.getBuildVector(VT, DL, Ops);
12511 }
12512 
12513 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12514     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12515   assert(!OriginalLoad->isVolatile());
12516 
12517   EVT ResultVT = EVE->getValueType(0);
12518   EVT VecEltVT = InVecVT.getVectorElementType();
12519   unsigned Align = OriginalLoad->getAlignment();
12520   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12521       VecEltVT.getTypeForEVT(*DAG.getContext()));
12522 
12523   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12524     return SDValue();
12525 
12526   Align = NewAlign;
12527 
12528   SDValue NewPtr = OriginalLoad->getBasePtr();
12529   SDValue Offset;
12530   EVT PtrType = NewPtr.getValueType();
12531   MachinePointerInfo MPI;
12532   SDLoc DL(EVE);
12533   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12534     int Elt = ConstEltNo->getZExtValue();
12535     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12536     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12537     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12538   } else {
12539     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12540     Offset = DAG.getNode(
12541         ISD::MUL, DL, PtrType, Offset,
12542         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12543     MPI = OriginalLoad->getPointerInfo();
12544   }
12545   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12546 
12547   // The replacement we need to do here is a little tricky: we need to
12548   // replace an extractelement of a load with a load.
12549   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12550   // Note that this replacement assumes that the extractvalue is the only
12551   // use of the load; that's okay because we don't want to perform this
12552   // transformation in other cases anyway.
12553   SDValue Load;
12554   SDValue Chain;
12555   if (ResultVT.bitsGT(VecEltVT)) {
12556     // If the result type of vextract is wider than the load, then issue an
12557     // extending load instead.
12558     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12559                                                   VecEltVT)
12560                                    ? ISD::ZEXTLOAD
12561                                    : ISD::EXTLOAD;
12562     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12563                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12564                           Align, OriginalLoad->getMemOperand()->getFlags(),
12565                           OriginalLoad->getAAInfo());
12566     Chain = Load.getValue(1);
12567   } else {
12568     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12569                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12570                        OriginalLoad->getAAInfo());
12571     Chain = Load.getValue(1);
12572     if (ResultVT.bitsLT(VecEltVT))
12573       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12574     else
12575       Load = DAG.getBitcast(ResultVT, Load);
12576   }
12577   WorklistRemover DeadNodes(*this);
12578   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12579   SDValue To[] = { Load, Chain };
12580   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12581   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12582   // worklist explicitly as well.
12583   AddToWorklist(Load.getNode());
12584   AddUsersToWorklist(Load.getNode()); // Add users too
12585   // Make sure to revisit this node to clean it up; it will usually be dead.
12586   AddToWorklist(EVE);
12587   ++OpsNarrowed;
12588   return SDValue(EVE, 0);
12589 }
12590 
12591 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12592   // (vextract (scalar_to_vector val, 0) -> val
12593   SDValue InVec = N->getOperand(0);
12594   EVT VT = InVec.getValueType();
12595   EVT NVT = N->getValueType(0);
12596 
12597   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12598     // Check if the result type doesn't match the inserted element type. A
12599     // SCALAR_TO_VECTOR may truncate the inserted element and the
12600     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12601     SDValue InOp = InVec.getOperand(0);
12602     if (InOp.getValueType() != NVT) {
12603       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12604       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12605     }
12606     return InOp;
12607   }
12608 
12609   SDValue EltNo = N->getOperand(1);
12610   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12611 
12612   // extract_vector_elt (build_vector x, y), 1 -> y
12613   if (ConstEltNo &&
12614       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12615       TLI.isTypeLegal(VT) &&
12616       (InVec.hasOneUse() ||
12617        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12618     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12619     EVT InEltVT = Elt.getValueType();
12620 
12621     // Sometimes build_vector's scalar input types do not match result type.
12622     if (NVT == InEltVT)
12623       return Elt;
12624 
12625     // TODO: It may be useful to truncate if free if the build_vector implicitly
12626     // converts.
12627   }
12628 
12629   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12630   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12631       ConstEltNo->isNullValue() && VT.isInteger()) {
12632     SDValue BCSrc = InVec.getOperand(0);
12633     if (BCSrc.getValueType().isScalarInteger())
12634       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12635   }
12636 
12637   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12638   //
12639   // This only really matters if the index is non-constant since other combines
12640   // on the constant elements already work.
12641   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12642       EltNo == InVec.getOperand(2)) {
12643     SDValue Elt = InVec.getOperand(1);
12644     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12645   }
12646 
12647   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12648   // We only perform this optimization before the op legalization phase because
12649   // we may introduce new vector instructions which are not backed by TD
12650   // patterns. For example on AVX, extracting elements from a wide vector
12651   // without using extract_subvector. However, if we can find an underlying
12652   // scalar value, then we can always use that.
12653   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12654     int NumElem = VT.getVectorNumElements();
12655     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12656     // Find the new index to extract from.
12657     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12658 
12659     // Extracting an undef index is undef.
12660     if (OrigElt == -1)
12661       return DAG.getUNDEF(NVT);
12662 
12663     // Select the right vector half to extract from.
12664     SDValue SVInVec;
12665     if (OrigElt < NumElem) {
12666       SVInVec = InVec->getOperand(0);
12667     } else {
12668       SVInVec = InVec->getOperand(1);
12669       OrigElt -= NumElem;
12670     }
12671 
12672     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12673       SDValue InOp = SVInVec.getOperand(OrigElt);
12674       if (InOp.getValueType() != NVT) {
12675         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12676         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12677       }
12678 
12679       return InOp;
12680     }
12681 
12682     // FIXME: We should handle recursing on other vector shuffles and
12683     // scalar_to_vector here as well.
12684 
12685     if (!LegalOperations) {
12686       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12687       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12688                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12689     }
12690   }
12691 
12692   bool BCNumEltsChanged = false;
12693   EVT ExtVT = VT.getVectorElementType();
12694   EVT LVT = ExtVT;
12695 
12696   // If the result of load has to be truncated, then it's not necessarily
12697   // profitable.
12698   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12699     return SDValue();
12700 
12701   if (InVec.getOpcode() == ISD::BITCAST) {
12702     // Don't duplicate a load with other uses.
12703     if (!InVec.hasOneUse())
12704       return SDValue();
12705 
12706     EVT BCVT = InVec.getOperand(0).getValueType();
12707     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12708       return SDValue();
12709     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12710       BCNumEltsChanged = true;
12711     InVec = InVec.getOperand(0);
12712     ExtVT = BCVT.getVectorElementType();
12713   }
12714 
12715   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12716   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12717       ISD::isNormalLoad(InVec.getNode()) &&
12718       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12719     SDValue Index = N->getOperand(1);
12720     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12721       if (!OrigLoad->isVolatile()) {
12722         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12723                                                              OrigLoad);
12724       }
12725     }
12726   }
12727 
12728   // Perform only after legalization to ensure build_vector / vector_shuffle
12729   // optimizations have already been done.
12730   if (!LegalOperations) return SDValue();
12731 
12732   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12733   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12734   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12735 
12736   if (ConstEltNo) {
12737     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12738 
12739     LoadSDNode *LN0 = nullptr;
12740     const ShuffleVectorSDNode *SVN = nullptr;
12741     if (ISD::isNormalLoad(InVec.getNode())) {
12742       LN0 = cast<LoadSDNode>(InVec);
12743     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12744                InVec.getOperand(0).getValueType() == ExtVT &&
12745                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12746       // Don't duplicate a load with other uses.
12747       if (!InVec.hasOneUse())
12748         return SDValue();
12749 
12750       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12751     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12752       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12753       // =>
12754       // (load $addr+1*size)
12755 
12756       // Don't duplicate a load with other uses.
12757       if (!InVec.hasOneUse())
12758         return SDValue();
12759 
12760       // If the bit convert changed the number of elements, it is unsafe
12761       // to examine the mask.
12762       if (BCNumEltsChanged)
12763         return SDValue();
12764 
12765       // Select the input vector, guarding against out of range extract vector.
12766       unsigned NumElems = VT.getVectorNumElements();
12767       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12768       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12769 
12770       if (InVec.getOpcode() == ISD::BITCAST) {
12771         // Don't duplicate a load with other uses.
12772         if (!InVec.hasOneUse())
12773           return SDValue();
12774 
12775         InVec = InVec.getOperand(0);
12776       }
12777       if (ISD::isNormalLoad(InVec.getNode())) {
12778         LN0 = cast<LoadSDNode>(InVec);
12779         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12780         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12781       }
12782     }
12783 
12784     // Make sure we found a non-volatile load and the extractelement is
12785     // the only use.
12786     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12787       return SDValue();
12788 
12789     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12790     if (Elt == -1)
12791       return DAG.getUNDEF(LVT);
12792 
12793     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12794   }
12795 
12796   return SDValue();
12797 }
12798 
12799 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12800 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12801   // We perform this optimization post type-legalization because
12802   // the type-legalizer often scalarizes integer-promoted vectors.
12803   // Performing this optimization before may create bit-casts which
12804   // will be type-legalized to complex code sequences.
12805   // We perform this optimization only before the operation legalizer because we
12806   // may introduce illegal operations.
12807   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12808     return SDValue();
12809 
12810   unsigned NumInScalars = N->getNumOperands();
12811   SDLoc DL(N);
12812   EVT VT = N->getValueType(0);
12813 
12814   // Check to see if this is a BUILD_VECTOR of a bunch of values
12815   // which come from any_extend or zero_extend nodes. If so, we can create
12816   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12817   // optimizations. We do not handle sign-extend because we can't fill the sign
12818   // using shuffles.
12819   EVT SourceType = MVT::Other;
12820   bool AllAnyExt = true;
12821 
12822   for (unsigned i = 0; i != NumInScalars; ++i) {
12823     SDValue In = N->getOperand(i);
12824     // Ignore undef inputs.
12825     if (In.isUndef()) continue;
12826 
12827     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12828     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12829 
12830     // Abort if the element is not an extension.
12831     if (!ZeroExt && !AnyExt) {
12832       SourceType = MVT::Other;
12833       break;
12834     }
12835 
12836     // The input is a ZeroExt or AnyExt. Check the original type.
12837     EVT InTy = In.getOperand(0).getValueType();
12838 
12839     // Check that all of the widened source types are the same.
12840     if (SourceType == MVT::Other)
12841       // First time.
12842       SourceType = InTy;
12843     else if (InTy != SourceType) {
12844       // Multiple income types. Abort.
12845       SourceType = MVT::Other;
12846       break;
12847     }
12848 
12849     // Check if all of the extends are ANY_EXTENDs.
12850     AllAnyExt &= AnyExt;
12851   }
12852 
12853   // In order to have valid types, all of the inputs must be extended from the
12854   // same source type and all of the inputs must be any or zero extend.
12855   // Scalar sizes must be a power of two.
12856   EVT OutScalarTy = VT.getScalarType();
12857   bool ValidTypes = SourceType != MVT::Other &&
12858                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12859                  isPowerOf2_32(SourceType.getSizeInBits());
12860 
12861   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12862   // turn into a single shuffle instruction.
12863   if (!ValidTypes)
12864     return SDValue();
12865 
12866   bool isLE = DAG.getDataLayout().isLittleEndian();
12867   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12868   assert(ElemRatio > 1 && "Invalid element size ratio");
12869   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12870                                DAG.getConstant(0, DL, SourceType);
12871 
12872   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12873   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12874 
12875   // Populate the new build_vector
12876   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12877     SDValue Cast = N->getOperand(i);
12878     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12879             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12880             Cast.isUndef()) && "Invalid cast opcode");
12881     SDValue In;
12882     if (Cast.isUndef())
12883       In = DAG.getUNDEF(SourceType);
12884     else
12885       In = Cast->getOperand(0);
12886     unsigned Index = isLE ? (i * ElemRatio) :
12887                             (i * ElemRatio + (ElemRatio - 1));
12888 
12889     assert(Index < Ops.size() && "Invalid index");
12890     Ops[Index] = In;
12891   }
12892 
12893   // The type of the new BUILD_VECTOR node.
12894   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12895   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12896          "Invalid vector size");
12897   // Check if the new vector type is legal.
12898   if (!isTypeLegal(VecVT)) return SDValue();
12899 
12900   // Make the new BUILD_VECTOR.
12901   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
12902 
12903   // The new BUILD_VECTOR node has the potential to be further optimized.
12904   AddToWorklist(BV.getNode());
12905   // Bitcast to the desired type.
12906   return DAG.getBitcast(VT, BV);
12907 }
12908 
12909 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12910   EVT VT = N->getValueType(0);
12911 
12912   unsigned NumInScalars = N->getNumOperands();
12913   SDLoc DL(N);
12914 
12915   EVT SrcVT = MVT::Other;
12916   unsigned Opcode = ISD::DELETED_NODE;
12917   unsigned NumDefs = 0;
12918 
12919   for (unsigned i = 0; i != NumInScalars; ++i) {
12920     SDValue In = N->getOperand(i);
12921     unsigned Opc = In.getOpcode();
12922 
12923     if (Opc == ISD::UNDEF)
12924       continue;
12925 
12926     // If all scalar values are floats and converted from integers.
12927     if (Opcode == ISD::DELETED_NODE &&
12928         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12929       Opcode = Opc;
12930     }
12931 
12932     if (Opc != Opcode)
12933       return SDValue();
12934 
12935     EVT InVT = In.getOperand(0).getValueType();
12936 
12937     // If all scalar values are typed differently, bail out. It's chosen to
12938     // simplify BUILD_VECTOR of integer types.
12939     if (SrcVT == MVT::Other)
12940       SrcVT = InVT;
12941     if (SrcVT != InVT)
12942       return SDValue();
12943     NumDefs++;
12944   }
12945 
12946   // If the vector has just one element defined, it's not worth to fold it into
12947   // a vectorized one.
12948   if (NumDefs < 2)
12949     return SDValue();
12950 
12951   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12952          && "Should only handle conversion from integer to float.");
12953   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12954 
12955   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12956 
12957   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12958     return SDValue();
12959 
12960   // Just because the floating-point vector type is legal does not necessarily
12961   // mean that the corresponding integer vector type is.
12962   if (!isTypeLegal(NVT))
12963     return SDValue();
12964 
12965   SmallVector<SDValue, 8> Opnds;
12966   for (unsigned i = 0; i != NumInScalars; ++i) {
12967     SDValue In = N->getOperand(i);
12968 
12969     if (In.isUndef())
12970       Opnds.push_back(DAG.getUNDEF(SrcVT));
12971     else
12972       Opnds.push_back(In.getOperand(0));
12973   }
12974   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
12975   AddToWorklist(BV.getNode());
12976 
12977   return DAG.getNode(Opcode, DL, VT, BV);
12978 }
12979 
12980 SDValue DAGCombiner::createBuildVecShuffle(SDLoc DL, SDNode *N,
12981                                            ArrayRef<int> VectorMask,
12982                                            SDValue VecIn1, SDValue VecIn2,
12983                                            unsigned LeftIdx) {
12984   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12985   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
12986 
12987   EVT VT = N->getValueType(0);
12988   EVT InVT1 = VecIn1.getValueType();
12989   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
12990 
12991   unsigned Vec2Offset = InVT1.getVectorNumElements();
12992   unsigned NumElems = VT.getVectorNumElements();
12993   unsigned ShuffleNumElems = NumElems;
12994 
12995   // We can't generate a shuffle node with mismatched input and output types.
12996   // Try to make the types match the type of the output.
12997   if (InVT1 != VT || InVT2 != VT) {
12998     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
12999       // If the output vector length is a multiple of both input lengths,
13000       // we can concatenate them and pad the rest with undefs.
13001       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13002       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13003       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13004       ConcatOps[0] = VecIn1;
13005       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13006       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13007       VecIn2 = SDValue();
13008     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13009       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13010         return SDValue();
13011 
13012       if (!VecIn2.getNode()) {
13013         // If we only have one input vector, and it's twice the size of the
13014         // output, split it in two.
13015         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13016                              DAG.getConstant(NumElems, DL, IdxTy));
13017         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13018         // Since we now have shorter input vectors, adjust the offset of the
13019         // second vector's start.
13020         Vec2Offset = NumElems;
13021       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13022         // VecIn1 is wider than the output, and we have another, possibly
13023         // smaller input. Pad the smaller input with undefs, shuffle at the
13024         // input vector width, and extract the output.
13025         // The shuffle type is different than VT, so check legality again.
13026         if (LegalOperations &&
13027             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13028           return SDValue();
13029 
13030         if (InVT1 != InVT2)
13031           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13032                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13033         ShuffleNumElems = NumElems * 2;
13034       } else {
13035         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13036         // than VecIn1. We can't handle this for now - this case will disappear
13037         // when we start sorting the vectors by type.
13038         return SDValue();
13039       }
13040     } else {
13041       // TODO: Support cases where the length mismatch isn't exactly by a
13042       // factor of 2.
13043       // TODO: Move this check upwards, so that if we have bad type
13044       // mismatches, we don't create any DAG nodes.
13045       return SDValue();
13046     }
13047   }
13048 
13049   // Initialize mask to undef.
13050   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13051 
13052   // Only need to run up to the number of elements actually used, not the
13053   // total number of elements in the shuffle - if we are shuffling a wider
13054   // vector, the high lanes should be set to undef.
13055   for (unsigned i = 0; i != NumElems; ++i) {
13056     if (VectorMask[i] <= 0)
13057       continue;
13058 
13059     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13060     if (VectorMask[i] == (int)LeftIdx) {
13061       Mask[i] = ExtIndex;
13062     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13063       Mask[i] = Vec2Offset + ExtIndex;
13064     }
13065   }
13066 
13067   // The type the input vectors may have changed above.
13068   InVT1 = VecIn1.getValueType();
13069 
13070   // If we already have a VecIn2, it should have the same type as VecIn1.
13071   // If we don't, get an undef/zero vector of the appropriate type.
13072   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13073   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13074 
13075   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13076   if (ShuffleNumElems > NumElems)
13077     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13078 
13079   return Shuffle;
13080 }
13081 
13082 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13083 // operations. If the types of the vectors we're extracting from allow it,
13084 // turn this into a vector_shuffle node.
13085 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13086   SDLoc DL(N);
13087   EVT VT = N->getValueType(0);
13088 
13089   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13090   if (!isTypeLegal(VT))
13091     return SDValue();
13092 
13093   // May only combine to shuffle after legalize if shuffle is legal.
13094   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13095     return SDValue();
13096 
13097   bool UsesZeroVector = false;
13098   unsigned NumElems = N->getNumOperands();
13099 
13100   // Record, for each element of the newly built vector, which input vector
13101   // that element comes from. -1 stands for undef, 0 for the zero vector,
13102   // and positive values for the input vectors.
13103   // VectorMask maps each element to its vector number, and VecIn maps vector
13104   // numbers to their initial SDValues.
13105 
13106   SmallVector<int, 8> VectorMask(NumElems, -1);
13107   SmallVector<SDValue, 8> VecIn;
13108   VecIn.push_back(SDValue());
13109 
13110   for (unsigned i = 0; i != NumElems; ++i) {
13111     SDValue Op = N->getOperand(i);
13112 
13113     if (Op.isUndef())
13114       continue;
13115 
13116     // See if we can use a blend with a zero vector.
13117     // TODO: Should we generalize this to a blend with an arbitrary constant
13118     // vector?
13119     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13120       UsesZeroVector = true;
13121       VectorMask[i] = 0;
13122       continue;
13123     }
13124 
13125     // Not an undef or zero. If the input is something other than an
13126     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13127     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13128         !isa<ConstantSDNode>(Op.getOperand(1)))
13129       return SDValue();
13130 
13131     SDValue ExtractedFromVec = Op.getOperand(0);
13132 
13133     // All inputs must have the same element type as the output.
13134     if (VT.getVectorElementType() !=
13135         ExtractedFromVec.getValueType().getVectorElementType())
13136       return SDValue();
13137 
13138     // Have we seen this input vector before?
13139     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13140     // a map back from SDValues to numbers isn't worth it.
13141     unsigned Idx = std::distance(
13142         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13143     if (Idx == VecIn.size())
13144       VecIn.push_back(ExtractedFromVec);
13145 
13146     VectorMask[i] = Idx;
13147   }
13148 
13149   // If we didn't find at least one input vector, bail out.
13150   if (VecIn.size() < 2)
13151     return SDValue();
13152 
13153   // TODO: We want to sort the vectors by descending length, so that adjacent
13154   // pairs have similar length, and the longer vector is always first in the
13155   // pair.
13156 
13157   // TODO: Should this fire if some of the input vectors has illegal type (like
13158   // it does now), or should we let legalization run its course first?
13159 
13160   // Shuffle phase:
13161   // Take pairs of vectors, and shuffle them so that the result has elements
13162   // from these vectors in the correct places.
13163   // For example, given:
13164   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13165   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13166   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13167   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13168   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13169   // We will generate:
13170   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13171   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13172   SmallVector<SDValue, 4> Shuffles;
13173   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13174     unsigned LeftIdx = 2 * In + 1;
13175     SDValue VecLeft = VecIn[LeftIdx];
13176     SDValue VecRight =
13177         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13178 
13179     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13180                                                 VecRight, LeftIdx))
13181       Shuffles.push_back(Shuffle);
13182     else
13183       return SDValue();
13184   }
13185 
13186   // If we need the zero vector as an "ingredient" in the blend tree, add it
13187   // to the list of shuffles.
13188   if (UsesZeroVector)
13189     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13190                                       : DAG.getConstantFP(0.0, DL, VT));
13191 
13192   // If we only have one shuffle, we're done.
13193   if (Shuffles.size() == 1)
13194     return Shuffles[0];
13195 
13196   // Update the vector mask to point to the post-shuffle vectors.
13197   for (int &Vec : VectorMask)
13198     if (Vec == 0)
13199       Vec = Shuffles.size() - 1;
13200     else
13201       Vec = (Vec - 1) / 2;
13202 
13203   // More than one shuffle. Generate a binary tree of blends, e.g. if from
13204   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13205   // generate:
13206   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13207   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13208   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13209   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13210   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13211   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13212   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13213 
13214   // Make sure the initial size of the shuffle list is even.
13215   if (Shuffles.size() % 2)
13216     Shuffles.push_back(DAG.getUNDEF(VT));
13217 
13218   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13219     if (CurSize % 2) {
13220       Shuffles[CurSize] = DAG.getUNDEF(VT);
13221       CurSize++;
13222     }
13223     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13224       int Left = 2 * In;
13225       int Right = 2 * In + 1;
13226       SmallVector<int, 8> Mask(NumElems, -1);
13227       for (unsigned i = 0; i != NumElems; ++i) {
13228         if (VectorMask[i] == Left) {
13229           Mask[i] = i;
13230           VectorMask[i] = In;
13231         } else if (VectorMask[i] == Right) {
13232           Mask[i] = i + NumElems;
13233           VectorMask[i] = In;
13234         }
13235       }
13236 
13237       Shuffles[In] =
13238           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13239     }
13240   }
13241 
13242   return Shuffles[0];
13243 }
13244 
13245 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13246   EVT VT = N->getValueType(0);
13247 
13248   // A vector built entirely of undefs is undef.
13249   if (ISD::allOperandsUndef(N))
13250     return DAG.getUNDEF(VT);
13251 
13252   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13253     return V;
13254 
13255   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13256     return V;
13257 
13258   if (SDValue V = reduceBuildVecToShuffle(N))
13259     return V;
13260 
13261   return SDValue();
13262 }
13263 
13264 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13265   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13266   EVT OpVT = N->getOperand(0).getValueType();
13267 
13268   // If the operands are legal vectors, leave them alone.
13269   if (TLI.isTypeLegal(OpVT))
13270     return SDValue();
13271 
13272   SDLoc DL(N);
13273   EVT VT = N->getValueType(0);
13274   SmallVector<SDValue, 8> Ops;
13275 
13276   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13277   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13278 
13279   // Keep track of what we encounter.
13280   bool AnyInteger = false;
13281   bool AnyFP = false;
13282   for (const SDValue &Op : N->ops()) {
13283     if (ISD::BITCAST == Op.getOpcode() &&
13284         !Op.getOperand(0).getValueType().isVector())
13285       Ops.push_back(Op.getOperand(0));
13286     else if (ISD::UNDEF == Op.getOpcode())
13287       Ops.push_back(ScalarUndef);
13288     else
13289       return SDValue();
13290 
13291     // Note whether we encounter an integer or floating point scalar.
13292     // If it's neither, bail out, it could be something weird like x86mmx.
13293     EVT LastOpVT = Ops.back().getValueType();
13294     if (LastOpVT.isFloatingPoint())
13295       AnyFP = true;
13296     else if (LastOpVT.isInteger())
13297       AnyInteger = true;
13298     else
13299       return SDValue();
13300   }
13301 
13302   // If any of the operands is a floating point scalar bitcast to a vector,
13303   // use floating point types throughout, and bitcast everything.
13304   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
13305   if (AnyFP) {
13306     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
13307     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13308     if (AnyInteger) {
13309       for (SDValue &Op : Ops) {
13310         if (Op.getValueType() == SVT)
13311           continue;
13312         if (Op.isUndef())
13313           Op = ScalarUndef;
13314         else
13315           Op = DAG.getBitcast(SVT, Op);
13316       }
13317     }
13318   }
13319 
13320   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
13321                                VT.getSizeInBits() / SVT.getSizeInBits());
13322   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
13323 }
13324 
13325 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
13326 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
13327 // most two distinct vectors the same size as the result, attempt to turn this
13328 // into a legal shuffle.
13329 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
13330   EVT VT = N->getValueType(0);
13331   EVT OpVT = N->getOperand(0).getValueType();
13332   int NumElts = VT.getVectorNumElements();
13333   int NumOpElts = OpVT.getVectorNumElements();
13334 
13335   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
13336   SmallVector<int, 8> Mask;
13337 
13338   for (SDValue Op : N->ops()) {
13339     // Peek through any bitcast.
13340     while (Op.getOpcode() == ISD::BITCAST)
13341       Op = Op.getOperand(0);
13342 
13343     // UNDEF nodes convert to UNDEF shuffle mask values.
13344     if (Op.isUndef()) {
13345       Mask.append((unsigned)NumOpElts, -1);
13346       continue;
13347     }
13348 
13349     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13350       return SDValue();
13351 
13352     // What vector are we extracting the subvector from and at what index?
13353     SDValue ExtVec = Op.getOperand(0);
13354 
13355     // We want the EVT of the original extraction to correctly scale the
13356     // extraction index.
13357     EVT ExtVT = ExtVec.getValueType();
13358 
13359     // Peek through any bitcast.
13360     while (ExtVec.getOpcode() == ISD::BITCAST)
13361       ExtVec = ExtVec.getOperand(0);
13362 
13363     // UNDEF nodes convert to UNDEF shuffle mask values.
13364     if (ExtVec.isUndef()) {
13365       Mask.append((unsigned)NumOpElts, -1);
13366       continue;
13367     }
13368 
13369     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13370       return SDValue();
13371     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13372 
13373     // Ensure that we are extracting a subvector from a vector the same
13374     // size as the result.
13375     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13376       return SDValue();
13377 
13378     // Scale the subvector index to account for any bitcast.
13379     int NumExtElts = ExtVT.getVectorNumElements();
13380     if (0 == (NumExtElts % NumElts))
13381       ExtIdx /= (NumExtElts / NumElts);
13382     else if (0 == (NumElts % NumExtElts))
13383       ExtIdx *= (NumElts / NumExtElts);
13384     else
13385       return SDValue();
13386 
13387     // At most we can reference 2 inputs in the final shuffle.
13388     if (SV0.isUndef() || SV0 == ExtVec) {
13389       SV0 = ExtVec;
13390       for (int i = 0; i != NumOpElts; ++i)
13391         Mask.push_back(i + ExtIdx);
13392     } else if (SV1.isUndef() || SV1 == ExtVec) {
13393       SV1 = ExtVec;
13394       for (int i = 0; i != NumOpElts; ++i)
13395         Mask.push_back(i + ExtIdx + NumElts);
13396     } else {
13397       return SDValue();
13398     }
13399   }
13400 
13401   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13402     return SDValue();
13403 
13404   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13405                               DAG.getBitcast(VT, SV1), Mask);
13406 }
13407 
13408 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13409   // If we only have one input vector, we don't need to do any concatenation.
13410   if (N->getNumOperands() == 1)
13411     return N->getOperand(0);
13412 
13413   // Check if all of the operands are undefs.
13414   EVT VT = N->getValueType(0);
13415   if (ISD::allOperandsUndef(N))
13416     return DAG.getUNDEF(VT);
13417 
13418   // Optimize concat_vectors where all but the first of the vectors are undef.
13419   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13420         return Op.isUndef();
13421       })) {
13422     SDValue In = N->getOperand(0);
13423     assert(In.getValueType().isVector() && "Must concat vectors");
13424 
13425     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13426     if (In->getOpcode() == ISD::BITCAST &&
13427         !In->getOperand(0)->getValueType(0).isVector()) {
13428       SDValue Scalar = In->getOperand(0);
13429 
13430       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13431       // look through the trunc so we can still do the transform:
13432       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13433       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13434           !TLI.isTypeLegal(Scalar.getValueType()) &&
13435           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13436         Scalar = Scalar->getOperand(0);
13437 
13438       EVT SclTy = Scalar->getValueType(0);
13439 
13440       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13441         return SDValue();
13442 
13443       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13444                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13445       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13446         return SDValue();
13447 
13448       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
13449       return DAG.getBitcast(VT, Res);
13450     }
13451   }
13452 
13453   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13454   // We have already tested above for an UNDEF only concatenation.
13455   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13456   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13457   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13458     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13459   };
13460   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13461     SmallVector<SDValue, 8> Opnds;
13462     EVT SVT = VT.getScalarType();
13463 
13464     EVT MinVT = SVT;
13465     if (!SVT.isFloatingPoint()) {
13466       // If BUILD_VECTOR are from built from integer, they may have different
13467       // operand types. Get the smallest type and truncate all operands to it.
13468       bool FoundMinVT = false;
13469       for (const SDValue &Op : N->ops())
13470         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13471           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13472           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13473           FoundMinVT = true;
13474         }
13475       assert(FoundMinVT && "Concat vector type mismatch");
13476     }
13477 
13478     for (const SDValue &Op : N->ops()) {
13479       EVT OpVT = Op.getValueType();
13480       unsigned NumElts = OpVT.getVectorNumElements();
13481 
13482       if (ISD::UNDEF == Op.getOpcode())
13483         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13484 
13485       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13486         if (SVT.isFloatingPoint()) {
13487           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13488           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13489         } else {
13490           for (unsigned i = 0; i != NumElts; ++i)
13491             Opnds.push_back(
13492                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13493         }
13494       }
13495     }
13496 
13497     assert(VT.getVectorNumElements() == Opnds.size() &&
13498            "Concat vector type mismatch");
13499     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13500   }
13501 
13502   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13503   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13504     return V;
13505 
13506   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13507   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13508     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13509       return V;
13510 
13511   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13512   // nodes often generate nop CONCAT_VECTOR nodes.
13513   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13514   // place the incoming vectors at the exact same location.
13515   SDValue SingleSource = SDValue();
13516   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13517 
13518   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13519     SDValue Op = N->getOperand(i);
13520 
13521     if (Op.isUndef())
13522       continue;
13523 
13524     // Check if this is the identity extract:
13525     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13526       return SDValue();
13527 
13528     // Find the single incoming vector for the extract_subvector.
13529     if (SingleSource.getNode()) {
13530       if (Op.getOperand(0) != SingleSource)
13531         return SDValue();
13532     } else {
13533       SingleSource = Op.getOperand(0);
13534 
13535       // Check the source type is the same as the type of the result.
13536       // If not, this concat may extend the vector, so we can not
13537       // optimize it away.
13538       if (SingleSource.getValueType() != N->getValueType(0))
13539         return SDValue();
13540     }
13541 
13542     unsigned IdentityIndex = i * PartNumElem;
13543     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13544     // The extract index must be constant.
13545     if (!CS)
13546       return SDValue();
13547 
13548     // Check that we are reading from the identity index.
13549     if (CS->getZExtValue() != IdentityIndex)
13550       return SDValue();
13551   }
13552 
13553   if (SingleSource.getNode())
13554     return SingleSource;
13555 
13556   return SDValue();
13557 }
13558 
13559 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13560   EVT NVT = N->getValueType(0);
13561   SDValue V = N->getOperand(0);
13562 
13563   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13564     // Combine:
13565     //    (extract_subvec (concat V1, V2, ...), i)
13566     // Into:
13567     //    Vi if possible
13568     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13569     // type.
13570     if (V->getOperand(0).getValueType() != NVT)
13571       return SDValue();
13572     unsigned Idx = N->getConstantOperandVal(1);
13573     unsigned NumElems = NVT.getVectorNumElements();
13574     assert((Idx % NumElems) == 0 &&
13575            "IDX in concat is not a multiple of the result vector length.");
13576     return V->getOperand(Idx / NumElems);
13577   }
13578 
13579   // Skip bitcasting
13580   if (V->getOpcode() == ISD::BITCAST)
13581     V = V.getOperand(0);
13582 
13583   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13584     // Handle only simple case where vector being inserted and vector
13585     // being extracted are of same type, and are half size of larger vectors.
13586     EVT BigVT = V->getOperand(0).getValueType();
13587     EVT SmallVT = V->getOperand(1).getValueType();
13588     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13589       return SDValue();
13590 
13591     // Only handle cases where both indexes are constants with the same type.
13592     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13593     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13594 
13595     if (InsIdx && ExtIdx &&
13596         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13597         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13598       // Combine:
13599       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13600       // Into:
13601       //    indices are equal or bit offsets are equal => V1
13602       //    otherwise => (extract_subvec V1, ExtIdx)
13603       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
13604           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
13605         return DAG.getBitcast(NVT, V->getOperand(1));
13606       return DAG.getNode(
13607           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
13608           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13609           N->getOperand(1));
13610     }
13611   }
13612 
13613   return SDValue();
13614 }
13615 
13616 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13617                                                  SDValue V, SelectionDAG &DAG) {
13618   SDLoc DL(V);
13619   EVT VT = V.getValueType();
13620 
13621   switch (V.getOpcode()) {
13622   default:
13623     return V;
13624 
13625   case ISD::CONCAT_VECTORS: {
13626     EVT OpVT = V->getOperand(0).getValueType();
13627     int OpSize = OpVT.getVectorNumElements();
13628     SmallBitVector OpUsedElements(OpSize, false);
13629     bool FoundSimplification = false;
13630     SmallVector<SDValue, 4> NewOps;
13631     NewOps.reserve(V->getNumOperands());
13632     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13633       SDValue Op = V->getOperand(i);
13634       bool OpUsed = false;
13635       for (int j = 0; j < OpSize; ++j)
13636         if (UsedElements[i * OpSize + j]) {
13637           OpUsedElements[j] = true;
13638           OpUsed = true;
13639         }
13640       NewOps.push_back(
13641           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13642                  : DAG.getUNDEF(OpVT));
13643       FoundSimplification |= Op == NewOps.back();
13644       OpUsedElements.reset();
13645     }
13646     if (FoundSimplification)
13647       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13648     return V;
13649   }
13650 
13651   case ISD::INSERT_SUBVECTOR: {
13652     SDValue BaseV = V->getOperand(0);
13653     SDValue SubV = V->getOperand(1);
13654     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13655     if (!IdxN)
13656       return V;
13657 
13658     int SubSize = SubV.getValueType().getVectorNumElements();
13659     int Idx = IdxN->getZExtValue();
13660     bool SubVectorUsed = false;
13661     SmallBitVector SubUsedElements(SubSize, false);
13662     for (int i = 0; i < SubSize; ++i)
13663       if (UsedElements[i + Idx]) {
13664         SubVectorUsed = true;
13665         SubUsedElements[i] = true;
13666         UsedElements[i + Idx] = false;
13667       }
13668 
13669     // Now recurse on both the base and sub vectors.
13670     SDValue SimplifiedSubV =
13671         SubVectorUsed
13672             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13673             : DAG.getUNDEF(SubV.getValueType());
13674     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13675     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13676       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13677                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13678     return V;
13679   }
13680   }
13681 }
13682 
13683 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13684                                        SDValue N1, SelectionDAG &DAG) {
13685   EVT VT = SVN->getValueType(0);
13686   int NumElts = VT.getVectorNumElements();
13687   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13688   for (int M : SVN->getMask())
13689     if (M >= 0 && M < NumElts)
13690       N0UsedElements[M] = true;
13691     else if (M >= NumElts)
13692       N1UsedElements[M - NumElts] = true;
13693 
13694   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13695   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13696   if (S0 == N0 && S1 == N1)
13697     return SDValue();
13698 
13699   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13700 }
13701 
13702 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13703 // or turn a shuffle of a single concat into simpler shuffle then concat.
13704 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13705   EVT VT = N->getValueType(0);
13706   unsigned NumElts = VT.getVectorNumElements();
13707 
13708   SDValue N0 = N->getOperand(0);
13709   SDValue N1 = N->getOperand(1);
13710   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13711 
13712   SmallVector<SDValue, 4> Ops;
13713   EVT ConcatVT = N0.getOperand(0).getValueType();
13714   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13715   unsigned NumConcats = NumElts / NumElemsPerConcat;
13716 
13717   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13718   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13719   // half vector elements.
13720   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13721       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13722                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13723     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13724                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13725     N1 = DAG.getUNDEF(ConcatVT);
13726     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13727   }
13728 
13729   // Look at every vector that's inserted. We're looking for exact
13730   // subvector-sized copies from a concatenated vector
13731   for (unsigned I = 0; I != NumConcats; ++I) {
13732     // Make sure we're dealing with a copy.
13733     unsigned Begin = I * NumElemsPerConcat;
13734     bool AllUndef = true, NoUndef = true;
13735     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13736       if (SVN->getMaskElt(J) >= 0)
13737         AllUndef = false;
13738       else
13739         NoUndef = false;
13740     }
13741 
13742     if (NoUndef) {
13743       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13744         return SDValue();
13745 
13746       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13747         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13748           return SDValue();
13749 
13750       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13751       if (FirstElt < N0.getNumOperands())
13752         Ops.push_back(N0.getOperand(FirstElt));
13753       else
13754         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13755 
13756     } else if (AllUndef) {
13757       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13758     } else { // Mixed with general masks and undefs, can't do optimization.
13759       return SDValue();
13760     }
13761   }
13762 
13763   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13764 }
13765 
13766 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13767 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13768 // This combine is done in the following cases:
13769 // 1. Both N0,N1 are BUILD_VECTOR's composed of constants or undefs.
13770 // 2. Only one of N0,N1 is a BUILD_VECTOR composed of constants or undefs -
13771 //    Combine iff that node is ALL_ZEROS. We prefer not to combine a
13772 //    BUILD_VECTOR of all constants to allow efficient materialization of
13773 //    constant vectors, but the ALL_ZEROS is an exception because
13774 //    zero-extension matching seems to rely on having BUILD_VECTOR nodes with
13775 //    zero padding between elements. FIXME: Eliminate this exception for
13776 //    ALL_ZEROS constant vectors.
13777 // 3. Neither N0,N1 are composed of only constants.
13778 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
13779                                        SelectionDAG &DAG,
13780                                        const TargetLowering &TLI) {
13781   EVT VT = SVN->getValueType(0);
13782   unsigned NumElts = VT.getVectorNumElements();
13783   SDValue N0 = SVN->getOperand(0);
13784   SDValue N1 = SVN->getOperand(1);
13785 
13786   if (!N0->hasOneUse() || !N1->hasOneUse())
13787     return SDValue();
13788   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
13789   // discussed above.
13790   if (!N1.isUndef()) {
13791     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
13792     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
13793     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
13794       return SDValue();
13795     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
13796       return SDValue();
13797   }
13798 
13799   SmallVector<SDValue, 8> Ops;
13800   for (int M : SVN->getMask()) {
13801     SDValue Op = DAG.getUNDEF(VT.getScalarType());
13802     if (M >= 0) {
13803       int Idx = M < (int)NumElts ? M : M - NumElts;
13804       SDValue &S = (M < (int)NumElts ? N0 : N1);
13805       if (S.getOpcode() == ISD::BUILD_VECTOR) {
13806         Op = S.getOperand(Idx);
13807       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13808         if (Idx == 0)
13809           Op = S.getOperand(0);
13810       } else {
13811         // Operand can't be combined - bail out.
13812         return SDValue();
13813       }
13814     }
13815     Ops.push_back(Op);
13816   }
13817   // BUILD_VECTOR requires all inputs to be of the same type, find the
13818   // maximum type and extend them all.
13819   EVT SVT = VT.getScalarType();
13820   if (SVT.isInteger())
13821     for (SDValue &Op : Ops)
13822       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13823   if (SVT != VT.getScalarType())
13824     for (SDValue &Op : Ops)
13825       Op = TLI.isZExtFree(Op.getValueType(), SVT)
13826                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
13827                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
13828   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
13829 }
13830 
13831 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13832   EVT VT = N->getValueType(0);
13833   unsigned NumElts = VT.getVectorNumElements();
13834 
13835   SDValue N0 = N->getOperand(0);
13836   SDValue N1 = N->getOperand(1);
13837 
13838   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13839 
13840   // Canonicalize shuffle undef, undef -> undef
13841   if (N0.isUndef() && N1.isUndef())
13842     return DAG.getUNDEF(VT);
13843 
13844   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13845 
13846   // Canonicalize shuffle v, v -> v, undef
13847   if (N0 == N1) {
13848     SmallVector<int, 8> NewMask;
13849     for (unsigned i = 0; i != NumElts; ++i) {
13850       int Idx = SVN->getMaskElt(i);
13851       if (Idx >= (int)NumElts) Idx -= NumElts;
13852       NewMask.push_back(Idx);
13853     }
13854     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
13855   }
13856 
13857   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13858   if (N0.isUndef())
13859     return DAG.getCommutedVectorShuffle(*SVN);
13860 
13861   // Remove references to rhs if it is undef
13862   if (N1.isUndef()) {
13863     bool Changed = false;
13864     SmallVector<int, 8> NewMask;
13865     for (unsigned i = 0; i != NumElts; ++i) {
13866       int Idx = SVN->getMaskElt(i);
13867       if (Idx >= (int)NumElts) {
13868         Idx = -1;
13869         Changed = true;
13870       }
13871       NewMask.push_back(Idx);
13872     }
13873     if (Changed)
13874       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
13875   }
13876 
13877   // If it is a splat, check if the argument vector is another splat or a
13878   // build_vector.
13879   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13880     SDNode *V = N0.getNode();
13881 
13882     // If this is a bit convert that changes the element type of the vector but
13883     // not the number of vector elements, look through it.  Be careful not to
13884     // look though conversions that change things like v4f32 to v2f64.
13885     if (V->getOpcode() == ISD::BITCAST) {
13886       SDValue ConvInput = V->getOperand(0);
13887       if (ConvInput.getValueType().isVector() &&
13888           ConvInput.getValueType().getVectorNumElements() == NumElts)
13889         V = ConvInput.getNode();
13890     }
13891 
13892     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13893       assert(V->getNumOperands() == NumElts &&
13894              "BUILD_VECTOR has wrong number of operands");
13895       SDValue Base;
13896       bool AllSame = true;
13897       for (unsigned i = 0; i != NumElts; ++i) {
13898         if (!V->getOperand(i).isUndef()) {
13899           Base = V->getOperand(i);
13900           break;
13901         }
13902       }
13903       // Splat of <u, u, u, u>, return <u, u, u, u>
13904       if (!Base.getNode())
13905         return N0;
13906       for (unsigned i = 0; i != NumElts; ++i) {
13907         if (V->getOperand(i) != Base) {
13908           AllSame = false;
13909           break;
13910         }
13911       }
13912       // Splat of <x, x, x, x>, return <x, x, x, x>
13913       if (AllSame)
13914         return N0;
13915 
13916       // Canonicalize any other splat as a build_vector.
13917       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13918       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13919       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13920 
13921       // We may have jumped through bitcasts, so the type of the
13922       // BUILD_VECTOR may not match the type of the shuffle.
13923       if (V->getValueType(0) != VT)
13924         NewBV = DAG.getBitcast(VT, NewBV);
13925       return NewBV;
13926     }
13927   }
13928 
13929   // There are various patterns used to build up a vector from smaller vectors,
13930   // subvectors, or elements. Scan chains of these and replace unused insertions
13931   // or components with undef.
13932   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13933     return S;
13934 
13935   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13936       Level < AfterLegalizeVectorOps &&
13937       (N1.isUndef() ||
13938       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13939        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13940     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13941       return V;
13942   }
13943 
13944   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13945   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13946   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13947     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
13948       return Res;
13949 
13950   // If this shuffle only has a single input that is a bitcasted shuffle,
13951   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13952   // back to their original types.
13953   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13954       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13955       TLI.isTypeLegal(VT)) {
13956 
13957     // Peek through the bitcast only if there is one user.
13958     SDValue BC0 = N0;
13959     while (BC0.getOpcode() == ISD::BITCAST) {
13960       if (!BC0.hasOneUse())
13961         break;
13962       BC0 = BC0.getOperand(0);
13963     }
13964 
13965     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13966       if (Scale == 1)
13967         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13968 
13969       SmallVector<int, 8> NewMask;
13970       for (int M : Mask)
13971         for (int s = 0; s != Scale; ++s)
13972           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13973       return NewMask;
13974     };
13975 
13976     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13977       EVT SVT = VT.getScalarType();
13978       EVT InnerVT = BC0->getValueType(0);
13979       EVT InnerSVT = InnerVT.getScalarType();
13980 
13981       // Determine which shuffle works with the smaller scalar type.
13982       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13983       EVT ScaleSVT = ScaleVT.getScalarType();
13984 
13985       if (TLI.isTypeLegal(ScaleVT) &&
13986           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13987           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13988 
13989         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13990         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13991 
13992         // Scale the shuffle masks to the smaller scalar type.
13993         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13994         SmallVector<int, 8> InnerMask =
13995             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13996         SmallVector<int, 8> OuterMask =
13997             ScaleShuffleMask(SVN->getMask(), OuterScale);
13998 
13999         // Merge the shuffle masks.
14000         SmallVector<int, 8> NewMask;
14001         for (int M : OuterMask)
14002           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
14003 
14004         // Test for shuffle mask legality over both commutations.
14005         SDValue SV0 = BC0->getOperand(0);
14006         SDValue SV1 = BC0->getOperand(1);
14007         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14008         if (!LegalMask) {
14009           std::swap(SV0, SV1);
14010           ShuffleVectorSDNode::commuteMask(NewMask);
14011           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14012         }
14013 
14014         if (LegalMask) {
14015           SV0 = DAG.getBitcast(ScaleVT, SV0);
14016           SV1 = DAG.getBitcast(ScaleVT, SV1);
14017           return DAG.getBitcast(
14018               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
14019         }
14020       }
14021     }
14022   }
14023 
14024   // Canonicalize shuffles according to rules:
14025   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
14026   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
14027   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
14028   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
14029       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
14030       TLI.isTypeLegal(VT)) {
14031     // The incoming shuffle must be of the same type as the result of the
14032     // current shuffle.
14033     assert(N1->getOperand(0).getValueType() == VT &&
14034            "Shuffle types don't match");
14035 
14036     SDValue SV0 = N1->getOperand(0);
14037     SDValue SV1 = N1->getOperand(1);
14038     bool HasSameOp0 = N0 == SV0;
14039     bool IsSV1Undef = SV1.isUndef();
14040     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
14041       // Commute the operands of this shuffle so that next rule
14042       // will trigger.
14043       return DAG.getCommutedVectorShuffle(*SVN);
14044   }
14045 
14046   // Try to fold according to rules:
14047   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14048   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14049   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14050   // Don't try to fold shuffles with illegal type.
14051   // Only fold if this shuffle is the only user of the other shuffle.
14052   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14053       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14054     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14055 
14056     // The incoming shuffle must be of the same type as the result of the
14057     // current shuffle.
14058     assert(OtherSV->getOperand(0).getValueType() == VT &&
14059            "Shuffle types don't match");
14060 
14061     SDValue SV0, SV1;
14062     SmallVector<int, 4> Mask;
14063     // Compute the combined shuffle mask for a shuffle with SV0 as the first
14064     // operand, and SV1 as the second operand.
14065     for (unsigned i = 0; i != NumElts; ++i) {
14066       int Idx = SVN->getMaskElt(i);
14067       if (Idx < 0) {
14068         // Propagate Undef.
14069         Mask.push_back(Idx);
14070         continue;
14071       }
14072 
14073       SDValue CurrentVec;
14074       if (Idx < (int)NumElts) {
14075         // This shuffle index refers to the inner shuffle N0. Lookup the inner
14076         // shuffle mask to identify which vector is actually referenced.
14077         Idx = OtherSV->getMaskElt(Idx);
14078         if (Idx < 0) {
14079           // Propagate Undef.
14080           Mask.push_back(Idx);
14081           continue;
14082         }
14083 
14084         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14085                                            : OtherSV->getOperand(1);
14086       } else {
14087         // This shuffle index references an element within N1.
14088         CurrentVec = N1;
14089       }
14090 
14091       // Simple case where 'CurrentVec' is UNDEF.
14092       if (CurrentVec.isUndef()) {
14093         Mask.push_back(-1);
14094         continue;
14095       }
14096 
14097       // Canonicalize the shuffle index. We don't know yet if CurrentVec
14098       // will be the first or second operand of the combined shuffle.
14099       Idx = Idx % NumElts;
14100       if (!SV0.getNode() || SV0 == CurrentVec) {
14101         // Ok. CurrentVec is the left hand side.
14102         // Update the mask accordingly.
14103         SV0 = CurrentVec;
14104         Mask.push_back(Idx);
14105         continue;
14106       }
14107 
14108       // Bail out if we cannot convert the shuffle pair into a single shuffle.
14109       if (SV1.getNode() && SV1 != CurrentVec)
14110         return SDValue();
14111 
14112       // Ok. CurrentVec is the right hand side.
14113       // Update the mask accordingly.
14114       SV1 = CurrentVec;
14115       Mask.push_back(Idx + NumElts);
14116     }
14117 
14118     // Check if all indices in Mask are Undef. In case, propagate Undef.
14119     bool isUndefMask = true;
14120     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14121       isUndefMask &= Mask[i] < 0;
14122 
14123     if (isUndefMask)
14124       return DAG.getUNDEF(VT);
14125 
14126     if (!SV0.getNode())
14127       SV0 = DAG.getUNDEF(VT);
14128     if (!SV1.getNode())
14129       SV1 = DAG.getUNDEF(VT);
14130 
14131     // Avoid introducing shuffles with illegal mask.
14132     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14133       ShuffleVectorSDNode::commuteMask(Mask);
14134 
14135       if (!TLI.isShuffleMaskLegal(Mask, VT))
14136         return SDValue();
14137 
14138       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14139       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14140       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14141       std::swap(SV0, SV1);
14142     }
14143 
14144     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14145     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14146     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14147     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14148   }
14149 
14150   return SDValue();
14151 }
14152 
14153 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14154   SDValue InVal = N->getOperand(0);
14155   EVT VT = N->getValueType(0);
14156 
14157   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14158   // with a VECTOR_SHUFFLE.
14159   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14160     SDValue InVec = InVal->getOperand(0);
14161     SDValue EltNo = InVal->getOperand(1);
14162 
14163     // FIXME: We could support implicit truncation if the shuffle can be
14164     // scaled to a smaller vector scalar type.
14165     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
14166     if (C0 && VT == InVec.getValueType() &&
14167         VT.getScalarType() == InVal.getValueType()) {
14168       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
14169       int Elt = C0->getZExtValue();
14170       NewMask[0] = Elt;
14171 
14172       if (TLI.isShuffleMaskLegal(NewMask, VT))
14173         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
14174                                     NewMask);
14175     }
14176   }
14177 
14178   return SDValue();
14179 }
14180 
14181 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
14182   EVT VT = N->getValueType(0);
14183   SDValue N0 = N->getOperand(0);
14184   SDValue N1 = N->getOperand(1);
14185   SDValue N2 = N->getOperand(2);
14186 
14187   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
14188   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
14189   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
14190   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
14191       N0.getOperand(1).getValueType() == N1.getValueType() &&
14192       N0.getOperand(2) == N2)
14193     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
14194                        N1, N2);
14195 
14196   if (N0.getValueType() != N1.getValueType())
14197     return SDValue();
14198 
14199   // If the input vector is a concatenation, and the insert replaces
14200   // one of the halves, we can optimize into a single concat_vectors.
14201   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
14202       N2.getOpcode() == ISD::Constant) {
14203     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
14204 
14205     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14206     // (concat_vectors Z, Y)
14207     if (InsIdx == 0)
14208       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
14209                          N0.getOperand(1));
14210 
14211     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14212     // (concat_vectors X, Z)
14213     if (InsIdx == VT.getVectorNumElements() / 2)
14214       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
14215                          N1);
14216   }
14217 
14218   return SDValue();
14219 }
14220 
14221 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
14222   SDValue N0 = N->getOperand(0);
14223 
14224   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
14225   if (N0->getOpcode() == ISD::FP16_TO_FP)
14226     return N0->getOperand(0);
14227 
14228   return SDValue();
14229 }
14230 
14231 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
14232   SDValue N0 = N->getOperand(0);
14233 
14234   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
14235   if (N0->getOpcode() == ISD::AND) {
14236     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
14237     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
14238       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
14239                          N0.getOperand(0));
14240     }
14241   }
14242 
14243   return SDValue();
14244 }
14245 
14246 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
14247 /// with the destination vector and a zero vector.
14248 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
14249 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
14250 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
14251   EVT VT = N->getValueType(0);
14252   SDValue LHS = N->getOperand(0);
14253   SDValue RHS = N->getOperand(1);
14254   SDLoc DL(N);
14255 
14256   // Make sure we're not running after operation legalization where it
14257   // may have custom lowered the vector shuffles.
14258   if (LegalOperations)
14259     return SDValue();
14260 
14261   if (N->getOpcode() != ISD::AND)
14262     return SDValue();
14263 
14264   if (RHS.getOpcode() == ISD::BITCAST)
14265     RHS = RHS.getOperand(0);
14266 
14267   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
14268     return SDValue();
14269 
14270   EVT RVT = RHS.getValueType();
14271   unsigned NumElts = RHS.getNumOperands();
14272 
14273   // Attempt to create a valid clear mask, splitting the mask into
14274   // sub elements and checking to see if each is
14275   // all zeros or all ones - suitable for shuffle masking.
14276   auto BuildClearMask = [&](int Split) {
14277     int NumSubElts = NumElts * Split;
14278     int NumSubBits = RVT.getScalarSizeInBits() / Split;
14279 
14280     SmallVector<int, 8> Indices;
14281     for (int i = 0; i != NumSubElts; ++i) {
14282       int EltIdx = i / Split;
14283       int SubIdx = i % Split;
14284       SDValue Elt = RHS.getOperand(EltIdx);
14285       if (Elt.isUndef()) {
14286         Indices.push_back(-1);
14287         continue;
14288       }
14289 
14290       APInt Bits;
14291       if (isa<ConstantSDNode>(Elt))
14292         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
14293       else if (isa<ConstantFPSDNode>(Elt))
14294         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
14295       else
14296         return SDValue();
14297 
14298       // Extract the sub element from the constant bit mask.
14299       if (DAG.getDataLayout().isBigEndian()) {
14300         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
14301       } else {
14302         Bits = Bits.lshr(SubIdx * NumSubBits);
14303       }
14304 
14305       if (Split > 1)
14306         Bits = Bits.trunc(NumSubBits);
14307 
14308       if (Bits.isAllOnesValue())
14309         Indices.push_back(i);
14310       else if (Bits == 0)
14311         Indices.push_back(i + NumSubElts);
14312       else
14313         return SDValue();
14314     }
14315 
14316     // Let's see if the target supports this vector_shuffle.
14317     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
14318     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
14319     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
14320       return SDValue();
14321 
14322     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
14323     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
14324                                                    DAG.getBitcast(ClearVT, LHS),
14325                                                    Zero, Indices));
14326   };
14327 
14328   // Determine maximum split level (byte level masking).
14329   int MaxSplit = 1;
14330   if (RVT.getScalarSizeInBits() % 8 == 0)
14331     MaxSplit = RVT.getScalarSizeInBits() / 8;
14332 
14333   for (int Split = 1; Split <= MaxSplit; ++Split)
14334     if (RVT.getScalarSizeInBits() % Split == 0)
14335       if (SDValue S = BuildClearMask(Split))
14336         return S;
14337 
14338   return SDValue();
14339 }
14340 
14341 /// Visit a binary vector operation, like ADD.
14342 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
14343   assert(N->getValueType(0).isVector() &&
14344          "SimplifyVBinOp only works on vectors!");
14345 
14346   SDValue LHS = N->getOperand(0);
14347   SDValue RHS = N->getOperand(1);
14348   SDValue Ops[] = {LHS, RHS};
14349 
14350   // See if we can constant fold the vector operation.
14351   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
14352           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
14353     return Fold;
14354 
14355   // Try to convert a constant mask AND into a shuffle clear mask.
14356   if (SDValue Shuffle = XformToShuffleWithZero(N))
14357     return Shuffle;
14358 
14359   // Type legalization might introduce new shuffles in the DAG.
14360   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
14361   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
14362   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
14363       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
14364       LHS.getOperand(1).isUndef() &&
14365       RHS.getOperand(1).isUndef()) {
14366     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
14367     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
14368 
14369     if (SVN0->getMask().equals(SVN1->getMask())) {
14370       EVT VT = N->getValueType(0);
14371       SDValue UndefVector = LHS.getOperand(1);
14372       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
14373                                      LHS.getOperand(0), RHS.getOperand(0),
14374                                      N->getFlags());
14375       AddUsersToWorklist(N);
14376       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
14377                                   SVN0->getMask());
14378     }
14379   }
14380 
14381   return SDValue();
14382 }
14383 
14384 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
14385                                     SDValue N2) {
14386   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14387 
14388   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14389                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
14390 
14391   // If we got a simplified select_cc node back from SimplifySelectCC, then
14392   // break it down into a new SETCC node, and a new SELECT node, and then return
14393   // the SELECT node, since we were called with a SELECT node.
14394   if (SCC.getNode()) {
14395     // Check to see if we got a select_cc back (to turn into setcc/select).
14396     // Otherwise, just return whatever node we got back, like fabs.
14397     if (SCC.getOpcode() == ISD::SELECT_CC) {
14398       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14399                                   N0.getValueType(),
14400                                   SCC.getOperand(0), SCC.getOperand(1),
14401                                   SCC.getOperand(4));
14402       AddToWorklist(SETCC.getNode());
14403       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14404                            SCC.getOperand(2), SCC.getOperand(3));
14405     }
14406 
14407     return SCC;
14408   }
14409   return SDValue();
14410 }
14411 
14412 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14413 /// being selected between, see if we can simplify the select.  Callers of this
14414 /// should assume that TheSelect is deleted if this returns true.  As such, they
14415 /// should return the appropriate thing (e.g. the node) back to the top-level of
14416 /// the DAG combiner loop to avoid it being looked at.
14417 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14418                                     SDValue RHS) {
14419 
14420   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14421   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14422   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14423     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14424       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14425       SDValue Sqrt = RHS;
14426       ISD::CondCode CC;
14427       SDValue CmpLHS;
14428       const ConstantFPSDNode *Zero = nullptr;
14429 
14430       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14431         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14432         CmpLHS = TheSelect->getOperand(0);
14433         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14434       } else {
14435         // SELECT or VSELECT
14436         SDValue Cmp = TheSelect->getOperand(0);
14437         if (Cmp.getOpcode() == ISD::SETCC) {
14438           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14439           CmpLHS = Cmp.getOperand(0);
14440           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14441         }
14442       }
14443       if (Zero && Zero->isZero() &&
14444           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14445           CC == ISD::SETULT || CC == ISD::SETLT)) {
14446         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14447         CombineTo(TheSelect, Sqrt);
14448         return true;
14449       }
14450     }
14451   }
14452   // Cannot simplify select with vector condition
14453   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14454 
14455   // If this is a select from two identical things, try to pull the operation
14456   // through the select.
14457   if (LHS.getOpcode() != RHS.getOpcode() ||
14458       !LHS.hasOneUse() || !RHS.hasOneUse())
14459     return false;
14460 
14461   // If this is a load and the token chain is identical, replace the select
14462   // of two loads with a load through a select of the address to load from.
14463   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14464   // constants have been dropped into the constant pool.
14465   if (LHS.getOpcode() == ISD::LOAD) {
14466     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14467     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14468 
14469     // Token chains must be identical.
14470     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14471         // Do not let this transformation reduce the number of volatile loads.
14472         LLD->isVolatile() || RLD->isVolatile() ||
14473         // FIXME: If either is a pre/post inc/dec load,
14474         // we'd need to split out the address adjustment.
14475         LLD->isIndexed() || RLD->isIndexed() ||
14476         // If this is an EXTLOAD, the VT's must match.
14477         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14478         // If this is an EXTLOAD, the kind of extension must match.
14479         (LLD->getExtensionType() != RLD->getExtensionType() &&
14480          // The only exception is if one of the extensions is anyext.
14481          LLD->getExtensionType() != ISD::EXTLOAD &&
14482          RLD->getExtensionType() != ISD::EXTLOAD) ||
14483         // FIXME: this discards src value information.  This is
14484         // over-conservative. It would be beneficial to be able to remember
14485         // both potential memory locations.  Since we are discarding
14486         // src value info, don't do the transformation if the memory
14487         // locations are not in the default address space.
14488         LLD->getPointerInfo().getAddrSpace() != 0 ||
14489         RLD->getPointerInfo().getAddrSpace() != 0 ||
14490         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14491                                       LLD->getBasePtr().getValueType()))
14492       return false;
14493 
14494     // Check that the select condition doesn't reach either load.  If so,
14495     // folding this will induce a cycle into the DAG.  If not, this is safe to
14496     // xform, so create a select of the addresses.
14497     SDValue Addr;
14498     if (TheSelect->getOpcode() == ISD::SELECT) {
14499       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14500       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14501           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14502         return false;
14503       // The loads must not depend on one another.
14504       if (LLD->isPredecessorOf(RLD) ||
14505           RLD->isPredecessorOf(LLD))
14506         return false;
14507       Addr = DAG.getSelect(SDLoc(TheSelect),
14508                            LLD->getBasePtr().getValueType(),
14509                            TheSelect->getOperand(0), LLD->getBasePtr(),
14510                            RLD->getBasePtr());
14511     } else {  // Otherwise SELECT_CC
14512       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14513       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14514 
14515       if ((LLD->hasAnyUseOfValue(1) &&
14516            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14517           (RLD->hasAnyUseOfValue(1) &&
14518            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14519         return false;
14520 
14521       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14522                          LLD->getBasePtr().getValueType(),
14523                          TheSelect->getOperand(0),
14524                          TheSelect->getOperand(1),
14525                          LLD->getBasePtr(), RLD->getBasePtr(),
14526                          TheSelect->getOperand(4));
14527     }
14528 
14529     SDValue Load;
14530     // It is safe to replace the two loads if they have different alignments,
14531     // but the new load must be the minimum (most restrictive) alignment of the
14532     // inputs.
14533     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14534     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14535     if (!RLD->isInvariant())
14536       MMOFlags &= ~MachineMemOperand::MOInvariant;
14537     if (!RLD->isDereferenceable())
14538       MMOFlags &= ~MachineMemOperand::MODereferenceable;
14539     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14540       // FIXME: Discards pointer and AA info.
14541       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14542                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14543                          MMOFlags);
14544     } else {
14545       // FIXME: Discards pointer and AA info.
14546       Load = DAG.getExtLoad(
14547           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14548                                                   : LLD->getExtensionType(),
14549           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14550           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14551     }
14552 
14553     // Users of the select now use the result of the load.
14554     CombineTo(TheSelect, Load);
14555 
14556     // Users of the old loads now use the new load's chain.  We know the
14557     // old-load value is dead now.
14558     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14559     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14560     return true;
14561   }
14562 
14563   return false;
14564 }
14565 
14566 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14567 /// where 'cond' is the comparison specified by CC.
14568 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14569                                       SDValue N2, SDValue N3, ISD::CondCode CC,
14570                                       bool NotExtCompare) {
14571   // (x ? y : y) -> y.
14572   if (N2 == N3) return N2;
14573 
14574   EVT VT = N2.getValueType();
14575   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14576   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14577 
14578   // Determine if the condition we're dealing with is constant
14579   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14580                               N0, N1, CC, DL, false);
14581   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14582 
14583   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14584     // fold select_cc true, x, y -> x
14585     // fold select_cc false, x, y -> y
14586     return !SCCC->isNullValue() ? N2 : N3;
14587   }
14588 
14589   // Check to see if we can simplify the select into an fabs node
14590   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14591     // Allow either -0.0 or 0.0
14592     if (CFP->isZero()) {
14593       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14594       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14595           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14596           N2 == N3.getOperand(0))
14597         return DAG.getNode(ISD::FABS, DL, VT, N0);
14598 
14599       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14600       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14601           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14602           N2.getOperand(0) == N3)
14603         return DAG.getNode(ISD::FABS, DL, VT, N3);
14604     }
14605   }
14606 
14607   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14608   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14609   // in it.  This is a win when the constant is not otherwise available because
14610   // it replaces two constant pool loads with one.  We only do this if the FP
14611   // type is known to be legal, because if it isn't, then we are before legalize
14612   // types an we want the other legalization to happen first (e.g. to avoid
14613   // messing with soft float) and if the ConstantFP is not legal, because if
14614   // it is legal, we may not need to store the FP constant in a constant pool.
14615   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14616     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14617       if (TLI.isTypeLegal(N2.getValueType()) &&
14618           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14619                TargetLowering::Legal &&
14620            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14621            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14622           // If both constants have multiple uses, then we won't need to do an
14623           // extra load, they are likely around in registers for other users.
14624           (TV->hasOneUse() || FV->hasOneUse())) {
14625         Constant *Elts[] = {
14626           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14627           const_cast<ConstantFP*>(TV->getConstantFPValue())
14628         };
14629         Type *FPTy = Elts[0]->getType();
14630         const DataLayout &TD = DAG.getDataLayout();
14631 
14632         // Create a ConstantArray of the two constants.
14633         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14634         SDValue CPIdx =
14635             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14636                                 TD.getPrefTypeAlignment(FPTy));
14637         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14638 
14639         // Get the offsets to the 0 and 1 element of the array so that we can
14640         // select between them.
14641         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14642         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14643         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14644 
14645         SDValue Cond = DAG.getSetCC(DL,
14646                                     getSetCCResultType(N0.getValueType()),
14647                                     N0, N1, CC);
14648         AddToWorklist(Cond.getNode());
14649         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14650                                           Cond, One, Zero);
14651         AddToWorklist(CstOffset.getNode());
14652         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14653                             CstOffset);
14654         AddToWorklist(CPIdx.getNode());
14655         return DAG.getLoad(
14656             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14657             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14658             Alignment);
14659       }
14660     }
14661 
14662   // Check to see if we can perform the "gzip trick", transforming
14663   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14664   if (isNullConstant(N3) && CC == ISD::SETLT &&
14665       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14666        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14667     EVT XType = N0.getValueType();
14668     EVT AType = N2.getValueType();
14669     if (XType.bitsGE(AType)) {
14670       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14671       // single-bit constant.
14672       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14673         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14674         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14675         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14676                                        getShiftAmountTy(N0.getValueType()));
14677         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14678                                     XType, N0, ShCt);
14679         AddToWorklist(Shift.getNode());
14680 
14681         if (XType.bitsGT(AType)) {
14682           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14683           AddToWorklist(Shift.getNode());
14684         }
14685 
14686         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14687       }
14688 
14689       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14690                                   XType, N0,
14691                                   DAG.getConstant(XType.getSizeInBits() - 1,
14692                                                   SDLoc(N0),
14693                                          getShiftAmountTy(N0.getValueType())));
14694       AddToWorklist(Shift.getNode());
14695 
14696       if (XType.bitsGT(AType)) {
14697         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14698         AddToWorklist(Shift.getNode());
14699       }
14700 
14701       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14702     }
14703   }
14704 
14705   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14706   // where y is has a single bit set.
14707   // A plaintext description would be, we can turn the SELECT_CC into an AND
14708   // when the condition can be materialized as an all-ones register.  Any
14709   // single bit-test can be materialized as an all-ones register with
14710   // shift-left and shift-right-arith.
14711   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14712       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14713     SDValue AndLHS = N0->getOperand(0);
14714     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14715     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14716       // Shift the tested bit over the sign bit.
14717       const APInt &AndMask = ConstAndRHS->getAPIntValue();
14718       SDValue ShlAmt =
14719         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14720                         getShiftAmountTy(AndLHS.getValueType()));
14721       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14722 
14723       // Now arithmetic right shift it all the way over, so the result is either
14724       // all-ones, or zero.
14725       SDValue ShrAmt =
14726         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14727                         getShiftAmountTy(Shl.getValueType()));
14728       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14729 
14730       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14731     }
14732   }
14733 
14734   // fold select C, 16, 0 -> shl C, 4
14735   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14736       TLI.getBooleanContents(N0.getValueType()) ==
14737           TargetLowering::ZeroOrOneBooleanContent) {
14738 
14739     // If the caller doesn't want us to simplify this into a zext of a compare,
14740     // don't do it.
14741     if (NotExtCompare && N2C->isOne())
14742       return SDValue();
14743 
14744     // Get a SetCC of the condition
14745     // NOTE: Don't create a SETCC if it's not legal on this target.
14746     if (!LegalOperations ||
14747         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14748       SDValue Temp, SCC;
14749       // cast from setcc result type to select result type
14750       if (LegalTypes) {
14751         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14752                             N0, N1, CC);
14753         if (N2.getValueType().bitsLT(SCC.getValueType()))
14754           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14755                                         N2.getValueType());
14756         else
14757           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14758                              N2.getValueType(), SCC);
14759       } else {
14760         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14761         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14762                            N2.getValueType(), SCC);
14763       }
14764 
14765       AddToWorklist(SCC.getNode());
14766       AddToWorklist(Temp.getNode());
14767 
14768       if (N2C->isOne())
14769         return Temp;
14770 
14771       // shl setcc result by log2 n2c
14772       return DAG.getNode(
14773           ISD::SHL, DL, N2.getValueType(), Temp,
14774           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14775                           getShiftAmountTy(Temp.getValueType())));
14776     }
14777   }
14778 
14779   // Check to see if this is an integer abs.
14780   // select_cc setg[te] X,  0,  X, -X ->
14781   // select_cc setgt    X, -1,  X, -X ->
14782   // select_cc setl[te] X,  0, -X,  X ->
14783   // select_cc setlt    X,  1, -X,  X ->
14784   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14785   if (N1C) {
14786     ConstantSDNode *SubC = nullptr;
14787     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14788          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14789         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14790       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14791     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14792               (N1C->isOne() && CC == ISD::SETLT)) &&
14793              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14794       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14795 
14796     EVT XType = N0.getValueType();
14797     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14798       SDLoc DL(N0);
14799       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14800                                   N0,
14801                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14802                                          getShiftAmountTy(N0.getValueType())));
14803       SDValue Add = DAG.getNode(ISD::ADD, DL,
14804                                 XType, N0, Shift);
14805       AddToWorklist(Shift.getNode());
14806       AddToWorklist(Add.getNode());
14807       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14808     }
14809   }
14810 
14811   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14812   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14813   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14814   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14815   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14816   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14817   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14818   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14819   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14820     SDValue ValueOnZero = N2;
14821     SDValue Count = N3;
14822     // If the condition is NE instead of E, swap the operands.
14823     if (CC == ISD::SETNE)
14824       std::swap(ValueOnZero, Count);
14825     // Check if the value on zero is a constant equal to the bits in the type.
14826     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14827       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14828         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14829         // legal, combine to just cttz.
14830         if ((Count.getOpcode() == ISD::CTTZ ||
14831              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14832             N0 == Count.getOperand(0) &&
14833             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14834           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14835         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14836         // legal, combine to just ctlz.
14837         if ((Count.getOpcode() == ISD::CTLZ ||
14838              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14839             N0 == Count.getOperand(0) &&
14840             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14841           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14842       }
14843     }
14844   }
14845 
14846   return SDValue();
14847 }
14848 
14849 /// This is a stub for TargetLowering::SimplifySetCC.
14850 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14851                                    ISD::CondCode Cond, const SDLoc &DL,
14852                                    bool foldBooleans) {
14853   TargetLowering::DAGCombinerInfo
14854     DagCombineInfo(DAG, Level, false, this);
14855   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14856 }
14857 
14858 /// Given an ISD::SDIV node expressing a divide by constant, return
14859 /// a DAG expression to select that will generate the same value by multiplying
14860 /// by a magic number.
14861 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14862 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14863   // when optimising for minimum size, we don't want to expand a div to a mul
14864   // and a shift.
14865   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14866     return SDValue();
14867 
14868   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14869   if (!C)
14870     return SDValue();
14871 
14872   // Avoid division by zero.
14873   if (C->isNullValue())
14874     return SDValue();
14875 
14876   std::vector<SDNode*> Built;
14877   SDValue S =
14878       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14879 
14880   for (SDNode *N : Built)
14881     AddToWorklist(N);
14882   return S;
14883 }
14884 
14885 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14886 /// DAG expression that will generate the same value by right shifting.
14887 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14888   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14889   if (!C)
14890     return SDValue();
14891 
14892   // Avoid division by zero.
14893   if (C->isNullValue())
14894     return SDValue();
14895 
14896   std::vector<SDNode *> Built;
14897   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14898 
14899   for (SDNode *N : Built)
14900     AddToWorklist(N);
14901   return S;
14902 }
14903 
14904 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14905 /// expression that will generate the same value by multiplying by a magic
14906 /// number.
14907 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14908 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14909   // when optimising for minimum size, we don't want to expand a div to a mul
14910   // and a shift.
14911   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14912     return SDValue();
14913 
14914   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14915   if (!C)
14916     return SDValue();
14917 
14918   // Avoid division by zero.
14919   if (C->isNullValue())
14920     return SDValue();
14921 
14922   std::vector<SDNode*> Built;
14923   SDValue S =
14924       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14925 
14926   for (SDNode *N : Built)
14927     AddToWorklist(N);
14928   return S;
14929 }
14930 
14931 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14932 /// For the reciprocal, we need to find the zero of the function:
14933 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
14934 ///     =>
14935 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14936 ///     does not require additional intermediate precision]
14937 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14938   if (Level >= AfterLegalizeDAG)
14939     return SDValue();
14940 
14941   // TODO: Handle half and/or extended types?
14942   EVT VT = Op.getValueType();
14943   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
14944     return SDValue();
14945 
14946   // If estimates are explicitly disabled for this function, we're done.
14947   MachineFunction &MF = DAG.getMachineFunction();
14948   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
14949   if (Enabled == TLI.ReciprocalEstimate::Disabled)
14950     return SDValue();
14951 
14952   // Estimates may be explicitly enabled for this type with a custom number of
14953   // refinement steps.
14954   int Iterations = TLI.getDivRefinementSteps(VT, MF);
14955   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
14956     AddToWorklist(Est.getNode());
14957 
14958     if (Iterations) {
14959       EVT VT = Op.getValueType();
14960       SDLoc DL(Op);
14961       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14962 
14963       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14964       for (int i = 0; i < Iterations; ++i) {
14965         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14966         AddToWorklist(NewEst.getNode());
14967 
14968         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14969         AddToWorklist(NewEst.getNode());
14970 
14971         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14972         AddToWorklist(NewEst.getNode());
14973 
14974         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14975         AddToWorklist(Est.getNode());
14976       }
14977     }
14978     return Est;
14979   }
14980 
14981   return SDValue();
14982 }
14983 
14984 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14985 /// For the reciprocal sqrt, we need to find the zero of the function:
14986 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14987 ///     =>
14988 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14989 /// As a result, we precompute A/2 prior to the iteration loop.
14990 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
14991                                          unsigned Iterations,
14992                                          SDNodeFlags *Flags, bool Reciprocal) {
14993   EVT VT = Arg.getValueType();
14994   SDLoc DL(Arg);
14995   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14996 
14997   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14998   // this entire sequence requires only one FP constant.
14999   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
15000   AddToWorklist(HalfArg.getNode());
15001 
15002   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
15003   AddToWorklist(HalfArg.getNode());
15004 
15005   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
15006   for (unsigned i = 0; i < Iterations; ++i) {
15007     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
15008     AddToWorklist(NewEst.getNode());
15009 
15010     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
15011     AddToWorklist(NewEst.getNode());
15012 
15013     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
15014     AddToWorklist(NewEst.getNode());
15015 
15016     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15017     AddToWorklist(Est.getNode());
15018   }
15019 
15020   // If non-reciprocal square root is requested, multiply the result by Arg.
15021   if (!Reciprocal) {
15022     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
15023     AddToWorklist(Est.getNode());
15024   }
15025 
15026   return Est;
15027 }
15028 
15029 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15030 /// For the reciprocal sqrt, we need to find the zero of the function:
15031 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15032 ///     =>
15033 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
15034 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
15035                                          unsigned Iterations,
15036                                          SDNodeFlags *Flags, bool Reciprocal) {
15037   EVT VT = Arg.getValueType();
15038   SDLoc DL(Arg);
15039   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
15040   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
15041 
15042   // This routine must enter the loop below to work correctly
15043   // when (Reciprocal == false).
15044   assert(Iterations > 0);
15045 
15046   // Newton iterations for reciprocal square root:
15047   // E = (E * -0.5) * ((A * E) * E + -3.0)
15048   for (unsigned i = 0; i < Iterations; ++i) {
15049     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15050     AddToWorklist(AE.getNode());
15051 
15052     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15053     AddToWorklist(AEE.getNode());
15054 
15055     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15056     AddToWorklist(RHS.getNode());
15057 
15058     // When calculating a square root at the last iteration build:
15059     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15060     // (notice a common subexpression)
15061     SDValue LHS;
15062     if (Reciprocal || (i + 1) < Iterations) {
15063       // RSQRT: LHS = (E * -0.5)
15064       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15065     } else {
15066       // SQRT: LHS = (A * E) * -0.5
15067       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15068     }
15069     AddToWorklist(LHS.getNode());
15070 
15071     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15072     AddToWorklist(Est.getNode());
15073   }
15074 
15075   return Est;
15076 }
15077 
15078 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15079 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15080 /// Op can be zero.
15081 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15082                                            bool Reciprocal) {
15083   if (Level >= AfterLegalizeDAG)
15084     return SDValue();
15085 
15086   // TODO: Handle half and/or extended types?
15087   EVT VT = Op.getValueType();
15088   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15089     return SDValue();
15090 
15091   // If estimates are explicitly disabled for this function, we're done.
15092   MachineFunction &MF = DAG.getMachineFunction();
15093   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
15094   if (Enabled == TLI.ReciprocalEstimate::Disabled)
15095     return SDValue();
15096 
15097   // Estimates may be explicitly enabled for this type with a custom number of
15098   // refinement steps.
15099   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
15100 
15101   bool UseOneConstNR = false;
15102   if (SDValue Est =
15103       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
15104                           Reciprocal)) {
15105     AddToWorklist(Est.getNode());
15106 
15107     if (Iterations) {
15108       Est = UseOneConstNR
15109             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
15110             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
15111 
15112       if (!Reciprocal) {
15113         // Unfortunately, Est is now NaN if the input was exactly 0.0.
15114         // Select out this case and force the answer to 0.0.
15115         EVT VT = Op.getValueType();
15116         SDLoc DL(Op);
15117 
15118         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
15119         EVT CCVT = getSetCCResultType(VT);
15120         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
15121         AddToWorklist(ZeroCmp.getNode());
15122 
15123         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
15124                           ZeroCmp, FPZero, Est);
15125         AddToWorklist(Est.getNode());
15126       }
15127     }
15128     return Est;
15129   }
15130 
15131   return SDValue();
15132 }
15133 
15134 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15135   return buildSqrtEstimateImpl(Op, Flags, true);
15136 }
15137 
15138 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15139   return buildSqrtEstimateImpl(Op, Flags, false);
15140 }
15141 
15142 /// Return true if base is a frame index, which is known not to alias with
15143 /// anything but itself.  Provides base object and offset as results.
15144 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
15145                            const GlobalValue *&GV, const void *&CV) {
15146   // Assume it is a primitive operation.
15147   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
15148 
15149   // If it's an adding a simple constant then integrate the offset.
15150   if (Base.getOpcode() == ISD::ADD) {
15151     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
15152       Base = Base.getOperand(0);
15153       Offset += C->getZExtValue();
15154     }
15155   }
15156 
15157   // Return the underlying GlobalValue, and update the Offset.  Return false
15158   // for GlobalAddressSDNode since the same GlobalAddress may be represented
15159   // by multiple nodes with different offsets.
15160   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
15161     GV = G->getGlobal();
15162     Offset += G->getOffset();
15163     return false;
15164   }
15165 
15166   // Return the underlying Constant value, and update the Offset.  Return false
15167   // for ConstantSDNodes since the same constant pool entry may be represented
15168   // by multiple nodes with different offsets.
15169   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
15170     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
15171                                          : (const void *)C->getConstVal();
15172     Offset += C->getOffset();
15173     return false;
15174   }
15175   // If it's any of the following then it can't alias with anything but itself.
15176   return isa<FrameIndexSDNode>(Base);
15177 }
15178 
15179 /// Return true if there is any possibility that the two addresses overlap.
15180 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
15181   // If they are the same then they must be aliases.
15182   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
15183 
15184   // If they are both volatile then they cannot be reordered.
15185   if (Op0->isVolatile() && Op1->isVolatile()) return true;
15186 
15187   // If one operation reads from invariant memory, and the other may store, they
15188   // cannot alias. These should really be checking the equivalent of mayWrite,
15189   // but it only matters for memory nodes other than load /store.
15190   if (Op0->isInvariant() && Op1->writeMem())
15191     return false;
15192 
15193   if (Op1->isInvariant() && Op0->writeMem())
15194     return false;
15195 
15196   // Gather base node and offset information.
15197   SDValue Base1, Base2;
15198   int64_t Offset1, Offset2;
15199   const GlobalValue *GV1, *GV2;
15200   const void *CV1, *CV2;
15201   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
15202                                       Base1, Offset1, GV1, CV1);
15203   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
15204                                       Base2, Offset2, GV2, CV2);
15205 
15206   // If they have a same base address then check to see if they overlap.
15207   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
15208     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15209              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15210 
15211   // It is possible for different frame indices to alias each other, mostly
15212   // when tail call optimization reuses return address slots for arguments.
15213   // To catch this case, look up the actual index of frame indices to compute
15214   // the real alias relationship.
15215   if (isFrameIndex1 && isFrameIndex2) {
15216     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
15217     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
15218     Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
15219     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15220              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15221   }
15222 
15223   // Otherwise, if we know what the bases are, and they aren't identical, then
15224   // we know they cannot alias.
15225   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
15226     return false;
15227 
15228   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
15229   // compared to the size and offset of the access, we may be able to prove they
15230   // do not alias.  This check is conservative for now to catch cases created by
15231   // splitting vector types.
15232   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
15233       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
15234       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
15235        Op1->getMemoryVT().getSizeInBits() >> 3) &&
15236       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
15237     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
15238     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
15239 
15240     // There is no overlap between these relatively aligned accesses of similar
15241     // size, return no alias.
15242     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
15243         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
15244       return false;
15245   }
15246 
15247   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
15248                    ? CombinerGlobalAA
15249                    : DAG.getSubtarget().useAA();
15250 #ifndef NDEBUG
15251   if (CombinerAAOnlyFunc.getNumOccurrences() &&
15252       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
15253     UseAA = false;
15254 #endif
15255   if (UseAA &&
15256       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
15257     // Use alias analysis information.
15258     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
15259                                  Op1->getSrcValueOffset());
15260     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
15261         Op0->getSrcValueOffset() - MinOffset;
15262     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
15263         Op1->getSrcValueOffset() - MinOffset;
15264     AliasResult AAResult =
15265         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
15266                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
15267                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
15268                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
15269     if (AAResult == NoAlias)
15270       return false;
15271   }
15272 
15273   // Otherwise we have to assume they alias.
15274   return true;
15275 }
15276 
15277 /// Walk up chain skipping non-aliasing memory nodes,
15278 /// looking for aliasing nodes and adding them to the Aliases vector.
15279 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
15280                                    SmallVectorImpl<SDValue> &Aliases) {
15281   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
15282   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
15283 
15284   // Get alias information for node.
15285   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
15286 
15287   // Starting off.
15288   Chains.push_back(OriginalChain);
15289   unsigned Depth = 0;
15290 
15291   // Look at each chain and determine if it is an alias.  If so, add it to the
15292   // aliases list.  If not, then continue up the chain looking for the next
15293   // candidate.
15294   while (!Chains.empty()) {
15295     SDValue Chain = Chains.pop_back_val();
15296 
15297     // For TokenFactor nodes, look at each operand and only continue up the
15298     // chain until we reach the depth limit.
15299     //
15300     // FIXME: The depth check could be made to return the last non-aliasing
15301     // chain we found before we hit a tokenfactor rather than the original
15302     // chain.
15303     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
15304       Aliases.clear();
15305       Aliases.push_back(OriginalChain);
15306       return;
15307     }
15308 
15309     // Don't bother if we've been before.
15310     if (!Visited.insert(Chain.getNode()).second)
15311       continue;
15312 
15313     switch (Chain.getOpcode()) {
15314     case ISD::EntryToken:
15315       // Entry token is ideal chain operand, but handled in FindBetterChain.
15316       break;
15317 
15318     case ISD::LOAD:
15319     case ISD::STORE: {
15320       // Get alias information for Chain.
15321       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
15322           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
15323 
15324       // If chain is alias then stop here.
15325       if (!(IsLoad && IsOpLoad) &&
15326           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
15327         Aliases.push_back(Chain);
15328       } else {
15329         // Look further up the chain.
15330         Chains.push_back(Chain.getOperand(0));
15331         ++Depth;
15332       }
15333       break;
15334     }
15335 
15336     case ISD::TokenFactor:
15337       // We have to check each of the operands of the token factor for "small"
15338       // token factors, so we queue them up.  Adding the operands to the queue
15339       // (stack) in reverse order maintains the original order and increases the
15340       // likelihood that getNode will find a matching token factor (CSE.)
15341       if (Chain.getNumOperands() > 16) {
15342         Aliases.push_back(Chain);
15343         break;
15344       }
15345       for (unsigned n = Chain.getNumOperands(); n;)
15346         Chains.push_back(Chain.getOperand(--n));
15347       ++Depth;
15348       break;
15349 
15350     default:
15351       // For all other instructions we will just have to take what we can get.
15352       Aliases.push_back(Chain);
15353       break;
15354     }
15355   }
15356 }
15357 
15358 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
15359 /// (aliasing node.)
15360 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
15361   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
15362 
15363   // Accumulate all the aliases to this node.
15364   GatherAllAliases(N, OldChain, Aliases);
15365 
15366   // If no operands then chain to entry token.
15367   if (Aliases.size() == 0)
15368     return DAG.getEntryNode();
15369 
15370   // If a single operand then chain to it.  We don't need to revisit it.
15371   if (Aliases.size() == 1)
15372     return Aliases[0];
15373 
15374   // Construct a custom tailored token factor.
15375   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
15376 }
15377 
15378 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
15379   // This holds the base pointer, index, and the offset in bytes from the base
15380   // pointer.
15381   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
15382 
15383   // We must have a base and an offset.
15384   if (!BasePtr.Base.getNode())
15385     return false;
15386 
15387   // Do not handle stores to undef base pointers.
15388   if (BasePtr.Base.isUndef())
15389     return false;
15390 
15391   SmallVector<StoreSDNode *, 8> ChainedStores;
15392   ChainedStores.push_back(St);
15393 
15394   // Walk up the chain and look for nodes with offsets from the same
15395   // base pointer. Stop when reaching an instruction with a different kind
15396   // or instruction which has a different base pointer.
15397   StoreSDNode *Index = St;
15398   while (Index) {
15399     // If the chain has more than one use, then we can't reorder the mem ops.
15400     if (Index != St && !SDValue(Index, 0)->hasOneUse())
15401       break;
15402 
15403     if (Index->isVolatile() || Index->isIndexed())
15404       break;
15405 
15406     // Find the base pointer and offset for this memory node.
15407     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
15408 
15409     // Check that the base pointer is the same as the original one.
15410     if (!Ptr.equalBaseIndex(BasePtr))
15411       break;
15412 
15413     // Find the next memory operand in the chain. If the next operand in the
15414     // chain is a store then move up and continue the scan with the next
15415     // memory operand. If the next operand is a load save it and use alias
15416     // information to check if it interferes with anything.
15417     SDNode *NextInChain = Index->getChain().getNode();
15418     while (true) {
15419       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
15420         // We found a store node. Use it for the next iteration.
15421         if (STn->isVolatile() || STn->isIndexed()) {
15422           Index = nullptr;
15423           break;
15424         }
15425         ChainedStores.push_back(STn);
15426         Index = STn;
15427         break;
15428       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
15429         NextInChain = Ldn->getChain().getNode();
15430         continue;
15431       } else {
15432         Index = nullptr;
15433         break;
15434       }
15435     }
15436   }
15437 
15438   bool MadeChangeToSt = false;
15439   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15440 
15441   for (StoreSDNode *ChainedStore : ChainedStores) {
15442     SDValue Chain = ChainedStore->getChain();
15443     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15444 
15445     if (Chain != BetterChain) {
15446       if (ChainedStore == St)
15447         MadeChangeToSt = true;
15448       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15449     }
15450   }
15451 
15452   // Do all replacements after finding the replacements to make to avoid making
15453   // the chains more complicated by introducing new TokenFactors.
15454   for (auto Replacement : BetterChains)
15455     replaceStoreChain(Replacement.first, Replacement.second);
15456 
15457   return MadeChangeToSt;
15458 }
15459 
15460 /// This is the entry point for the file.
15461 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15462                            CodeGenOpt::Level OptLevel) {
15463   /// This is the main entry point to this class.
15464   DAGCombiner(*this, AA, OptLevel).Run(Level);
15465 }
15466