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/ADT/SetVector.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.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/SelectionDAG.h"
28 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include <algorithm>
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "dagcombine"
46 
47 STATISTIC(NodesCombined   , "Number of dag nodes combined");
48 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
49 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
50 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
51 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
52 STATISTIC(SlicedLoads, "Number of load sliced");
53 
54 namespace {
55   static cl::opt<bool>
56     CombinerAA("combiner-alias-analysis", cl::Hidden,
57                cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 
59   static cl::opt<bool>
60     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
61                cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 
63   static cl::opt<bool>
64     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
65                cl::desc("Enable DAG combiner's use of TBAA"));
66 
67 #ifndef NDEBUG
68   static cl::opt<std::string>
69     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
70                cl::desc("Only use DAG-combiner alias analysis in this"
71                         " function"));
72 #endif
73 
74   /// Hidden option to stress test load slicing, i.e., when this option
75   /// is enabled, load slicing bypasses most of its profitability guards.
76   static cl::opt<bool>
77   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
78                     cl::desc("Bypass the profitability model of load "
79                              "slicing"),
80                     cl::init(false));
81 
82   static cl::opt<bool>
83     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
84                       cl::desc("DAG combiner may split indexing from loads"));
85 
86 //------------------------------ DAGCombiner ---------------------------------//
87 
88   class DAGCombiner {
89     SelectionDAG &DAG;
90     const TargetLowering &TLI;
91     CombineLevel Level;
92     CodeGenOpt::Level OptLevel;
93     bool LegalOperations;
94     bool LegalTypes;
95     bool ForCodeSize;
96 
97     /// \brief Worklist of all of the nodes that need to be simplified.
98     ///
99     /// This must behave as a stack -- new nodes to process are pushed onto the
100     /// back and when processing we pop off of the back.
101     ///
102     /// The worklist will not contain duplicates but may contain null entries
103     /// due to nodes being deleted from the underlying DAG.
104     SmallVector<SDNode *, 64> Worklist;
105 
106     /// \brief Mapping from an SDNode to its position on the worklist.
107     ///
108     /// This is used to find and remove nodes from the worklist (by nulling
109     /// them) when they are deleted from the underlying DAG. It relies on
110     /// stable indices of nodes within the worklist.
111     DenseMap<SDNode *, unsigned> WorklistMap;
112 
113     /// \brief Set of nodes which have been combined (at least once).
114     ///
115     /// This is used to allow us to reliably add any operands of a DAG node
116     /// which have not yet been combined to the worklist.
117     SmallPtrSet<SDNode *, 32> CombinedNodes;
118 
119     // AA - Used for DAG load/store alias analysis.
120     AliasAnalysis &AA;
121 
122     /// When an instruction is simplified, add all users of the instruction to
123     /// the work lists because they might get more simplified now.
124     void AddUsersToWorklist(SDNode *N) {
125       for (SDNode *Node : N->uses())
126         AddToWorklist(Node);
127     }
128 
129     /// Call the node-specific routine that folds each particular type of node.
130     SDValue visit(SDNode *N);
131 
132   public:
133     /// Add to the worklist making sure its instance is at the back (next to be
134     /// processed.)
135     void AddToWorklist(SDNode *N) {
136       // Skip handle nodes as they can't usefully be combined and confuse the
137       // zero-use deletion strategy.
138       if (N->getOpcode() == ISD::HANDLENODE)
139         return;
140 
141       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
142         Worklist.push_back(N);
143     }
144 
145     /// Remove all instances of N from the worklist.
146     void removeFromWorklist(SDNode *N) {
147       CombinedNodes.erase(N);
148 
149       auto It = WorklistMap.find(N);
150       if (It == WorklistMap.end())
151         return; // Not in the worklist.
152 
153       // Null out the entry rather than erasing it to avoid a linear operation.
154       Worklist[It->second] = nullptr;
155       WorklistMap.erase(It);
156     }
157 
158     void deleteAndRecombine(SDNode *N);
159     bool recursivelyDeleteUnusedNodes(SDNode *N);
160 
161     /// Replaces all uses of the results of one DAG node with new values.
162     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
163                       bool AddTo = true);
164 
165     /// Replaces all uses of the results of one DAG node with new values.
166     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
167       return CombineTo(N, &Res, 1, AddTo);
168     }
169 
170     /// Replaces all uses of the results of one DAG node with new values.
171     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
172                       bool AddTo = true) {
173       SDValue To[] = { Res0, Res1 };
174       return CombineTo(N, To, 2, AddTo);
175     }
176 
177     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
178 
179   private:
180 
181     /// Check the specified integer node value to see if it can be simplified or
182     /// if things it uses can be simplified by bit propagation.
183     /// If so, return true.
184     bool SimplifyDemandedBits(SDValue Op) {
185       unsigned BitWidth = Op.getScalarValueSizeInBits();
186       APInt Demanded = APInt::getAllOnesValue(BitWidth);
187       return SimplifyDemandedBits(Op, Demanded);
188     }
189 
190     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
191 
192     bool CombineToPreIndexedLoadStore(SDNode *N);
193     bool CombineToPostIndexedLoadStore(SDNode *N);
194     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
195     bool SliceUpLoad(SDNode *N);
196 
197     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
198     ///   load.
199     ///
200     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
201     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
202     /// \param EltNo index of the vector element to load.
203     /// \param OriginalLoad load that EVE came from to be replaced.
204     /// \returns EVE on success SDValue() on failure.
205     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
206         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
207     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
208     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
209     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
210     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
211     SDValue PromoteIntBinOp(SDValue Op);
212     SDValue PromoteIntShiftOp(SDValue Op);
213     SDValue PromoteExtend(SDValue Op);
214     bool PromoteLoad(SDValue Op);
215 
216     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
217                          SDValue ExtLoad, const SDLoc &DL,
218                          ISD::NodeType ExtType);
219 
220     /// Call the node-specific routine that knows how to fold each
221     /// particular type of node. If that doesn't do anything, try the
222     /// target-specific DAG combines.
223     SDValue combine(SDNode *N);
224 
225     // Visitation implementation - Implement dag node combining for different
226     // node types.  The semantics are as follows:
227     // Return Value:
228     //   SDValue.getNode() == 0 - No change was made
229     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
230     //   otherwise              - N should be replaced by the returned Operand.
231     //
232     SDValue visitTokenFactor(SDNode *N);
233     SDValue visitMERGE_VALUES(SDNode *N);
234     SDValue visitADD(SDNode *N);
235     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
236     SDValue visitSUB(SDNode *N);
237     SDValue visitADDC(SDNode *N);
238     SDValue visitSUBC(SDNode *N);
239     SDValue visitADDE(SDNode *N);
240     SDValue visitSUBE(SDNode *N);
241     SDValue visitMUL(SDNode *N);
242     SDValue useDivRem(SDNode *N);
243     SDValue visitSDIV(SDNode *N);
244     SDValue visitUDIV(SDNode *N);
245     SDValue visitREM(SDNode *N);
246     SDValue visitMULHU(SDNode *N);
247     SDValue visitMULHS(SDNode *N);
248     SDValue visitSMUL_LOHI(SDNode *N);
249     SDValue visitUMUL_LOHI(SDNode *N);
250     SDValue visitSMULO(SDNode *N);
251     SDValue visitUMULO(SDNode *N);
252     SDValue visitIMINMAX(SDNode *N);
253     SDValue visitAND(SDNode *N);
254     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
255     SDValue visitOR(SDNode *N);
256     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
257     SDValue visitXOR(SDNode *N);
258     SDValue SimplifyVBinOp(SDNode *N);
259     SDValue visitSHL(SDNode *N);
260     SDValue visitSRA(SDNode *N);
261     SDValue visitSRL(SDNode *N);
262     SDValue visitRotate(SDNode *N);
263     SDValue visitBSWAP(SDNode *N);
264     SDValue visitBITREVERSE(SDNode *N);
265     SDValue visitCTLZ(SDNode *N);
266     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
267     SDValue visitCTTZ(SDNode *N);
268     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
269     SDValue visitCTPOP(SDNode *N);
270     SDValue visitSELECT(SDNode *N);
271     SDValue visitVSELECT(SDNode *N);
272     SDValue visitSELECT_CC(SDNode *N);
273     SDValue visitSETCC(SDNode *N);
274     SDValue visitSETCCE(SDNode *N);
275     SDValue visitSIGN_EXTEND(SDNode *N);
276     SDValue visitZERO_EXTEND(SDNode *N);
277     SDValue visitANY_EXTEND(SDNode *N);
278     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
279     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
280     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
281     SDValue visitTRUNCATE(SDNode *N);
282     SDValue visitBITCAST(SDNode *N);
283     SDValue visitBUILD_PAIR(SDNode *N);
284     SDValue visitFADD(SDNode *N);
285     SDValue visitFSUB(SDNode *N);
286     SDValue visitFMUL(SDNode *N);
287     SDValue visitFMA(SDNode *N);
288     SDValue visitFDIV(SDNode *N);
289     SDValue visitFREM(SDNode *N);
290     SDValue visitFSQRT(SDNode *N);
291     SDValue visitFCOPYSIGN(SDNode *N);
292     SDValue visitSINT_TO_FP(SDNode *N);
293     SDValue visitUINT_TO_FP(SDNode *N);
294     SDValue visitFP_TO_SINT(SDNode *N);
295     SDValue visitFP_TO_UINT(SDNode *N);
296     SDValue visitFP_ROUND(SDNode *N);
297     SDValue visitFP_ROUND_INREG(SDNode *N);
298     SDValue visitFP_EXTEND(SDNode *N);
299     SDValue visitFNEG(SDNode *N);
300     SDValue visitFABS(SDNode *N);
301     SDValue visitFCEIL(SDNode *N);
302     SDValue visitFTRUNC(SDNode *N);
303     SDValue visitFFLOOR(SDNode *N);
304     SDValue visitFMINNUM(SDNode *N);
305     SDValue visitFMAXNUM(SDNode *N);
306     SDValue visitBRCOND(SDNode *N);
307     SDValue visitBR_CC(SDNode *N);
308     SDValue visitLOAD(SDNode *N);
309 
310     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
311     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
312 
313     SDValue visitSTORE(SDNode *N);
314     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
315     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
316     SDValue visitBUILD_VECTOR(SDNode *N);
317     SDValue visitCONCAT_VECTORS(SDNode *N);
318     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
319     SDValue visitVECTOR_SHUFFLE(SDNode *N);
320     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
321     SDValue visitINSERT_SUBVECTOR(SDNode *N);
322     SDValue visitMLOAD(SDNode *N);
323     SDValue visitMSTORE(SDNode *N);
324     SDValue visitMGATHER(SDNode *N);
325     SDValue visitMSCATTER(SDNode *N);
326     SDValue visitFP_TO_FP16(SDNode *N);
327     SDValue visitFP16_TO_FP(SDNode *N);
328 
329     SDValue visitFADDForFMACombine(SDNode *N);
330     SDValue visitFSUBForFMACombine(SDNode *N);
331     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
332 
333     SDValue XformToShuffleWithZero(SDNode *N);
334     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
335                            SDValue RHS);
336 
337     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
338 
339     SDValue foldSelectOfConstants(SDNode *N);
340     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
341     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
342     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
343     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
344                              SDValue N2, SDValue N3, ISD::CondCode CC,
345                              bool NotExtCompare = false);
346     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
347                                    SDValue N2, SDValue N3, ISD::CondCode CC);
348     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
349                           const SDLoc &DL, bool foldBooleans = true);
350 
351     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
352                            SDValue &CC) const;
353     bool isOneUseSetCC(SDValue N) const;
354 
355     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
356                                          unsigned HiOp);
357     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
358     SDValue CombineExtLoad(SDNode *N);
359     SDValue combineRepeatedFPDivisors(SDNode *N);
360     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
361     SDValue BuildSDIV(SDNode *N);
362     SDValue BuildSDIVPow2(SDNode *N);
363     SDValue BuildUDIV(SDNode *N);
364     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
365     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
366     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
367     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
368     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
369     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
370                                 SDNodeFlags *Flags, bool Reciprocal);
371     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
372                                 SDNodeFlags *Flags, bool Reciprocal);
373     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
374                                bool DemandHighBits = true);
375     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
376     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
377                               SDValue InnerPos, SDValue InnerNeg,
378                               unsigned PosOpcode, unsigned NegOpcode,
379                               const SDLoc &DL);
380     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
381     SDValue MatchLoadCombine(SDNode *N);
382     SDValue ReduceLoadWidth(SDNode *N);
383     SDValue ReduceLoadOpStoreWidth(SDNode *N);
384     SDValue splitMergedValStore(StoreSDNode *ST);
385     SDValue TransformFPLoadStorePair(SDNode *N);
386     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
387     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
388     SDValue reduceBuildVecToShuffle(SDNode *N);
389     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
390                                   ArrayRef<int> VectorMask, SDValue VecIn1,
391                                   SDValue VecIn2, unsigned LeftIdx);
392 
393     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
394 
395     /// Walk up chain skipping non-aliasing memory nodes,
396     /// looking for aliasing nodes and adding them to the Aliases vector.
397     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
398                           SmallVectorImpl<SDValue> &Aliases);
399 
400     /// Return true if there is any possibility that the two addresses overlap.
401     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
402 
403     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
404     /// chain (aliasing node.)
405     SDValue FindBetterChain(SDNode *N, SDValue Chain);
406 
407     /// Try to replace a store and any possibly adjacent stores on
408     /// consecutive chains with better chains. Return true only if St is
409     /// replaced.
410     ///
411     /// Notice that other chains may still be replaced even if the function
412     /// returns false.
413     bool findBetterNeighborChains(StoreSDNode *St);
414 
415     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
416     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
417 
418     /// Holds a pointer to an LSBaseSDNode as well as information on where it
419     /// is located in a sequence of memory operations connected by a chain.
420     struct MemOpLink {
421       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
422       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
423       // Ptr to the mem node.
424       LSBaseSDNode *MemNode;
425       // Offset from the base ptr.
426       int64_t OffsetFromBase;
427       // What is the sequence number of this mem node.
428       // Lowest mem operand in the DAG starts at zero.
429       unsigned SequenceNum;
430     };
431 
432     /// This is a helper function for visitMUL to check the profitability
433     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
434     /// MulNode is the original multiply, AddNode is (add x, c1),
435     /// and ConstNode is c2.
436     bool isMulAddWithConstProfitable(SDNode *MulNode,
437                                      SDValue &AddNode,
438                                      SDValue &ConstNode);
439 
440     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
441     /// constant build_vector of the stored constant values in Stores.
442     SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL,
443                                          ArrayRef<MemOpLink> Stores,
444                                          SmallVectorImpl<SDValue> &Chains,
445                                          EVT Ty) const;
446 
447     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
448     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
449     /// the type of the loaded value to be extended.  LoadedVT returns the type
450     /// of the original loaded value.  NarrowLoad returns whether the load would
451     /// need to be narrowed in order to match.
452     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
453                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
454                           bool &NarrowLoad);
455 
456     /// This is a helper function for MergeConsecutiveStores. When the source
457     /// elements of the consecutive stores are all constants or all extracted
458     /// vector elements, try to merge them into one larger store.
459     /// \return number of stores that were merged into a merged store (always
460     /// a prefix of \p StoreNode).
461     bool MergeStoresOfConstantsOrVecElts(
462         SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
463         bool IsConstantSrc, bool UseVector);
464 
465     /// This is a helper function for MergeConsecutiveStores.
466     /// Stores that may be merged are placed in StoreNodes.
467     /// Loads that may alias with those stores are placed in AliasLoadNodes.
468     void getStoreMergeAndAliasCandidates(
469         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
470         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
471 
472     /// Helper function for MergeConsecutiveStores. Checks if
473     /// Candidate stores have indirect dependency through their
474     /// operands. \return True if safe to merge
475     bool checkMergeStoreCandidatesForDependencies(
476         SmallVectorImpl<MemOpLink> &StoreNodes);
477 
478     /// Merge consecutive store operations into a wide store.
479     /// This optimization uses wide integers or vectors when possible.
480     /// \return number of stores that were merged into a merged store (the
481     /// affected nodes are stored as a prefix in \p StoreNodes).
482     bool MergeConsecutiveStores(StoreSDNode *N,
483                                 SmallVectorImpl<MemOpLink> &StoreNodes);
484 
485     /// \brief Try to transform a truncation where C is a constant:
486     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
487     ///
488     /// \p N needs to be a truncation and its first operand an AND. Other
489     /// requirements are checked by the function (e.g. that trunc is
490     /// single-use) and if missed an empty SDValue is returned.
491     SDValue distributeTruncateThroughAnd(SDNode *N);
492 
493   public:
494     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
495         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
496           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
497       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
498     }
499 
500     /// Runs the dag combiner on all nodes in the work list
501     void Run(CombineLevel AtLevel);
502 
503     SelectionDAG &getDAG() const { return DAG; }
504 
505     /// Returns a type large enough to hold any valid shift amount - before type
506     /// legalization these can be huge.
507     EVT getShiftAmountTy(EVT LHSTy) {
508       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
509       if (LHSTy.isVector())
510         return LHSTy;
511       auto &DL = DAG.getDataLayout();
512       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
513                         : TLI.getPointerTy(DL);
514     }
515 
516     /// This method returns true if we are running before type legalization or
517     /// if the specified VT is legal.
518     bool isTypeLegal(const EVT &VT) {
519       if (!LegalTypes) return true;
520       return TLI.isTypeLegal(VT);
521     }
522 
523     /// Convenience wrapper around TargetLowering::getSetCCResultType
524     EVT getSetCCResultType(EVT VT) const {
525       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
526     }
527   };
528 }
529 
530 
531 namespace {
532 /// This class is a DAGUpdateListener that removes any deleted
533 /// nodes from the worklist.
534 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
535   DAGCombiner &DC;
536 public:
537   explicit WorklistRemover(DAGCombiner &dc)
538     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
539 
540   void NodeDeleted(SDNode *N, SDNode *E) override {
541     DC.removeFromWorklist(N);
542   }
543 };
544 }
545 
546 //===----------------------------------------------------------------------===//
547 //  TargetLowering::DAGCombinerInfo implementation
548 //===----------------------------------------------------------------------===//
549 
550 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
551   ((DAGCombiner*)DC)->AddToWorklist(N);
552 }
553 
554 SDValue TargetLowering::DAGCombinerInfo::
555 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
556   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
557 }
558 
559 SDValue TargetLowering::DAGCombinerInfo::
560 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
561   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
562 }
563 
564 
565 SDValue TargetLowering::DAGCombinerInfo::
566 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
567   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
568 }
569 
570 void TargetLowering::DAGCombinerInfo::
571 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
572   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
573 }
574 
575 //===----------------------------------------------------------------------===//
576 // Helper Functions
577 //===----------------------------------------------------------------------===//
578 
579 void DAGCombiner::deleteAndRecombine(SDNode *N) {
580   removeFromWorklist(N);
581 
582   // If the operands of this node are only used by the node, they will now be
583   // dead. Make sure to re-visit them and recursively delete dead nodes.
584   for (const SDValue &Op : N->ops())
585     // For an operand generating multiple values, one of the values may
586     // become dead allowing further simplification (e.g. split index
587     // arithmetic from an indexed load).
588     if (Op->hasOneUse() || Op->getNumValues() > 1)
589       AddToWorklist(Op.getNode());
590 
591   DAG.DeleteNode(N);
592 }
593 
594 /// Return 1 if we can compute the negated form of the specified expression for
595 /// the same cost as the expression itself, or 2 if we can compute the negated
596 /// form more cheaply than the expression itself.
597 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
598                                const TargetLowering &TLI,
599                                const TargetOptions *Options,
600                                unsigned Depth = 0) {
601   // fneg is removable even if it has multiple uses.
602   if (Op.getOpcode() == ISD::FNEG) return 2;
603 
604   // Don't allow anything with multiple uses.
605   if (!Op.hasOneUse()) return 0;
606 
607   // Don't recurse exponentially.
608   if (Depth > 6) return 0;
609 
610   switch (Op.getOpcode()) {
611   default: return false;
612   case ISD::ConstantFP: {
613     if (!LegalOperations)
614       return 1;
615 
616     // Don't invert constant FP values after legalization unless the target says
617     // the negated constant is legal.
618     EVT VT = Op.getValueType();
619     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
620       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
621   }
622   case ISD::FADD:
623     // FIXME: determine better conditions for this xform.
624     if (!Options->UnsafeFPMath) return 0;
625 
626     // After operation legalization, it might not be legal to create new FSUBs.
627     if (LegalOperations &&
628         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
629       return 0;
630 
631     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
632     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
633                                     Options, Depth + 1))
634       return V;
635     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
636     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
637                               Depth + 1);
638   case ISD::FSUB:
639     // We can't turn -(A-B) into B-A when we honor signed zeros.
640     if (!Options->NoSignedZerosFPMath &&
641         !Op.getNode()->getFlags()->hasNoSignedZeros())
642       return 0;
643 
644     // fold (fneg (fsub A, B)) -> (fsub B, A)
645     return 1;
646 
647   case ISD::FMUL:
648   case ISD::FDIV:
649     if (Options->HonorSignDependentRoundingFPMath()) return 0;
650 
651     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
652     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
653                                     Options, Depth + 1))
654       return V;
655 
656     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
657                               Depth + 1);
658 
659   case ISD::FP_EXTEND:
660   case ISD::FP_ROUND:
661   case ISD::FSIN:
662     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
663                               Depth + 1);
664   }
665 }
666 
667 /// If isNegatibleForFree returns true, return the newly negated expression.
668 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
669                                     bool LegalOperations, unsigned Depth = 0) {
670   const TargetOptions &Options = DAG.getTarget().Options;
671   // fneg is removable even if it has multiple uses.
672   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
673 
674   // Don't allow anything with multiple uses.
675   assert(Op.hasOneUse() && "Unknown reuse!");
676 
677   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
678 
679   const SDNodeFlags *Flags = Op.getNode()->getFlags();
680 
681   switch (Op.getOpcode()) {
682   default: llvm_unreachable("Unknown code");
683   case ISD::ConstantFP: {
684     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
685     V.changeSign();
686     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
687   }
688   case ISD::FADD:
689     // FIXME: determine better conditions for this xform.
690     assert(Options.UnsafeFPMath);
691 
692     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
693     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
694                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
695       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
696                          GetNegatedExpression(Op.getOperand(0), DAG,
697                                               LegalOperations, Depth+1),
698                          Op.getOperand(1), Flags);
699     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
700     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
701                        GetNegatedExpression(Op.getOperand(1), DAG,
702                                             LegalOperations, Depth+1),
703                        Op.getOperand(0), Flags);
704   case ISD::FSUB:
705     // fold (fneg (fsub 0, B)) -> B
706     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
707       if (N0CFP->isZero())
708         return Op.getOperand(1);
709 
710     // fold (fneg (fsub A, B)) -> (fsub B, A)
711     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
712                        Op.getOperand(1), Op.getOperand(0), Flags);
713 
714   case ISD::FMUL:
715   case ISD::FDIV:
716     assert(!Options.HonorSignDependentRoundingFPMath());
717 
718     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
719     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
720                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
721       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
722                          GetNegatedExpression(Op.getOperand(0), DAG,
723                                               LegalOperations, Depth+1),
724                          Op.getOperand(1), Flags);
725 
726     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
727     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
728                        Op.getOperand(0),
729                        GetNegatedExpression(Op.getOperand(1), DAG,
730                                             LegalOperations, Depth+1), Flags);
731 
732   case ISD::FP_EXTEND:
733   case ISD::FSIN:
734     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
735                        GetNegatedExpression(Op.getOperand(0), DAG,
736                                             LegalOperations, Depth+1));
737   case ISD::FP_ROUND:
738       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
739                          GetNegatedExpression(Op.getOperand(0), DAG,
740                                               LegalOperations, Depth+1),
741                          Op.getOperand(1));
742   }
743 }
744 
745 // APInts must be the same size for most operations, this helper
746 // function zero extends the shorter of the pair so that they match.
747 // We provide an Offset so that we can create bitwidths that won't overflow.
748 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
749   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
750   LHS = LHS.zextOrSelf(Bits);
751   RHS = RHS.zextOrSelf(Bits);
752 }
753 
754 // Return true if this node is a setcc, or is a select_cc
755 // that selects between the target values used for true and false, making it
756 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
757 // the appropriate nodes based on the type of node we are checking. This
758 // simplifies life a bit for the callers.
759 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
760                                     SDValue &CC) const {
761   if (N.getOpcode() == ISD::SETCC) {
762     LHS = N.getOperand(0);
763     RHS = N.getOperand(1);
764     CC  = N.getOperand(2);
765     return true;
766   }
767 
768   if (N.getOpcode() != ISD::SELECT_CC ||
769       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
770       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
771     return false;
772 
773   if (TLI.getBooleanContents(N.getValueType()) ==
774       TargetLowering::UndefinedBooleanContent)
775     return false;
776 
777   LHS = N.getOperand(0);
778   RHS = N.getOperand(1);
779   CC  = N.getOperand(4);
780   return true;
781 }
782 
783 /// Return true if this is a SetCC-equivalent operation with only one use.
784 /// If this is true, it allows the users to invert the operation for free when
785 /// it is profitable to do so.
786 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
787   SDValue N0, N1, N2;
788   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
789     return true;
790   return false;
791 }
792 
793 // \brief Returns the SDNode if it is a constant float BuildVector
794 // or constant float.
795 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
796   if (isa<ConstantFPSDNode>(N))
797     return N.getNode();
798   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
799     return N.getNode();
800   return nullptr;
801 }
802 
803 // Determines if it is a constant integer or a build vector of constant
804 // integers (and undefs).
805 // Do not permit build vector implicit truncation.
806 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
807   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
808     return !(Const->isOpaque() && NoOpaques);
809   if (N.getOpcode() != ISD::BUILD_VECTOR)
810     return false;
811   unsigned BitWidth = N.getScalarValueSizeInBits();
812   for (const SDValue &Op : N->op_values()) {
813     if (Op.isUndef())
814       continue;
815     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
816     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
817         (Const->isOpaque() && NoOpaques))
818       return false;
819   }
820   return true;
821 }
822 
823 // Determines if it is a constant null integer or a splatted vector of a
824 // constant null integer (with no undefs).
825 // Build vector implicit truncation is not an issue for null values.
826 static bool isNullConstantOrNullSplatConstant(SDValue N) {
827   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
828     return Splat->isNullValue();
829   return false;
830 }
831 
832 // Determines if it is a constant integer of one or a splatted vector of a
833 // constant integer of one (with no undefs).
834 // Do not permit build vector implicit truncation.
835 static bool isOneConstantOrOneSplatConstant(SDValue N) {
836   unsigned BitWidth = N.getScalarValueSizeInBits();
837   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
838     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
839   return false;
840 }
841 
842 // Determines if it is a constant integer of all ones or a splatted vector of a
843 // constant integer of all ones (with no undefs).
844 // Do not permit build vector implicit truncation.
845 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
846   unsigned BitWidth = N.getScalarValueSizeInBits();
847   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
848     return Splat->isAllOnesValue() &&
849            Splat->getAPIntValue().getBitWidth() == BitWidth;
850   return false;
851 }
852 
853 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
854 // undef's.
855 static bool isAnyConstantBuildVector(const SDNode *N) {
856   return ISD::isBuildVectorOfConstantSDNodes(N) ||
857          ISD::isBuildVectorOfConstantFPSDNodes(N);
858 }
859 
860 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
861                                     SDValue N1) {
862   EVT VT = N0.getValueType();
863   if (N0.getOpcode() == Opc) {
864     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
865       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
866         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
867         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
868           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
869         return SDValue();
870       }
871       if (N0.hasOneUse()) {
872         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
873         // use
874         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
875         if (!OpNode.getNode())
876           return SDValue();
877         AddToWorklist(OpNode.getNode());
878         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
879       }
880     }
881   }
882 
883   if (N1.getOpcode() == Opc) {
884     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
885       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
886         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
887         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
888           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
889         return SDValue();
890       }
891       if (N1.hasOneUse()) {
892         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
893         // use
894         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
895         if (!OpNode.getNode())
896           return SDValue();
897         AddToWorklist(OpNode.getNode());
898         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
899       }
900     }
901   }
902 
903   return SDValue();
904 }
905 
906 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
907                                bool AddTo) {
908   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
909   ++NodesCombined;
910   DEBUG(dbgs() << "\nReplacing.1 ";
911         N->dump(&DAG);
912         dbgs() << "\nWith: ";
913         To[0].getNode()->dump(&DAG);
914         dbgs() << " and " << NumTo-1 << " other values\n");
915   for (unsigned i = 0, e = NumTo; i != e; ++i)
916     assert((!To[i].getNode() ||
917             N->getValueType(i) == To[i].getValueType()) &&
918            "Cannot combine value to value of different type!");
919 
920   WorklistRemover DeadNodes(*this);
921   DAG.ReplaceAllUsesWith(N, To);
922   if (AddTo) {
923     // Push the new nodes and any users onto the worklist
924     for (unsigned i = 0, e = NumTo; i != e; ++i) {
925       if (To[i].getNode()) {
926         AddToWorklist(To[i].getNode());
927         AddUsersToWorklist(To[i].getNode());
928       }
929     }
930   }
931 
932   // Finally, if the node is now dead, remove it from the graph.  The node
933   // may not be dead if the replacement process recursively simplified to
934   // something else needing this node.
935   if (N->use_empty())
936     deleteAndRecombine(N);
937   return SDValue(N, 0);
938 }
939 
940 void DAGCombiner::
941 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
942   // Replace all uses.  If any nodes become isomorphic to other nodes and
943   // are deleted, make sure to remove them from our worklist.
944   WorklistRemover DeadNodes(*this);
945   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
946 
947   // Push the new node and any (possibly new) users onto the worklist.
948   AddToWorklist(TLO.New.getNode());
949   AddUsersToWorklist(TLO.New.getNode());
950 
951   // Finally, if the node is now dead, remove it from the graph.  The node
952   // may not be dead if the replacement process recursively simplified to
953   // something else needing this node.
954   if (TLO.Old.getNode()->use_empty())
955     deleteAndRecombine(TLO.Old.getNode());
956 }
957 
958 /// Check the specified integer node value to see if it can be simplified or if
959 /// things it uses can be simplified by bit propagation. If so, return true.
960 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
961   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
962   APInt KnownZero, KnownOne;
963   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
964     return false;
965 
966   // Revisit the node.
967   AddToWorklist(Op.getNode());
968 
969   // Replace the old value with the new one.
970   ++NodesCombined;
971   DEBUG(dbgs() << "\nReplacing.2 ";
972         TLO.Old.getNode()->dump(&DAG);
973         dbgs() << "\nWith: ";
974         TLO.New.getNode()->dump(&DAG);
975         dbgs() << '\n');
976 
977   CommitTargetLoweringOpt(TLO);
978   return true;
979 }
980 
981 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
982   SDLoc DL(Load);
983   EVT VT = Load->getValueType(0);
984   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
985 
986   DEBUG(dbgs() << "\nReplacing.9 ";
987         Load->dump(&DAG);
988         dbgs() << "\nWith: ";
989         Trunc.getNode()->dump(&DAG);
990         dbgs() << '\n');
991   WorklistRemover DeadNodes(*this);
992   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
993   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
994   deleteAndRecombine(Load);
995   AddToWorklist(Trunc.getNode());
996 }
997 
998 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
999   Replace = false;
1000   SDLoc DL(Op);
1001   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1002     LoadSDNode *LD = cast<LoadSDNode>(Op);
1003     EVT MemVT = LD->getMemoryVT();
1004     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1005       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1006                                                        : ISD::EXTLOAD)
1007       : LD->getExtensionType();
1008     Replace = true;
1009     return DAG.getExtLoad(ExtType, DL, PVT,
1010                           LD->getChain(), LD->getBasePtr(),
1011                           MemVT, LD->getMemOperand());
1012   }
1013 
1014   unsigned Opc = Op.getOpcode();
1015   switch (Opc) {
1016   default: break;
1017   case ISD::AssertSext:
1018     return DAG.getNode(ISD::AssertSext, DL, PVT,
1019                        SExtPromoteOperand(Op.getOperand(0), PVT),
1020                        Op.getOperand(1));
1021   case ISD::AssertZext:
1022     return DAG.getNode(ISD::AssertZext, DL, PVT,
1023                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1024                        Op.getOperand(1));
1025   case ISD::Constant: {
1026     unsigned ExtOpc =
1027       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1028     return DAG.getNode(ExtOpc, DL, PVT, Op);
1029   }
1030   }
1031 
1032   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1033     return SDValue();
1034   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1035 }
1036 
1037 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1038   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1039     return SDValue();
1040   EVT OldVT = Op.getValueType();
1041   SDLoc DL(Op);
1042   bool Replace = false;
1043   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1044   if (!NewOp.getNode())
1045     return SDValue();
1046   AddToWorklist(NewOp.getNode());
1047 
1048   if (Replace)
1049     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1050   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1051                      DAG.getValueType(OldVT));
1052 }
1053 
1054 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1055   EVT OldVT = Op.getValueType();
1056   SDLoc DL(Op);
1057   bool Replace = false;
1058   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1059   if (!NewOp.getNode())
1060     return SDValue();
1061   AddToWorklist(NewOp.getNode());
1062 
1063   if (Replace)
1064     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1065   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1066 }
1067 
1068 /// Promote the specified integer binary operation if the target indicates it is
1069 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1070 /// i32 since i16 instructions are longer.
1071 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1072   if (!LegalOperations)
1073     return SDValue();
1074 
1075   EVT VT = Op.getValueType();
1076   if (VT.isVector() || !VT.isInteger())
1077     return SDValue();
1078 
1079   // If operation type is 'undesirable', e.g. i16 on x86, consider
1080   // promoting it.
1081   unsigned Opc = Op.getOpcode();
1082   if (TLI.isTypeDesirableForOp(Opc, VT))
1083     return SDValue();
1084 
1085   EVT PVT = VT;
1086   // Consult target whether it is a good idea to promote this operation and
1087   // what's the right type to promote it to.
1088   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1089     assert(PVT != VT && "Don't know what type to promote to!");
1090 
1091     bool Replace0 = false;
1092     SDValue N0 = Op.getOperand(0);
1093     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1094     if (!NN0.getNode())
1095       return SDValue();
1096 
1097     bool Replace1 = false;
1098     SDValue N1 = Op.getOperand(1);
1099     SDValue NN1;
1100     if (N0 == N1)
1101       NN1 = NN0;
1102     else {
1103       NN1 = PromoteOperand(N1, PVT, Replace1);
1104       if (!NN1.getNode())
1105         return SDValue();
1106     }
1107 
1108     AddToWorklist(NN0.getNode());
1109     if (NN1.getNode())
1110       AddToWorklist(NN1.getNode());
1111 
1112     if (Replace0)
1113       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1114     if (Replace1)
1115       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1116 
1117     DEBUG(dbgs() << "\nPromoting ";
1118           Op.getNode()->dump(&DAG));
1119     SDLoc DL(Op);
1120     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1121                        DAG.getNode(Opc, DL, PVT, NN0, NN1));
1122   }
1123   return SDValue();
1124 }
1125 
1126 /// Promote the specified integer shift operation if the target indicates it is
1127 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1128 /// i32 since i16 instructions are longer.
1129 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1130   if (!LegalOperations)
1131     return SDValue();
1132 
1133   EVT VT = Op.getValueType();
1134   if (VT.isVector() || !VT.isInteger())
1135     return SDValue();
1136 
1137   // If operation type is 'undesirable', e.g. i16 on x86, consider
1138   // promoting it.
1139   unsigned Opc = Op.getOpcode();
1140   if (TLI.isTypeDesirableForOp(Opc, VT))
1141     return SDValue();
1142 
1143   EVT PVT = VT;
1144   // Consult target whether it is a good idea to promote this operation and
1145   // what's the right type to promote it to.
1146   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1147     assert(PVT != VT && "Don't know what type to promote to!");
1148 
1149     bool Replace = false;
1150     SDValue N0 = Op.getOperand(0);
1151     if (Opc == ISD::SRA)
1152       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1153     else if (Opc == ISD::SRL)
1154       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1155     else
1156       N0 = PromoteOperand(N0, PVT, Replace);
1157     if (!N0.getNode())
1158       return SDValue();
1159 
1160     AddToWorklist(N0.getNode());
1161     if (Replace)
1162       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1163 
1164     DEBUG(dbgs() << "\nPromoting ";
1165           Op.getNode()->dump(&DAG));
1166     SDLoc DL(Op);
1167     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1168                        DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1)));
1169   }
1170   return SDValue();
1171 }
1172 
1173 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1174   if (!LegalOperations)
1175     return SDValue();
1176 
1177   EVT VT = Op.getValueType();
1178   if (VT.isVector() || !VT.isInteger())
1179     return SDValue();
1180 
1181   // If operation type is 'undesirable', e.g. i16 on x86, consider
1182   // promoting it.
1183   unsigned Opc = Op.getOpcode();
1184   if (TLI.isTypeDesirableForOp(Opc, VT))
1185     return SDValue();
1186 
1187   EVT PVT = VT;
1188   // Consult target whether it is a good idea to promote this operation and
1189   // what's the right type to promote it to.
1190   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1191     assert(PVT != VT && "Don't know what type to promote to!");
1192     // fold (aext (aext x)) -> (aext x)
1193     // fold (aext (zext x)) -> (zext x)
1194     // fold (aext (sext x)) -> (sext x)
1195     DEBUG(dbgs() << "\nPromoting ";
1196           Op.getNode()->dump(&DAG));
1197     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1198   }
1199   return SDValue();
1200 }
1201 
1202 bool DAGCombiner::PromoteLoad(SDValue Op) {
1203   if (!LegalOperations)
1204     return false;
1205 
1206   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1207     return false;
1208 
1209   EVT VT = Op.getValueType();
1210   if (VT.isVector() || !VT.isInteger())
1211     return false;
1212 
1213   // If operation type is 'undesirable', e.g. i16 on x86, consider
1214   // promoting it.
1215   unsigned Opc = Op.getOpcode();
1216   if (TLI.isTypeDesirableForOp(Opc, VT))
1217     return false;
1218 
1219   EVT PVT = VT;
1220   // Consult target whether it is a good idea to promote this operation and
1221   // what's the right type to promote it to.
1222   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1223     assert(PVT != VT && "Don't know what type to promote to!");
1224 
1225     SDLoc DL(Op);
1226     SDNode *N = Op.getNode();
1227     LoadSDNode *LD = cast<LoadSDNode>(N);
1228     EVT MemVT = LD->getMemoryVT();
1229     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1230       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1231                                                        : ISD::EXTLOAD)
1232       : LD->getExtensionType();
1233     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1234                                    LD->getChain(), LD->getBasePtr(),
1235                                    MemVT, LD->getMemOperand());
1236     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1237 
1238     DEBUG(dbgs() << "\nPromoting ";
1239           N->dump(&DAG);
1240           dbgs() << "\nTo: ";
1241           Result.getNode()->dump(&DAG);
1242           dbgs() << '\n');
1243     WorklistRemover DeadNodes(*this);
1244     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1245     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1246     deleteAndRecombine(N);
1247     AddToWorklist(Result.getNode());
1248     return true;
1249   }
1250   return false;
1251 }
1252 
1253 /// \brief Recursively delete a node which has no uses and any operands for
1254 /// which it is the only use.
1255 ///
1256 /// Note that this both deletes the nodes and removes them from the worklist.
1257 /// It also adds any nodes who have had a user deleted to the worklist as they
1258 /// may now have only one use and subject to other combines.
1259 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1260   if (!N->use_empty())
1261     return false;
1262 
1263   SmallSetVector<SDNode *, 16> Nodes;
1264   Nodes.insert(N);
1265   do {
1266     N = Nodes.pop_back_val();
1267     if (!N)
1268       continue;
1269 
1270     if (N->use_empty()) {
1271       for (const SDValue &ChildN : N->op_values())
1272         Nodes.insert(ChildN.getNode());
1273 
1274       removeFromWorklist(N);
1275       DAG.DeleteNode(N);
1276     } else {
1277       AddToWorklist(N);
1278     }
1279   } while (!Nodes.empty());
1280   return true;
1281 }
1282 
1283 //===----------------------------------------------------------------------===//
1284 //  Main DAG Combiner implementation
1285 //===----------------------------------------------------------------------===//
1286 
1287 void DAGCombiner::Run(CombineLevel AtLevel) {
1288   // set the instance variables, so that the various visit routines may use it.
1289   Level = AtLevel;
1290   LegalOperations = Level >= AfterLegalizeVectorOps;
1291   LegalTypes = Level >= AfterLegalizeTypes;
1292 
1293   // Add all the dag nodes to the worklist.
1294   for (SDNode &Node : DAG.allnodes())
1295     AddToWorklist(&Node);
1296 
1297   // Create a dummy node (which is not added to allnodes), that adds a reference
1298   // to the root node, preventing it from being deleted, and tracking any
1299   // changes of the root.
1300   HandleSDNode Dummy(DAG.getRoot());
1301 
1302   // While the worklist isn't empty, find a node and try to combine it.
1303   while (!WorklistMap.empty()) {
1304     SDNode *N;
1305     // The Worklist holds the SDNodes in order, but it may contain null entries.
1306     do {
1307       N = Worklist.pop_back_val();
1308     } while (!N);
1309 
1310     bool GoodWorklistEntry = WorklistMap.erase(N);
1311     (void)GoodWorklistEntry;
1312     assert(GoodWorklistEntry &&
1313            "Found a worklist entry without a corresponding map entry!");
1314 
1315     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1316     // N is deleted from the DAG, since they too may now be dead or may have a
1317     // reduced number of uses, allowing other xforms.
1318     if (recursivelyDeleteUnusedNodes(N))
1319       continue;
1320 
1321     WorklistRemover DeadNodes(*this);
1322 
1323     // If this combine is running after legalizing the DAG, re-legalize any
1324     // nodes pulled off the worklist.
1325     if (Level == AfterLegalizeDAG) {
1326       SmallSetVector<SDNode *, 16> UpdatedNodes;
1327       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1328 
1329       for (SDNode *LN : UpdatedNodes) {
1330         AddToWorklist(LN);
1331         AddUsersToWorklist(LN);
1332       }
1333       if (!NIsValid)
1334         continue;
1335     }
1336 
1337     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1338 
1339     // Add any operands of the new node which have not yet been combined to the
1340     // worklist as well. Because the worklist uniques things already, this
1341     // won't repeatedly process the same operand.
1342     CombinedNodes.insert(N);
1343     for (const SDValue &ChildN : N->op_values())
1344       if (!CombinedNodes.count(ChildN.getNode()))
1345         AddToWorklist(ChildN.getNode());
1346 
1347     SDValue RV = combine(N);
1348 
1349     if (!RV.getNode())
1350       continue;
1351 
1352     ++NodesCombined;
1353 
1354     // If we get back the same node we passed in, rather than a new node or
1355     // zero, we know that the node must have defined multiple values and
1356     // CombineTo was used.  Since CombineTo takes care of the worklist
1357     // mechanics for us, we have no work to do in this case.
1358     if (RV.getNode() == N)
1359       continue;
1360 
1361     assert(N->getOpcode() != ISD::DELETED_NODE &&
1362            RV.getOpcode() != ISD::DELETED_NODE &&
1363            "Node was deleted but visit returned new node!");
1364 
1365     DEBUG(dbgs() << " ... into: ";
1366           RV.getNode()->dump(&DAG));
1367 
1368     if (N->getNumValues() == RV.getNode()->getNumValues())
1369       DAG.ReplaceAllUsesWith(N, RV.getNode());
1370     else {
1371       assert(N->getValueType(0) == RV.getValueType() &&
1372              N->getNumValues() == 1 && "Type mismatch");
1373       SDValue OpV = RV;
1374       DAG.ReplaceAllUsesWith(N, &OpV);
1375     }
1376 
1377     // Push the new node and any users onto the worklist
1378     AddToWorklist(RV.getNode());
1379     AddUsersToWorklist(RV.getNode());
1380 
1381     // Finally, if the node is now dead, remove it from the graph.  The node
1382     // may not be dead if the replacement process recursively simplified to
1383     // something else needing this node. This will also take care of adding any
1384     // operands which have lost a user to the worklist.
1385     recursivelyDeleteUnusedNodes(N);
1386   }
1387 
1388   // If the root changed (e.g. it was a dead load, update the root).
1389   DAG.setRoot(Dummy.getValue());
1390   DAG.RemoveDeadNodes();
1391 }
1392 
1393 SDValue DAGCombiner::visit(SDNode *N) {
1394   switch (N->getOpcode()) {
1395   default: break;
1396   case ISD::TokenFactor:        return visitTokenFactor(N);
1397   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1398   case ISD::ADD:                return visitADD(N);
1399   case ISD::SUB:                return visitSUB(N);
1400   case ISD::ADDC:               return visitADDC(N);
1401   case ISD::SUBC:               return visitSUBC(N);
1402   case ISD::ADDE:               return visitADDE(N);
1403   case ISD::SUBE:               return visitSUBE(N);
1404   case ISD::MUL:                return visitMUL(N);
1405   case ISD::SDIV:               return visitSDIV(N);
1406   case ISD::UDIV:               return visitUDIV(N);
1407   case ISD::SREM:
1408   case ISD::UREM:               return visitREM(N);
1409   case ISD::MULHU:              return visitMULHU(N);
1410   case ISD::MULHS:              return visitMULHS(N);
1411   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1412   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1413   case ISD::SMULO:              return visitSMULO(N);
1414   case ISD::UMULO:              return visitUMULO(N);
1415   case ISD::SMIN:
1416   case ISD::SMAX:
1417   case ISD::UMIN:
1418   case ISD::UMAX:               return visitIMINMAX(N);
1419   case ISD::AND:                return visitAND(N);
1420   case ISD::OR:                 return visitOR(N);
1421   case ISD::XOR:                return visitXOR(N);
1422   case ISD::SHL:                return visitSHL(N);
1423   case ISD::SRA:                return visitSRA(N);
1424   case ISD::SRL:                return visitSRL(N);
1425   case ISD::ROTR:
1426   case ISD::ROTL:               return visitRotate(N);
1427   case ISD::BSWAP:              return visitBSWAP(N);
1428   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1429   case ISD::CTLZ:               return visitCTLZ(N);
1430   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1431   case ISD::CTTZ:               return visitCTTZ(N);
1432   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1433   case ISD::CTPOP:              return visitCTPOP(N);
1434   case ISD::SELECT:             return visitSELECT(N);
1435   case ISD::VSELECT:            return visitVSELECT(N);
1436   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1437   case ISD::SETCC:              return visitSETCC(N);
1438   case ISD::SETCCE:             return visitSETCCE(N);
1439   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1440   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1441   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1442   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1443   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1444   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1445   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1446   case ISD::BITCAST:            return visitBITCAST(N);
1447   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1448   case ISD::FADD:               return visitFADD(N);
1449   case ISD::FSUB:               return visitFSUB(N);
1450   case ISD::FMUL:               return visitFMUL(N);
1451   case ISD::FMA:                return visitFMA(N);
1452   case ISD::FDIV:               return visitFDIV(N);
1453   case ISD::FREM:               return visitFREM(N);
1454   case ISD::FSQRT:              return visitFSQRT(N);
1455   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1456   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1457   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1458   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1459   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1460   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1461   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1462   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1463   case ISD::FNEG:               return visitFNEG(N);
1464   case ISD::FABS:               return visitFABS(N);
1465   case ISD::FFLOOR:             return visitFFLOOR(N);
1466   case ISD::FMINNUM:            return visitFMINNUM(N);
1467   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1468   case ISD::FCEIL:              return visitFCEIL(N);
1469   case ISD::FTRUNC:             return visitFTRUNC(N);
1470   case ISD::BRCOND:             return visitBRCOND(N);
1471   case ISD::BR_CC:              return visitBR_CC(N);
1472   case ISD::LOAD:               return visitLOAD(N);
1473   case ISD::STORE:              return visitSTORE(N);
1474   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1475   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1476   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1477   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1478   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1479   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1480   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1481   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1482   case ISD::MGATHER:            return visitMGATHER(N);
1483   case ISD::MLOAD:              return visitMLOAD(N);
1484   case ISD::MSCATTER:           return visitMSCATTER(N);
1485   case ISD::MSTORE:             return visitMSTORE(N);
1486   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1487   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1488   }
1489   return SDValue();
1490 }
1491 
1492 SDValue DAGCombiner::combine(SDNode *N) {
1493   SDValue RV = visit(N);
1494 
1495   // If nothing happened, try a target-specific DAG combine.
1496   if (!RV.getNode()) {
1497     assert(N->getOpcode() != ISD::DELETED_NODE &&
1498            "Node was deleted but visit returned NULL!");
1499 
1500     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1501         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1502 
1503       // Expose the DAG combiner to the target combiner impls.
1504       TargetLowering::DAGCombinerInfo
1505         DagCombineInfo(DAG, Level, false, this);
1506 
1507       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1508     }
1509   }
1510 
1511   // If nothing happened still, try promoting the operation.
1512   if (!RV.getNode()) {
1513     switch (N->getOpcode()) {
1514     default: break;
1515     case ISD::ADD:
1516     case ISD::SUB:
1517     case ISD::MUL:
1518     case ISD::AND:
1519     case ISD::OR:
1520     case ISD::XOR:
1521       RV = PromoteIntBinOp(SDValue(N, 0));
1522       break;
1523     case ISD::SHL:
1524     case ISD::SRA:
1525     case ISD::SRL:
1526       RV = PromoteIntShiftOp(SDValue(N, 0));
1527       break;
1528     case ISD::SIGN_EXTEND:
1529     case ISD::ZERO_EXTEND:
1530     case ISD::ANY_EXTEND:
1531       RV = PromoteExtend(SDValue(N, 0));
1532       break;
1533     case ISD::LOAD:
1534       if (PromoteLoad(SDValue(N, 0)))
1535         RV = SDValue(N, 0);
1536       break;
1537     }
1538   }
1539 
1540   // If N is a commutative binary node, try commuting it to enable more
1541   // sdisel CSE.
1542   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1543       N->getNumValues() == 1) {
1544     SDValue N0 = N->getOperand(0);
1545     SDValue N1 = N->getOperand(1);
1546 
1547     // Constant operands are canonicalized to RHS.
1548     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1549       SDValue Ops[] = {N1, N0};
1550       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1551                                             N->getFlags());
1552       if (CSENode)
1553         return SDValue(CSENode, 0);
1554     }
1555   }
1556 
1557   return RV;
1558 }
1559 
1560 /// Given a node, return its input chain if it has one, otherwise return a null
1561 /// sd operand.
1562 static SDValue getInputChainForNode(SDNode *N) {
1563   if (unsigned NumOps = N->getNumOperands()) {
1564     if (N->getOperand(0).getValueType() == MVT::Other)
1565       return N->getOperand(0);
1566     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1567       return N->getOperand(NumOps-1);
1568     for (unsigned i = 1; i < NumOps-1; ++i)
1569       if (N->getOperand(i).getValueType() == MVT::Other)
1570         return N->getOperand(i);
1571   }
1572   return SDValue();
1573 }
1574 
1575 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1576   // If N has two operands, where one has an input chain equal to the other,
1577   // the 'other' chain is redundant.
1578   if (N->getNumOperands() == 2) {
1579     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1580       return N->getOperand(0);
1581     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1582       return N->getOperand(1);
1583   }
1584 
1585   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1586   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1587   SmallPtrSet<SDNode*, 16> SeenOps;
1588   bool Changed = false;             // If we should replace this token factor.
1589 
1590   // Start out with this token factor.
1591   TFs.push_back(N);
1592 
1593   // Iterate through token factors.  The TFs grows when new token factors are
1594   // encountered.
1595   for (unsigned i = 0; i < TFs.size(); ++i) {
1596     SDNode *TF = TFs[i];
1597 
1598     // Check each of the operands.
1599     for (const SDValue &Op : TF->op_values()) {
1600 
1601       switch (Op.getOpcode()) {
1602       case ISD::EntryToken:
1603         // Entry tokens don't need to be added to the list. They are
1604         // redundant.
1605         Changed = true;
1606         break;
1607 
1608       case ISD::TokenFactor:
1609         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1610           // Queue up for processing.
1611           TFs.push_back(Op.getNode());
1612           // Clean up in case the token factor is removed.
1613           AddToWorklist(Op.getNode());
1614           Changed = true;
1615           break;
1616         }
1617         LLVM_FALLTHROUGH;
1618 
1619       default:
1620         // Only add if it isn't already in the list.
1621         if (SeenOps.insert(Op.getNode()).second)
1622           Ops.push_back(Op);
1623         else
1624           Changed = true;
1625         break;
1626       }
1627     }
1628   }
1629 
1630   SDValue Result;
1631 
1632   // If we've changed things around then replace token factor.
1633   if (Changed) {
1634     if (Ops.empty()) {
1635       // The entry token is the only possible outcome.
1636       Result = DAG.getEntryNode();
1637     } else {
1638       // New and improved token factor.
1639       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1640     }
1641 
1642     // Add users to worklist if AA is enabled, since it may introduce
1643     // a lot of new chained token factors while removing memory deps.
1644     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1645       : DAG.getSubtarget().useAA();
1646     return CombineTo(N, Result, UseAA /*add to worklist*/);
1647   }
1648 
1649   return Result;
1650 }
1651 
1652 /// MERGE_VALUES can always be eliminated.
1653 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1654   WorklistRemover DeadNodes(*this);
1655   // Replacing results may cause a different MERGE_VALUES to suddenly
1656   // be CSE'd with N, and carry its uses with it. Iterate until no
1657   // uses remain, to ensure that the node can be safely deleted.
1658   // First add the users of this node to the work list so that they
1659   // can be tried again once they have new operands.
1660   AddUsersToWorklist(N);
1661   do {
1662     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1663       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1664   } while (!N->use_empty());
1665   deleteAndRecombine(N);
1666   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1667 }
1668 
1669 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1670 /// ConstantSDNode pointer else nullptr.
1671 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1672   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1673   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1674 }
1675 
1676 SDValue DAGCombiner::visitADD(SDNode *N) {
1677   SDValue N0 = N->getOperand(0);
1678   SDValue N1 = N->getOperand(1);
1679   EVT VT = N0.getValueType();
1680   SDLoc DL(N);
1681 
1682   // fold vector ops
1683   if (VT.isVector()) {
1684     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1685       return FoldedVOp;
1686 
1687     // fold (add x, 0) -> x, vector edition
1688     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1689       return N0;
1690     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1691       return N1;
1692   }
1693 
1694   // fold (add x, undef) -> undef
1695   if (N0.isUndef())
1696     return N0;
1697 
1698   if (N1.isUndef())
1699     return N1;
1700 
1701   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1702     // canonicalize constant to RHS
1703     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1704       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1705     // fold (add c1, c2) -> c1+c2
1706     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1707                                       N1.getNode());
1708   }
1709 
1710   // fold (add x, 0) -> x
1711   if (isNullConstant(N1))
1712     return N0;
1713 
1714   // fold ((c1-A)+c2) -> (c1+c2)-A
1715   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1716     if (N0.getOpcode() == ISD::SUB)
1717       if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1718         return DAG.getNode(ISD::SUB, DL, VT,
1719                            DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1720                            N0.getOperand(1));
1721       }
1722   }
1723 
1724   // reassociate add
1725   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1726     return RADD;
1727 
1728   // fold ((0-A) + B) -> B-A
1729   if (N0.getOpcode() == ISD::SUB &&
1730       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1731     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1732 
1733   // fold (A + (0-B)) -> A-B
1734   if (N1.getOpcode() == ISD::SUB &&
1735       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1736     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1737 
1738   // fold (A+(B-A)) -> B
1739   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1740     return N1.getOperand(0);
1741 
1742   // fold ((B-A)+A) -> B
1743   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1744     return N0.getOperand(0);
1745 
1746   // fold (A+(B-(A+C))) to (B-C)
1747   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1748       N0 == N1.getOperand(1).getOperand(0))
1749     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1750                        N1.getOperand(1).getOperand(1));
1751 
1752   // fold (A+(B-(C+A))) to (B-C)
1753   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1754       N0 == N1.getOperand(1).getOperand(1))
1755     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1756                        N1.getOperand(1).getOperand(0));
1757 
1758   // fold (A+((B-A)+or-C)) to (B+or-C)
1759   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1760       N1.getOperand(0).getOpcode() == ISD::SUB &&
1761       N0 == N1.getOperand(0).getOperand(1))
1762     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1763                        N1.getOperand(1));
1764 
1765   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1766   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1767     SDValue N00 = N0.getOperand(0);
1768     SDValue N01 = N0.getOperand(1);
1769     SDValue N10 = N1.getOperand(0);
1770     SDValue N11 = N1.getOperand(1);
1771 
1772     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1773       return DAG.getNode(ISD::SUB, DL, VT,
1774                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1775                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1776   }
1777 
1778   if (SimplifyDemandedBits(SDValue(N, 0)))
1779     return SDValue(N, 0);
1780 
1781   // fold (a+b) -> (a|b) iff a and b share no bits.
1782   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1783       VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1784     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1785 
1786   if (SDValue Combined = visitADDLike(N0, N1, N))
1787     return Combined;
1788 
1789   if (SDValue Combined = visitADDLike(N1, N0, N))
1790     return Combined;
1791 
1792   return SDValue();
1793 }
1794 
1795 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
1796   EVT VT = N0.getValueType();
1797   SDLoc DL(LocReference);
1798 
1799   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1800   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1801       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1802     return DAG.getNode(ISD::SUB, DL, VT, N0,
1803                        DAG.getNode(ISD::SHL, DL, VT,
1804                                    N1.getOperand(0).getOperand(1),
1805                                    N1.getOperand(1)));
1806 
1807   if (N1.getOpcode() == ISD::AND) {
1808     SDValue AndOp0 = N1.getOperand(0);
1809     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1810     unsigned DestBits = VT.getScalarSizeInBits();
1811 
1812     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1813     // and similar xforms where the inner op is either ~0 or 0.
1814     if (NumSignBits == DestBits &&
1815         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1816       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
1817   }
1818 
1819   // add (sext i1), X -> sub X, (zext i1)
1820   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1821       N0.getOperand(0).getValueType() == MVT::i1 &&
1822       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1823     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1824     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1825   }
1826 
1827   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1828   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1829     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1830     if (TN->getVT() == MVT::i1) {
1831       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1832                                  DAG.getConstant(1, DL, VT));
1833       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1834     }
1835   }
1836 
1837   return SDValue();
1838 }
1839 
1840 SDValue DAGCombiner::visitADDC(SDNode *N) {
1841   SDValue N0 = N->getOperand(0);
1842   SDValue N1 = N->getOperand(1);
1843   EVT VT = N0.getValueType();
1844 
1845   // If the flag result is dead, turn this into an ADD.
1846   if (!N->hasAnyUseOfValue(1))
1847     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1848                      DAG.getNode(ISD::CARRY_FALSE,
1849                                  SDLoc(N), MVT::Glue));
1850 
1851   // canonicalize constant to RHS.
1852   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1853   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1854   if (N0C && !N1C)
1855     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1856 
1857   // fold (addc x, 0) -> x + no carry out
1858   if (isNullConstant(N1))
1859     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1860                                         SDLoc(N), MVT::Glue));
1861 
1862   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1863   APInt LHSZero, LHSOne;
1864   APInt RHSZero, RHSOne;
1865   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1866 
1867   if (LHSZero.getBoolValue()) {
1868     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1869 
1870     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1871     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1872     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1873       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1874                        DAG.getNode(ISD::CARRY_FALSE,
1875                                    SDLoc(N), MVT::Glue));
1876   }
1877 
1878   return SDValue();
1879 }
1880 
1881 SDValue DAGCombiner::visitADDE(SDNode *N) {
1882   SDValue N0 = N->getOperand(0);
1883   SDValue N1 = N->getOperand(1);
1884   SDValue CarryIn = N->getOperand(2);
1885 
1886   // canonicalize constant to RHS
1887   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1888   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1889   if (N0C && !N1C)
1890     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1891                        N1, N0, CarryIn);
1892 
1893   // fold (adde x, y, false) -> (addc x, y)
1894   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1895     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1896 
1897   return SDValue();
1898 }
1899 
1900 // Since it may not be valid to emit a fold to zero for vector initializers
1901 // check if we can before folding.
1902 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1903                              SelectionDAG &DAG, bool LegalOperations,
1904                              bool LegalTypes) {
1905   if (!VT.isVector())
1906     return DAG.getConstant(0, DL, VT);
1907   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1908     return DAG.getConstant(0, DL, VT);
1909   return SDValue();
1910 }
1911 
1912 SDValue DAGCombiner::visitSUB(SDNode *N) {
1913   SDValue N0 = N->getOperand(0);
1914   SDValue N1 = N->getOperand(1);
1915   EVT VT = N0.getValueType();
1916   SDLoc DL(N);
1917 
1918   // fold vector ops
1919   if (VT.isVector()) {
1920     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1921       return FoldedVOp;
1922 
1923     // fold (sub x, 0) -> x, vector edition
1924     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1925       return N0;
1926   }
1927 
1928   // fold (sub x, x) -> 0
1929   // FIXME: Refactor this and xor and other similar operations together.
1930   if (N0 == N1)
1931     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
1932   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1933       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1934     // fold (sub c1, c2) -> c1-c2
1935     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
1936                                       N1.getNode());
1937   }
1938 
1939   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1940 
1941   // fold (sub x, c) -> (add x, -c)
1942   if (N1C) {
1943     return DAG.getNode(ISD::ADD, DL, VT, N0,
1944                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1945   }
1946 
1947   if (isNullConstantOrNullSplatConstant(N0)) {
1948     unsigned BitWidth = VT.getScalarSizeInBits();
1949     // Right-shifting everything out but the sign bit followed by negation is
1950     // the same as flipping arithmetic/logical shift type without the negation:
1951     // -(X >>u 31) -> (X >>s 31)
1952     // -(X >>s 31) -> (X >>u 31)
1953     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
1954       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
1955       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
1956         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
1957         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
1958           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
1959       }
1960     }
1961 
1962     // 0 - X --> 0 if the sub is NUW.
1963     if (N->getFlags()->hasNoUnsignedWrap())
1964       return N0;
1965 
1966     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignBit(BitWidth))) {
1967       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
1968       // N1 must be 0 because negating the minimum signed value is undefined.
1969       if (N->getFlags()->hasNoSignedWrap())
1970         return N0;
1971 
1972       // 0 - X --> X if X is 0 or the minimum signed value.
1973       return N1;
1974     }
1975   }
1976 
1977   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1978   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
1979     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
1980 
1981   // fold A-(A-B) -> B
1982   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1983     return N1.getOperand(1);
1984 
1985   // fold (A+B)-A -> B
1986   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1987     return N0.getOperand(1);
1988 
1989   // fold (A+B)-B -> A
1990   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1991     return N0.getOperand(0);
1992 
1993   // fold C2-(A+C1) -> (C2-C1)-A
1994   if (N1.getOpcode() == ISD::ADD) {
1995     SDValue N11 = N1.getOperand(1);
1996     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
1997         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
1998       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
1999       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2000     }
2001   }
2002 
2003   // fold ((A+(B+or-C))-B) -> A+or-C
2004   if (N0.getOpcode() == ISD::ADD &&
2005       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2006        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2007       N0.getOperand(1).getOperand(0) == N1)
2008     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2009                        N0.getOperand(1).getOperand(1));
2010 
2011   // fold ((A+(C+B))-B) -> A+C
2012   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2013       N0.getOperand(1).getOperand(1) == N1)
2014     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2015                        N0.getOperand(1).getOperand(0));
2016 
2017   // fold ((A-(B-C))-C) -> A-B
2018   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2019       N0.getOperand(1).getOperand(1) == N1)
2020     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2021                        N0.getOperand(1).getOperand(0));
2022 
2023   // If either operand of a sub is undef, the result is undef
2024   if (N0.isUndef())
2025     return N0;
2026   if (N1.isUndef())
2027     return N1;
2028 
2029   // If the relocation model supports it, consider symbol offsets.
2030   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2031     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2032       // fold (sub Sym, c) -> Sym-c
2033       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2034         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2035                                     GA->getOffset() -
2036                                         (uint64_t)N1C->getSExtValue());
2037       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2038       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2039         if (GA->getGlobal() == GB->getGlobal())
2040           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2041                                  DL, VT);
2042     }
2043 
2044   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2045   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2046     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2047     if (TN->getVT() == MVT::i1) {
2048       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2049                                  DAG.getConstant(1, DL, VT));
2050       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2051     }
2052   }
2053 
2054   return SDValue();
2055 }
2056 
2057 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2058   SDValue N0 = N->getOperand(0);
2059   SDValue N1 = N->getOperand(1);
2060   EVT VT = N0.getValueType();
2061   SDLoc DL(N);
2062 
2063   // If the flag result is dead, turn this into an SUB.
2064   if (!N->hasAnyUseOfValue(1))
2065     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2066                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2067 
2068   // fold (subc x, x) -> 0 + no borrow
2069   if (N0 == N1)
2070     return CombineTo(N, DAG.getConstant(0, DL, VT),
2071                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2072 
2073   // fold (subc x, 0) -> x + no borrow
2074   if (isNullConstant(N1))
2075     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2076 
2077   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2078   if (isAllOnesConstant(N0))
2079     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2080                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2081 
2082   return SDValue();
2083 }
2084 
2085 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2086   SDValue N0 = N->getOperand(0);
2087   SDValue N1 = N->getOperand(1);
2088   SDValue CarryIn = N->getOperand(2);
2089 
2090   // fold (sube x, y, false) -> (subc x, y)
2091   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2092     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2093 
2094   return SDValue();
2095 }
2096 
2097 SDValue DAGCombiner::visitMUL(SDNode *N) {
2098   SDValue N0 = N->getOperand(0);
2099   SDValue N1 = N->getOperand(1);
2100   EVT VT = N0.getValueType();
2101 
2102   // fold (mul x, undef) -> 0
2103   if (N0.isUndef() || N1.isUndef())
2104     return DAG.getConstant(0, SDLoc(N), VT);
2105 
2106   bool N0IsConst = false;
2107   bool N1IsConst = false;
2108   bool N1IsOpaqueConst = false;
2109   bool N0IsOpaqueConst = false;
2110   APInt ConstValue0, ConstValue1;
2111   // fold vector ops
2112   if (VT.isVector()) {
2113     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2114       return FoldedVOp;
2115 
2116     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2117     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2118   } else {
2119     N0IsConst = isa<ConstantSDNode>(N0);
2120     if (N0IsConst) {
2121       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2122       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2123     }
2124     N1IsConst = isa<ConstantSDNode>(N1);
2125     if (N1IsConst) {
2126       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2127       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2128     }
2129   }
2130 
2131   // fold (mul c1, c2) -> c1*c2
2132   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2133     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2134                                       N0.getNode(), N1.getNode());
2135 
2136   // canonicalize constant to RHS (vector doesn't have to splat)
2137   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2138      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2139     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2140   // fold (mul x, 0) -> 0
2141   if (N1IsConst && ConstValue1 == 0)
2142     return N1;
2143   // We require a splat of the entire scalar bit width for non-contiguous
2144   // bit patterns.
2145   bool IsFullSplat =
2146     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2147   // fold (mul x, 1) -> x
2148   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2149     return N0;
2150   // fold (mul x, -1) -> 0-x
2151   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2152     SDLoc DL(N);
2153     return DAG.getNode(ISD::SUB, DL, VT,
2154                        DAG.getConstant(0, DL, VT), N0);
2155   }
2156   // fold (mul x, (1 << c)) -> x << c
2157   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2158       IsFullSplat) {
2159     SDLoc DL(N);
2160     return DAG.getNode(ISD::SHL, DL, VT, N0,
2161                        DAG.getConstant(ConstValue1.logBase2(), DL,
2162                                        getShiftAmountTy(N0.getValueType())));
2163   }
2164   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2165   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2166       IsFullSplat) {
2167     unsigned Log2Val = (-ConstValue1).logBase2();
2168     SDLoc DL(N);
2169     // FIXME: If the input is something that is easily negated (e.g. a
2170     // single-use add), we should put the negate there.
2171     return DAG.getNode(ISD::SUB, DL, VT,
2172                        DAG.getConstant(0, DL, VT),
2173                        DAG.getNode(ISD::SHL, DL, VT, N0,
2174                             DAG.getConstant(Log2Val, DL,
2175                                       getShiftAmountTy(N0.getValueType()))));
2176   }
2177 
2178   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2179   if (N0.getOpcode() == ISD::SHL &&
2180       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2181       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2182     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2183     if (isConstantOrConstantVector(C3))
2184       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2185   }
2186 
2187   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2188   // use.
2189   {
2190     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2191 
2192     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2193     if (N0.getOpcode() == ISD::SHL &&
2194         isConstantOrConstantVector(N0.getOperand(1)) &&
2195         N0.getNode()->hasOneUse()) {
2196       Sh = N0; Y = N1;
2197     } else if (N1.getOpcode() == ISD::SHL &&
2198                isConstantOrConstantVector(N1.getOperand(1)) &&
2199                N1.getNode()->hasOneUse()) {
2200       Sh = N1; Y = N0;
2201     }
2202 
2203     if (Sh.getNode()) {
2204       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2205       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2206     }
2207   }
2208 
2209   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2210   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2211       N0.getOpcode() == ISD::ADD &&
2212       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2213       isMulAddWithConstProfitable(N, N0, N1))
2214       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2215                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2216                                      N0.getOperand(0), N1),
2217                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2218                                      N0.getOperand(1), N1));
2219 
2220   // reassociate mul
2221   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2222     return RMUL;
2223 
2224   return SDValue();
2225 }
2226 
2227 /// Return true if divmod libcall is available.
2228 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2229                                      const TargetLowering &TLI) {
2230   RTLIB::Libcall LC;
2231   EVT NodeType = Node->getValueType(0);
2232   if (!NodeType.isSimple())
2233     return false;
2234   switch (NodeType.getSimpleVT().SimpleTy) {
2235   default: return false; // No libcall for vector types.
2236   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2237   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2238   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2239   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2240   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2241   }
2242 
2243   return TLI.getLibcallName(LC) != nullptr;
2244 }
2245 
2246 /// Issue divrem if both quotient and remainder are needed.
2247 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2248   if (Node->use_empty())
2249     return SDValue(); // This is a dead node, leave it alone.
2250 
2251   unsigned Opcode = Node->getOpcode();
2252   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2253   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2254 
2255   // DivMod lib calls can still work on non-legal types if using lib-calls.
2256   EVT VT = Node->getValueType(0);
2257   if (VT.isVector() || !VT.isInteger())
2258     return SDValue();
2259 
2260   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2261     return SDValue();
2262 
2263   // If DIVREM is going to get expanded into a libcall,
2264   // but there is no libcall available, then don't combine.
2265   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2266       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2267     return SDValue();
2268 
2269   // If div is legal, it's better to do the normal expansion
2270   unsigned OtherOpcode = 0;
2271   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2272     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2273     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2274       return SDValue();
2275   } else {
2276     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2277     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2278       return SDValue();
2279   }
2280 
2281   SDValue Op0 = Node->getOperand(0);
2282   SDValue Op1 = Node->getOperand(1);
2283   SDValue combined;
2284   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2285          UE = Op0.getNode()->use_end(); UI != UE;) {
2286     SDNode *User = *UI++;
2287     if (User == Node || User->use_empty())
2288       continue;
2289     // Convert the other matching node(s), too;
2290     // otherwise, the DIVREM may get target-legalized into something
2291     // target-specific that we won't be able to recognize.
2292     unsigned UserOpc = User->getOpcode();
2293     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2294         User->getOperand(0) == Op0 &&
2295         User->getOperand(1) == Op1) {
2296       if (!combined) {
2297         if (UserOpc == OtherOpcode) {
2298           SDVTList VTs = DAG.getVTList(VT, VT);
2299           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2300         } else if (UserOpc == DivRemOpc) {
2301           combined = SDValue(User, 0);
2302         } else {
2303           assert(UserOpc == Opcode);
2304           continue;
2305         }
2306       }
2307       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2308         CombineTo(User, combined);
2309       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2310         CombineTo(User, combined.getValue(1));
2311     }
2312   }
2313   return combined;
2314 }
2315 
2316 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2317   SDValue N0 = N->getOperand(0);
2318   SDValue N1 = N->getOperand(1);
2319   EVT VT = N->getValueType(0);
2320 
2321   // fold vector ops
2322   if (VT.isVector())
2323     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2324       return FoldedVOp;
2325 
2326   SDLoc DL(N);
2327 
2328   // fold (sdiv c1, c2) -> c1/c2
2329   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2330   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2331   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2332     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2333   // fold (sdiv X, 1) -> X
2334   if (N1C && N1C->isOne())
2335     return N0;
2336   // fold (sdiv X, -1) -> 0-X
2337   if (N1C && N1C->isAllOnesValue())
2338     return DAG.getNode(ISD::SUB, DL, VT,
2339                        DAG.getConstant(0, DL, VT), N0);
2340 
2341   // If we know the sign bits of both operands are zero, strength reduce to a
2342   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2343   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2344     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2345 
2346   // fold (sdiv X, pow2) -> simple ops after legalize
2347   // FIXME: We check for the exact bit here because the generic lowering gives
2348   // better results in that case. The target-specific lowering should learn how
2349   // to handle exact sdivs efficiently.
2350   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2351       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2352       (N1C->getAPIntValue().isPowerOf2() ||
2353        (-N1C->getAPIntValue()).isPowerOf2())) {
2354     // Target-specific implementation of sdiv x, pow2.
2355     if (SDValue Res = BuildSDIVPow2(N))
2356       return Res;
2357 
2358     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2359 
2360     // Splat the sign bit into the register
2361     SDValue SGN =
2362         DAG.getNode(ISD::SRA, DL, VT, N0,
2363                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2364                                     getShiftAmountTy(N0.getValueType())));
2365     AddToWorklist(SGN.getNode());
2366 
2367     // Add (N0 < 0) ? abs2 - 1 : 0;
2368     SDValue SRL =
2369         DAG.getNode(ISD::SRL, DL, VT, SGN,
2370                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2371                                     getShiftAmountTy(SGN.getValueType())));
2372     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2373     AddToWorklist(SRL.getNode());
2374     AddToWorklist(ADD.getNode());    // Divide by pow2
2375     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2376                   DAG.getConstant(lg2, DL,
2377                                   getShiftAmountTy(ADD.getValueType())));
2378 
2379     // If we're dividing by a positive value, we're done.  Otherwise, we must
2380     // negate the result.
2381     if (N1C->getAPIntValue().isNonNegative())
2382       return SRA;
2383 
2384     AddToWorklist(SRA.getNode());
2385     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2386   }
2387 
2388   // If integer divide is expensive and we satisfy the requirements, emit an
2389   // alternate sequence.  Targets may check function attributes for size/speed
2390   // trade-offs.
2391   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2392   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2393     if (SDValue Op = BuildSDIV(N))
2394       return Op;
2395 
2396   // sdiv, srem -> sdivrem
2397   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2398   // true.  Otherwise, we break the simplification logic in visitREM().
2399   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2400     if (SDValue DivRem = useDivRem(N))
2401         return DivRem;
2402 
2403   // undef / X -> 0
2404   if (N0.isUndef())
2405     return DAG.getConstant(0, DL, VT);
2406   // X / undef -> undef
2407   if (N1.isUndef())
2408     return N1;
2409 
2410   return SDValue();
2411 }
2412 
2413 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2414   SDValue N0 = N->getOperand(0);
2415   SDValue N1 = N->getOperand(1);
2416   EVT VT = N->getValueType(0);
2417 
2418   // fold vector ops
2419   if (VT.isVector())
2420     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2421       return FoldedVOp;
2422 
2423   SDLoc DL(N);
2424 
2425   // fold (udiv c1, c2) -> c1/c2
2426   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2427   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2428   if (N0C && N1C)
2429     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2430                                                     N0C, N1C))
2431       return Folded;
2432 
2433   // fold (udiv x, (1 << c)) -> x >>u c
2434   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2435       DAG.isKnownToBeAPowerOfTwo(N1)) {
2436     SDValue LogBase2 = BuildLogBase2(N1, DL);
2437     AddToWorklist(LogBase2.getNode());
2438 
2439     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2440     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2441     AddToWorklist(Trunc.getNode());
2442     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2443   }
2444 
2445   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2446   if (N1.getOpcode() == ISD::SHL) {
2447     SDValue N10 = N1.getOperand(0);
2448     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2449         DAG.isKnownToBeAPowerOfTwo(N10)) {
2450       SDValue LogBase2 = BuildLogBase2(N10, DL);
2451       AddToWorklist(LogBase2.getNode());
2452 
2453       EVT ADDVT = N1.getOperand(1).getValueType();
2454       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2455       AddToWorklist(Trunc.getNode());
2456       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2457       AddToWorklist(Add.getNode());
2458       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2459     }
2460   }
2461 
2462   // fold (udiv x, c) -> alternate
2463   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2464   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2465     if (SDValue Op = BuildUDIV(N))
2466       return Op;
2467 
2468   // sdiv, srem -> sdivrem
2469   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2470   // true.  Otherwise, we break the simplification logic in visitREM().
2471   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2472     if (SDValue DivRem = useDivRem(N))
2473         return DivRem;
2474 
2475   // undef / X -> 0
2476   if (N0.isUndef())
2477     return DAG.getConstant(0, DL, VT);
2478   // X / undef -> undef
2479   if (N1.isUndef())
2480     return N1;
2481 
2482   return SDValue();
2483 }
2484 
2485 // handles ISD::SREM and ISD::UREM
2486 SDValue DAGCombiner::visitREM(SDNode *N) {
2487   unsigned Opcode = N->getOpcode();
2488   SDValue N0 = N->getOperand(0);
2489   SDValue N1 = N->getOperand(1);
2490   EVT VT = N->getValueType(0);
2491   bool isSigned = (Opcode == ISD::SREM);
2492   SDLoc DL(N);
2493 
2494   // fold (rem c1, c2) -> c1%c2
2495   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2496   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2497   if (N0C && N1C)
2498     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2499       return Folded;
2500 
2501   if (isSigned) {
2502     // If we know the sign bits of both operands are zero, strength reduce to a
2503     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2504     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2505       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2506   } else {
2507     // fold (urem x, pow2) -> (and x, pow2-1)
2508     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2509       APInt NegOne = APInt::getAllOnesValue(VT.getScalarSizeInBits());
2510       SDValue Add =
2511           DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2512       AddToWorklist(Add.getNode());
2513       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2514     }
2515     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2516     if (N1.getOpcode() == ISD::SHL &&
2517         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2518       APInt NegOne = APInt::getAllOnesValue(VT.getScalarSizeInBits());
2519       SDValue Add =
2520           DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2521       AddToWorklist(Add.getNode());
2522       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2523     }
2524   }
2525 
2526   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2527 
2528   // If X/C can be simplified by the division-by-constant logic, lower
2529   // X%C to the equivalent of X-X/C*C.
2530   // To avoid mangling nodes, this simplification requires that the combine()
2531   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2532   // against this by skipping the simplification if isIntDivCheap().  When
2533   // div is not cheap, combine will not return a DIVREM.  Regardless,
2534   // checking cheapness here makes sense since the simplification results in
2535   // fatter code.
2536   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2537     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2538     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2539     AddToWorklist(Div.getNode());
2540     SDValue OptimizedDiv = combine(Div.getNode());
2541     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2542       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2543              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2544       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2545       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2546       AddToWorklist(Mul.getNode());
2547       return Sub;
2548     }
2549   }
2550 
2551   // sdiv, srem -> sdivrem
2552   if (SDValue DivRem = useDivRem(N))
2553     return DivRem.getValue(1);
2554 
2555   // undef % X -> 0
2556   if (N0.isUndef())
2557     return DAG.getConstant(0, DL, VT);
2558   // X % undef -> undef
2559   if (N1.isUndef())
2560     return N1;
2561 
2562   return SDValue();
2563 }
2564 
2565 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2566   SDValue N0 = N->getOperand(0);
2567   SDValue N1 = N->getOperand(1);
2568   EVT VT = N->getValueType(0);
2569   SDLoc DL(N);
2570 
2571   // fold (mulhs x, 0) -> 0
2572   if (isNullConstant(N1))
2573     return N1;
2574   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2575   if (isOneConstant(N1)) {
2576     SDLoc DL(N);
2577     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2578                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2579                                        getShiftAmountTy(N0.getValueType())));
2580   }
2581   // fold (mulhs x, undef) -> 0
2582   if (N0.isUndef() || N1.isUndef())
2583     return DAG.getConstant(0, SDLoc(N), VT);
2584 
2585   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2586   // plus a shift.
2587   if (VT.isSimple() && !VT.isVector()) {
2588     MVT Simple = VT.getSimpleVT();
2589     unsigned SimpleSize = Simple.getSizeInBits();
2590     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2591     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2592       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2593       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2594       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2595       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2596             DAG.getConstant(SimpleSize, DL,
2597                             getShiftAmountTy(N1.getValueType())));
2598       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2599     }
2600   }
2601 
2602   return SDValue();
2603 }
2604 
2605 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2606   SDValue N0 = N->getOperand(0);
2607   SDValue N1 = N->getOperand(1);
2608   EVT VT = N->getValueType(0);
2609   SDLoc DL(N);
2610 
2611   // fold (mulhu x, 0) -> 0
2612   if (isNullConstant(N1))
2613     return N1;
2614   // fold (mulhu x, 1) -> 0
2615   if (isOneConstant(N1))
2616     return DAG.getConstant(0, DL, N0.getValueType());
2617   // fold (mulhu x, undef) -> 0
2618   if (N0.isUndef() || N1.isUndef())
2619     return DAG.getConstant(0, DL, VT);
2620 
2621   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2622   // plus a shift.
2623   if (VT.isSimple() && !VT.isVector()) {
2624     MVT Simple = VT.getSimpleVT();
2625     unsigned SimpleSize = Simple.getSizeInBits();
2626     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2627     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2628       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2629       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2630       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2631       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2632             DAG.getConstant(SimpleSize, DL,
2633                             getShiftAmountTy(N1.getValueType())));
2634       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2635     }
2636   }
2637 
2638   return SDValue();
2639 }
2640 
2641 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2642 /// give the opcodes for the two computations that are being performed. Return
2643 /// true if a simplification was made.
2644 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2645                                                 unsigned HiOp) {
2646   // If the high half is not needed, just compute the low half.
2647   bool HiExists = N->hasAnyUseOfValue(1);
2648   if (!HiExists &&
2649       (!LegalOperations ||
2650        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2651     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2652     return CombineTo(N, Res, Res);
2653   }
2654 
2655   // If the low half is not needed, just compute the high half.
2656   bool LoExists = N->hasAnyUseOfValue(0);
2657   if (!LoExists &&
2658       (!LegalOperations ||
2659        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2660     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2661     return CombineTo(N, Res, Res);
2662   }
2663 
2664   // If both halves are used, return as it is.
2665   if (LoExists && HiExists)
2666     return SDValue();
2667 
2668   // If the two computed results can be simplified separately, separate them.
2669   if (LoExists) {
2670     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2671     AddToWorklist(Lo.getNode());
2672     SDValue LoOpt = combine(Lo.getNode());
2673     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2674         (!LegalOperations ||
2675          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2676       return CombineTo(N, LoOpt, LoOpt);
2677   }
2678 
2679   if (HiExists) {
2680     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2681     AddToWorklist(Hi.getNode());
2682     SDValue HiOpt = combine(Hi.getNode());
2683     if (HiOpt.getNode() && HiOpt != Hi &&
2684         (!LegalOperations ||
2685          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2686       return CombineTo(N, HiOpt, HiOpt);
2687   }
2688 
2689   return SDValue();
2690 }
2691 
2692 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2693   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2694     return Res;
2695 
2696   EVT VT = N->getValueType(0);
2697   SDLoc DL(N);
2698 
2699   // If the type is twice as wide is legal, transform the mulhu to a wider
2700   // multiply plus a shift.
2701   if (VT.isSimple() && !VT.isVector()) {
2702     MVT Simple = VT.getSimpleVT();
2703     unsigned SimpleSize = Simple.getSizeInBits();
2704     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2705     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2706       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2707       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2708       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2709       // Compute the high part as N1.
2710       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2711             DAG.getConstant(SimpleSize, DL,
2712                             getShiftAmountTy(Lo.getValueType())));
2713       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2714       // Compute the low part as N0.
2715       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2716       return CombineTo(N, Lo, Hi);
2717     }
2718   }
2719 
2720   return SDValue();
2721 }
2722 
2723 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2724   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2725     return Res;
2726 
2727   EVT VT = N->getValueType(0);
2728   SDLoc DL(N);
2729 
2730   // If the type is twice as wide is legal, transform the mulhu to a wider
2731   // multiply plus a shift.
2732   if (VT.isSimple() && !VT.isVector()) {
2733     MVT Simple = VT.getSimpleVT();
2734     unsigned SimpleSize = Simple.getSizeInBits();
2735     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2736     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2737       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2738       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2739       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2740       // Compute the high part as N1.
2741       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2742             DAG.getConstant(SimpleSize, DL,
2743                             getShiftAmountTy(Lo.getValueType())));
2744       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2745       // Compute the low part as N0.
2746       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2747       return CombineTo(N, Lo, Hi);
2748     }
2749   }
2750 
2751   return SDValue();
2752 }
2753 
2754 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2755   // (smulo x, 2) -> (saddo x, x)
2756   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2757     if (C2->getAPIntValue() == 2)
2758       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2759                          N->getOperand(0), N->getOperand(0));
2760 
2761   return SDValue();
2762 }
2763 
2764 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2765   // (umulo x, 2) -> (uaddo x, x)
2766   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2767     if (C2->getAPIntValue() == 2)
2768       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2769                          N->getOperand(0), N->getOperand(0));
2770 
2771   return SDValue();
2772 }
2773 
2774 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2775   SDValue N0 = N->getOperand(0);
2776   SDValue N1 = N->getOperand(1);
2777   EVT VT = N0.getValueType();
2778 
2779   // fold vector ops
2780   if (VT.isVector())
2781     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2782       return FoldedVOp;
2783 
2784   // fold (add c1, c2) -> c1+c2
2785   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2786   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2787   if (N0C && N1C)
2788     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2789 
2790   // canonicalize constant to RHS
2791   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2792      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2793     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2794 
2795   return SDValue();
2796 }
2797 
2798 /// If this is a binary operator with two operands of the same opcode, try to
2799 /// simplify it.
2800 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2801   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2802   EVT VT = N0.getValueType();
2803   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2804 
2805   // Bail early if none of these transforms apply.
2806   if (N0.getNumOperands() == 0) return SDValue();
2807 
2808   // For each of OP in AND/OR/XOR:
2809   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2810   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2811   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2812   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2813   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2814   //
2815   // do not sink logical op inside of a vector extend, since it may combine
2816   // into a vsetcc.
2817   EVT Op0VT = N0.getOperand(0).getValueType();
2818   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2819        N0.getOpcode() == ISD::SIGN_EXTEND ||
2820        N0.getOpcode() == ISD::BSWAP ||
2821        // Avoid infinite looping with PromoteIntBinOp.
2822        (N0.getOpcode() == ISD::ANY_EXTEND &&
2823         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2824        (N0.getOpcode() == ISD::TRUNCATE &&
2825         (!TLI.isZExtFree(VT, Op0VT) ||
2826          !TLI.isTruncateFree(Op0VT, VT)) &&
2827         TLI.isTypeLegal(Op0VT))) &&
2828       !VT.isVector() &&
2829       Op0VT == N1.getOperand(0).getValueType() &&
2830       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2831     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2832                                  N0.getOperand(0).getValueType(),
2833                                  N0.getOperand(0), N1.getOperand(0));
2834     AddToWorklist(ORNode.getNode());
2835     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2836   }
2837 
2838   // For each of OP in SHL/SRL/SRA/AND...
2839   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2840   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2841   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2842   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2843        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2844       N0.getOperand(1) == N1.getOperand(1)) {
2845     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2846                                  N0.getOperand(0).getValueType(),
2847                                  N0.getOperand(0), N1.getOperand(0));
2848     AddToWorklist(ORNode.getNode());
2849     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2850                        ORNode, N0.getOperand(1));
2851   }
2852 
2853   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2854   // Only perform this optimization up until type legalization, before
2855   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2856   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2857   // we don't want to undo this promotion.
2858   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2859   // on scalars.
2860   if ((N0.getOpcode() == ISD::BITCAST ||
2861        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2862        Level <= AfterLegalizeTypes) {
2863     SDValue In0 = N0.getOperand(0);
2864     SDValue In1 = N1.getOperand(0);
2865     EVT In0Ty = In0.getValueType();
2866     EVT In1Ty = In1.getValueType();
2867     SDLoc DL(N);
2868     // If both incoming values are integers, and the original types are the
2869     // same.
2870     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2871       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2872       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2873       AddToWorklist(Op.getNode());
2874       return BC;
2875     }
2876   }
2877 
2878   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2879   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2880   // If both shuffles use the same mask, and both shuffle within a single
2881   // vector, then it is worthwhile to move the swizzle after the operation.
2882   // The type-legalizer generates this pattern when loading illegal
2883   // vector types from memory. In many cases this allows additional shuffle
2884   // optimizations.
2885   // There are other cases where moving the shuffle after the xor/and/or
2886   // is profitable even if shuffles don't perform a swizzle.
2887   // If both shuffles use the same mask, and both shuffles have the same first
2888   // or second operand, then it might still be profitable to move the shuffle
2889   // after the xor/and/or operation.
2890   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2891     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2892     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2893 
2894     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2895            "Inputs to shuffles are not the same type");
2896 
2897     // Check that both shuffles use the same mask. The masks are known to be of
2898     // the same length because the result vector type is the same.
2899     // Check also that shuffles have only one use to avoid introducing extra
2900     // instructions.
2901     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2902         SVN0->getMask().equals(SVN1->getMask())) {
2903       SDValue ShOp = N0->getOperand(1);
2904 
2905       // Don't try to fold this node if it requires introducing a
2906       // build vector of all zeros that might be illegal at this stage.
2907       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2908         if (!LegalTypes)
2909           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2910         else
2911           ShOp = SDValue();
2912       }
2913 
2914       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2915       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2916       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2917       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2918         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2919                                       N0->getOperand(0), N1->getOperand(0));
2920         AddToWorklist(NewNode.getNode());
2921         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2922                                     SVN0->getMask());
2923       }
2924 
2925       // Don't try to fold this node if it requires introducing a
2926       // build vector of all zeros that might be illegal at this stage.
2927       ShOp = N0->getOperand(0);
2928       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2929         if (!LegalTypes)
2930           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2931         else
2932           ShOp = SDValue();
2933       }
2934 
2935       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2936       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2937       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2938       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2939         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2940                                       N0->getOperand(1), N1->getOperand(1));
2941         AddToWorklist(NewNode.getNode());
2942         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2943                                     SVN0->getMask());
2944       }
2945     }
2946   }
2947 
2948   return SDValue();
2949 }
2950 
2951 /// This contains all DAGCombine rules which reduce two values combined by
2952 /// an And operation to a single value. This makes them reusable in the context
2953 /// of visitSELECT(). Rules involving constants are not included as
2954 /// visitSELECT() already handles those cases.
2955 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2956                                   SDNode *LocReference) {
2957   EVT VT = N1.getValueType();
2958 
2959   // fold (and x, undef) -> 0
2960   if (N0.isUndef() || N1.isUndef())
2961     return DAG.getConstant(0, SDLoc(LocReference), VT);
2962   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2963   SDValue LL, LR, RL, RR, CC0, CC1;
2964   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2965     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2966     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2967 
2968     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2969         LL.getValueType().isInteger()) {
2970       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2971       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2972         EVT CCVT = getSetCCResultType(LR.getValueType());
2973         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2974           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2975                                        LR.getValueType(), LL, RL);
2976           AddToWorklist(ORNode.getNode());
2977           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2978         }
2979       }
2980       if (isAllOnesConstant(LR)) {
2981         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2982         if (Op1 == ISD::SETEQ) {
2983           EVT CCVT = getSetCCResultType(LR.getValueType());
2984           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2985             SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2986                                           LR.getValueType(), LL, RL);
2987             AddToWorklist(ANDNode.getNode());
2988             return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2989           }
2990         }
2991         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2992         if (Op1 == ISD::SETGT) {
2993           EVT CCVT = getSetCCResultType(LR.getValueType());
2994           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2995             SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2996                                          LR.getValueType(), LL, RL);
2997             AddToWorklist(ORNode.getNode());
2998             return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2999           }
3000         }
3001       }
3002     }
3003     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
3004     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
3005         Op0 == Op1 && LL.getValueType().isInteger() &&
3006       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3007                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3008       EVT CCVT = getSetCCResultType(LL.getValueType());
3009       if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3010         SDLoc DL(N0);
3011         SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
3012                                       LL, DAG.getConstant(1, DL,
3013                                                           LL.getValueType()));
3014         AddToWorklist(ADDNode.getNode());
3015         return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
3016                             DAG.getConstant(2, DL, LL.getValueType()),
3017                             ISD::SETUGE);
3018       }
3019     }
3020     // canonicalize equivalent to ll == rl
3021     if (LL == RR && LR == RL) {
3022       Op1 = ISD::getSetCCSwappedOperands(Op1);
3023       std::swap(RL, RR);
3024     }
3025     if (LL == RL && LR == RR) {
3026       bool isInteger = LL.getValueType().isInteger();
3027       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
3028       if (Result != ISD::SETCC_INVALID &&
3029           (!LegalOperations ||
3030            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3031             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3032         EVT CCVT = getSetCCResultType(LL.getValueType());
3033         if (N0.getValueType() == CCVT ||
3034             (!LegalOperations && N0.getValueType() == MVT::i1))
3035           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3036                               LL, LR, Result);
3037       }
3038     }
3039   }
3040 
3041   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3042       VT.getSizeInBits() <= 64) {
3043     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3044       APInt ADDC = ADDI->getAPIntValue();
3045       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3046         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3047         // immediate for an add, but it is legal if its top c2 bits are set,
3048         // transform the ADD so the immediate doesn't need to be materialized
3049         // in a register.
3050         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3051           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3052                                              SRLI->getZExtValue());
3053           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3054             ADDC |= Mask;
3055             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3056               SDLoc DL(N0);
3057               SDValue NewAdd =
3058                 DAG.getNode(ISD::ADD, DL, VT,
3059                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3060               CombineTo(N0.getNode(), NewAdd);
3061               // Return N so it doesn't get rechecked!
3062               return SDValue(LocReference, 0);
3063             }
3064           }
3065         }
3066       }
3067     }
3068   }
3069 
3070   // Reduce bit extract of low half of an integer to the narrower type.
3071   // (and (srl i64:x, K), KMask) ->
3072   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3073   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3074     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3075       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3076         unsigned Size = VT.getSizeInBits();
3077         const APInt &AndMask = CAnd->getAPIntValue();
3078         unsigned ShiftBits = CShift->getZExtValue();
3079 
3080         // Bail out, this node will probably disappear anyway.
3081         if (ShiftBits == 0)
3082           return SDValue();
3083 
3084         unsigned MaskBits = AndMask.countTrailingOnes();
3085         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3086 
3087         if (APIntOps::isMask(AndMask) &&
3088             // Required bits must not span the two halves of the integer and
3089             // must fit in the half size type.
3090             (ShiftBits + MaskBits <= Size / 2) &&
3091             TLI.isNarrowingProfitable(VT, HalfVT) &&
3092             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3093             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3094             TLI.isTruncateFree(VT, HalfVT) &&
3095             TLI.isZExtFree(HalfVT, VT)) {
3096           // The isNarrowingProfitable is to avoid regressions on PPC and
3097           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3098           // on downstream users of this. Those patterns could probably be
3099           // extended to handle extensions mixed in.
3100 
3101           SDValue SL(N0);
3102           assert(MaskBits <= Size);
3103 
3104           // Extracting the highest bit of the low half.
3105           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3106           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3107                                       N0.getOperand(0));
3108 
3109           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3110           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3111           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3112           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3113           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3114         }
3115       }
3116     }
3117   }
3118 
3119   return SDValue();
3120 }
3121 
3122 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3123                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3124                                    bool &NarrowLoad) {
3125   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3126 
3127   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3128     return false;
3129 
3130   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3131   LoadedVT = LoadN->getMemoryVT();
3132 
3133   if (ExtVT == LoadedVT &&
3134       (!LegalOperations ||
3135        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3136     // ZEXTLOAD will match without needing to change the size of the value being
3137     // loaded.
3138     NarrowLoad = false;
3139     return true;
3140   }
3141 
3142   // Do not change the width of a volatile load.
3143   if (LoadN->isVolatile())
3144     return false;
3145 
3146   // Do not generate loads of non-round integer types since these can
3147   // be expensive (and would be wrong if the type is not byte sized).
3148   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3149     return false;
3150 
3151   if (LegalOperations &&
3152       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3153     return false;
3154 
3155   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3156     return false;
3157 
3158   NarrowLoad = true;
3159   return true;
3160 }
3161 
3162 SDValue DAGCombiner::visitAND(SDNode *N) {
3163   SDValue N0 = N->getOperand(0);
3164   SDValue N1 = N->getOperand(1);
3165   EVT VT = N1.getValueType();
3166 
3167   // x & x --> x
3168   if (N0 == N1)
3169     return N0;
3170 
3171   // fold vector ops
3172   if (VT.isVector()) {
3173     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3174       return FoldedVOp;
3175 
3176     // fold (and x, 0) -> 0, vector edition
3177     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3178       // do not return N0, because undef node may exist in N0
3179       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3180                              SDLoc(N), N0.getValueType());
3181     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3182       // do not return N1, because undef node may exist in N1
3183       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3184                              SDLoc(N), N1.getValueType());
3185 
3186     // fold (and x, -1) -> x, vector edition
3187     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3188       return N1;
3189     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3190       return N0;
3191   }
3192 
3193   // fold (and c1, c2) -> c1&c2
3194   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3195   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3196   if (N0C && N1C && !N1C->isOpaque())
3197     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3198   // canonicalize constant to RHS
3199   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3200      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3201     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3202   // fold (and x, -1) -> x
3203   if (isAllOnesConstant(N1))
3204     return N0;
3205   // if (and x, c) is known to be zero, return 0
3206   unsigned BitWidth = VT.getScalarSizeInBits();
3207   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3208                                    APInt::getAllOnesValue(BitWidth)))
3209     return DAG.getConstant(0, SDLoc(N), VT);
3210   // reassociate and
3211   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3212     return RAND;
3213   // fold (and (or x, C), D) -> D if (C & D) == D
3214   if (N1C && N0.getOpcode() == ISD::OR)
3215     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3216       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3217         return N1;
3218   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3219   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3220     SDValue N0Op0 = N0.getOperand(0);
3221     APInt Mask = ~N1C->getAPIntValue();
3222     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3223     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3224       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3225                                  N0.getValueType(), N0Op0);
3226 
3227       // Replace uses of the AND with uses of the Zero extend node.
3228       CombineTo(N, Zext);
3229 
3230       // We actually want to replace all uses of the any_extend with the
3231       // zero_extend, to avoid duplicating things.  This will later cause this
3232       // AND to be folded.
3233       CombineTo(N0.getNode(), Zext);
3234       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3235     }
3236   }
3237   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3238   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3239   // already be zero by virtue of the width of the base type of the load.
3240   //
3241   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3242   // more cases.
3243   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3244        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3245        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3246        N0.getOperand(0).getResNo() == 0) ||
3247       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3248     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3249                                          N0 : N0.getOperand(0) );
3250 
3251     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3252     // This can be a pure constant or a vector splat, in which case we treat the
3253     // vector as a scalar and use the splat value.
3254     APInt Constant = APInt::getNullValue(1);
3255     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3256       Constant = C->getAPIntValue();
3257     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3258       APInt SplatValue, SplatUndef;
3259       unsigned SplatBitSize;
3260       bool HasAnyUndefs;
3261       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3262                                              SplatBitSize, HasAnyUndefs);
3263       if (IsSplat) {
3264         // Undef bits can contribute to a possible optimisation if set, so
3265         // set them.
3266         SplatValue |= SplatUndef;
3267 
3268         // The splat value may be something like "0x00FFFFFF", which means 0 for
3269         // the first vector value and FF for the rest, repeating. We need a mask
3270         // that will apply equally to all members of the vector, so AND all the
3271         // lanes of the constant together.
3272         EVT VT = Vector->getValueType(0);
3273         unsigned BitWidth = VT.getScalarSizeInBits();
3274 
3275         // If the splat value has been compressed to a bitlength lower
3276         // than the size of the vector lane, we need to re-expand it to
3277         // the lane size.
3278         if (BitWidth > SplatBitSize)
3279           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3280                SplatBitSize < BitWidth;
3281                SplatBitSize = SplatBitSize * 2)
3282             SplatValue |= SplatValue.shl(SplatBitSize);
3283 
3284         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3285         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3286         if (SplatBitSize % BitWidth == 0) {
3287           Constant = APInt::getAllOnesValue(BitWidth);
3288           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3289             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3290         }
3291       }
3292     }
3293 
3294     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3295     // actually legal and isn't going to get expanded, else this is a false
3296     // optimisation.
3297     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3298                                                     Load->getValueType(0),
3299                                                     Load->getMemoryVT());
3300 
3301     // Resize the constant to the same size as the original memory access before
3302     // extension. If it is still the AllOnesValue then this AND is completely
3303     // unneeded.
3304     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3305 
3306     bool B;
3307     switch (Load->getExtensionType()) {
3308     default: B = false; break;
3309     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3310     case ISD::ZEXTLOAD:
3311     case ISD::NON_EXTLOAD: B = true; break;
3312     }
3313 
3314     if (B && Constant.isAllOnesValue()) {
3315       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3316       // preserve semantics once we get rid of the AND.
3317       SDValue NewLoad(Load, 0);
3318       if (Load->getExtensionType() == ISD::EXTLOAD) {
3319         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3320                               Load->getValueType(0), SDLoc(Load),
3321                               Load->getChain(), Load->getBasePtr(),
3322                               Load->getOffset(), Load->getMemoryVT(),
3323                               Load->getMemOperand());
3324         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3325         if (Load->getNumValues() == 3) {
3326           // PRE/POST_INC loads have 3 values.
3327           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3328                            NewLoad.getValue(2) };
3329           CombineTo(Load, To, 3, true);
3330         } else {
3331           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3332         }
3333       }
3334 
3335       // Fold the AND away, taking care not to fold to the old load node if we
3336       // replaced it.
3337       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3338 
3339       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3340     }
3341   }
3342 
3343   // fold (and (load x), 255) -> (zextload x, i8)
3344   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3345   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3346   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3347                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3348                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3349     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3350     LoadSDNode *LN0 = HasAnyExt
3351       ? cast<LoadSDNode>(N0.getOperand(0))
3352       : cast<LoadSDNode>(N0);
3353     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3354         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3355       auto NarrowLoad = false;
3356       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3357       EVT ExtVT, LoadedVT;
3358       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3359                            NarrowLoad)) {
3360         if (!NarrowLoad) {
3361           SDValue NewLoad =
3362             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3363                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3364                            LN0->getMemOperand());
3365           AddToWorklist(N);
3366           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3367           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3368         } else {
3369           EVT PtrType = LN0->getOperand(1).getValueType();
3370 
3371           unsigned Alignment = LN0->getAlignment();
3372           SDValue NewPtr = LN0->getBasePtr();
3373 
3374           // For big endian targets, we need to add an offset to the pointer
3375           // to load the correct bytes.  For little endian systems, we merely
3376           // need to read fewer bytes from the same pointer.
3377           if (DAG.getDataLayout().isBigEndian()) {
3378             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3379             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3380             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3381             SDLoc DL(LN0);
3382             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3383                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3384             Alignment = MinAlign(Alignment, PtrOff);
3385           }
3386 
3387           AddToWorklist(NewPtr.getNode());
3388 
3389           SDValue Load = DAG.getExtLoad(
3390               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3391               LN0->getPointerInfo(), ExtVT, Alignment,
3392               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3393           AddToWorklist(N);
3394           CombineTo(LN0, Load, Load.getValue(1));
3395           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3396         }
3397       }
3398     }
3399   }
3400 
3401   if (SDValue Combined = visitANDLike(N0, N1, N))
3402     return Combined;
3403 
3404   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3405   if (N0.getOpcode() == N1.getOpcode())
3406     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3407       return Tmp;
3408 
3409   // Masking the negated extension of a boolean is just the zero-extended
3410   // boolean:
3411   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3412   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3413   //
3414   // Note: the SimplifyDemandedBits fold below can make an information-losing
3415   // transform, and then we have no way to find this better fold.
3416   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3417     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3418     SDValue SubRHS = N0.getOperand(1);
3419     if (SubLHS && SubLHS->isNullValue()) {
3420       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3421           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3422         return SubRHS;
3423       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3424           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3425         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3426     }
3427   }
3428 
3429   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3430   // fold (and (sra)) -> (and (srl)) when possible.
3431   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
3432     return SDValue(N, 0);
3433 
3434   // fold (zext_inreg (extload x)) -> (zextload x)
3435   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3436     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3437     EVT MemVT = LN0->getMemoryVT();
3438     // If we zero all the possible extended bits, then we can turn this into
3439     // a zextload if we are running before legalize or the operation is legal.
3440     unsigned BitWidth = N1.getScalarValueSizeInBits();
3441     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3442                            BitWidth - MemVT.getScalarSizeInBits())) &&
3443         ((!LegalOperations && !LN0->isVolatile()) ||
3444          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3445       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3446                                        LN0->getChain(), LN0->getBasePtr(),
3447                                        MemVT, LN0->getMemOperand());
3448       AddToWorklist(N);
3449       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3450       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3451     }
3452   }
3453   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3454   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3455       N0.hasOneUse()) {
3456     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3457     EVT MemVT = LN0->getMemoryVT();
3458     // If we zero all the possible extended bits, then we can turn this into
3459     // a zextload if we are running before legalize or the operation is legal.
3460     unsigned BitWidth = N1.getScalarValueSizeInBits();
3461     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3462                            BitWidth - MemVT.getScalarSizeInBits())) &&
3463         ((!LegalOperations && !LN0->isVolatile()) ||
3464          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3465       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3466                                        LN0->getChain(), LN0->getBasePtr(),
3467                                        MemVT, LN0->getMemOperand());
3468       AddToWorklist(N);
3469       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3470       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3471     }
3472   }
3473   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3474   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3475     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3476                                            N0.getOperand(1), false))
3477       return BSwap;
3478   }
3479 
3480   return SDValue();
3481 }
3482 
3483 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3484 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3485                                         bool DemandHighBits) {
3486   if (!LegalOperations)
3487     return SDValue();
3488 
3489   EVT VT = N->getValueType(0);
3490   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3491     return SDValue();
3492   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3493     return SDValue();
3494 
3495   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3496   bool LookPassAnd0 = false;
3497   bool LookPassAnd1 = false;
3498   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3499       std::swap(N0, N1);
3500   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3501       std::swap(N0, N1);
3502   if (N0.getOpcode() == ISD::AND) {
3503     if (!N0.getNode()->hasOneUse())
3504       return SDValue();
3505     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3506     if (!N01C || N01C->getZExtValue() != 0xFF00)
3507       return SDValue();
3508     N0 = N0.getOperand(0);
3509     LookPassAnd0 = true;
3510   }
3511 
3512   if (N1.getOpcode() == ISD::AND) {
3513     if (!N1.getNode()->hasOneUse())
3514       return SDValue();
3515     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3516     if (!N11C || N11C->getZExtValue() != 0xFF)
3517       return SDValue();
3518     N1 = N1.getOperand(0);
3519     LookPassAnd1 = true;
3520   }
3521 
3522   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3523     std::swap(N0, N1);
3524   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3525     return SDValue();
3526   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3527     return SDValue();
3528 
3529   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3530   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3531   if (!N01C || !N11C)
3532     return SDValue();
3533   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3534     return SDValue();
3535 
3536   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3537   SDValue N00 = N0->getOperand(0);
3538   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3539     if (!N00.getNode()->hasOneUse())
3540       return SDValue();
3541     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3542     if (!N001C || N001C->getZExtValue() != 0xFF)
3543       return SDValue();
3544     N00 = N00.getOperand(0);
3545     LookPassAnd0 = true;
3546   }
3547 
3548   SDValue N10 = N1->getOperand(0);
3549   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3550     if (!N10.getNode()->hasOneUse())
3551       return SDValue();
3552     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3553     if (!N101C || N101C->getZExtValue() != 0xFF00)
3554       return SDValue();
3555     N10 = N10.getOperand(0);
3556     LookPassAnd1 = true;
3557   }
3558 
3559   if (N00 != N10)
3560     return SDValue();
3561 
3562   // Make sure everything beyond the low halfword gets set to zero since the SRL
3563   // 16 will clear the top bits.
3564   unsigned OpSizeInBits = VT.getSizeInBits();
3565   if (DemandHighBits && OpSizeInBits > 16) {
3566     // If the left-shift isn't masked out then the only way this is a bswap is
3567     // if all bits beyond the low 8 are 0. In that case the entire pattern
3568     // reduces to a left shift anyway: leave it for other parts of the combiner.
3569     if (!LookPassAnd0)
3570       return SDValue();
3571 
3572     // However, if the right shift isn't masked out then it might be because
3573     // it's not needed. See if we can spot that too.
3574     if (!LookPassAnd1 &&
3575         !DAG.MaskedValueIsZero(
3576             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3577       return SDValue();
3578   }
3579 
3580   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3581   if (OpSizeInBits > 16) {
3582     SDLoc DL(N);
3583     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3584                       DAG.getConstant(OpSizeInBits - 16, DL,
3585                                       getShiftAmountTy(VT)));
3586   }
3587   return Res;
3588 }
3589 
3590 /// Return true if the specified node is an element that makes up a 32-bit
3591 /// packed halfword byteswap.
3592 /// ((x & 0x000000ff) << 8) |
3593 /// ((x & 0x0000ff00) >> 8) |
3594 /// ((x & 0x00ff0000) << 8) |
3595 /// ((x & 0xff000000) >> 8)
3596 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3597   if (!N.getNode()->hasOneUse())
3598     return false;
3599 
3600   unsigned Opc = N.getOpcode();
3601   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3602     return false;
3603 
3604   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3605   if (!N1C)
3606     return false;
3607 
3608   unsigned Num;
3609   switch (N1C->getZExtValue()) {
3610   default:
3611     return false;
3612   case 0xFF:       Num = 0; break;
3613   case 0xFF00:     Num = 1; break;
3614   case 0xFF0000:   Num = 2; break;
3615   case 0xFF000000: Num = 3; break;
3616   }
3617 
3618   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3619   SDValue N0 = N.getOperand(0);
3620   if (Opc == ISD::AND) {
3621     if (Num == 0 || Num == 2) {
3622       // (x >> 8) & 0xff
3623       // (x >> 8) & 0xff0000
3624       if (N0.getOpcode() != ISD::SRL)
3625         return false;
3626       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3627       if (!C || C->getZExtValue() != 8)
3628         return false;
3629     } else {
3630       // (x << 8) & 0xff00
3631       // (x << 8) & 0xff000000
3632       if (N0.getOpcode() != ISD::SHL)
3633         return false;
3634       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3635       if (!C || C->getZExtValue() != 8)
3636         return false;
3637     }
3638   } else if (Opc == ISD::SHL) {
3639     // (x & 0xff) << 8
3640     // (x & 0xff0000) << 8
3641     if (Num != 0 && Num != 2)
3642       return false;
3643     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3644     if (!C || C->getZExtValue() != 8)
3645       return false;
3646   } else { // Opc == ISD::SRL
3647     // (x & 0xff00) >> 8
3648     // (x & 0xff000000) >> 8
3649     if (Num != 1 && Num != 3)
3650       return false;
3651     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3652     if (!C || C->getZExtValue() != 8)
3653       return false;
3654   }
3655 
3656   if (Parts[Num])
3657     return false;
3658 
3659   Parts[Num] = N0.getOperand(0).getNode();
3660   return true;
3661 }
3662 
3663 /// Match a 32-bit packed halfword bswap. That is
3664 /// ((x & 0x000000ff) << 8) |
3665 /// ((x & 0x0000ff00) >> 8) |
3666 /// ((x & 0x00ff0000) << 8) |
3667 /// ((x & 0xff000000) >> 8)
3668 /// => (rotl (bswap x), 16)
3669 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3670   if (!LegalOperations)
3671     return SDValue();
3672 
3673   EVT VT = N->getValueType(0);
3674   if (VT != MVT::i32)
3675     return SDValue();
3676   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3677     return SDValue();
3678 
3679   // Look for either
3680   // (or (or (and), (and)), (or (and), (and)))
3681   // (or (or (or (and), (and)), (and)), (and))
3682   if (N0.getOpcode() != ISD::OR)
3683     return SDValue();
3684   SDValue N00 = N0.getOperand(0);
3685   SDValue N01 = N0.getOperand(1);
3686   SDNode *Parts[4] = {};
3687 
3688   if (N1.getOpcode() == ISD::OR &&
3689       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3690     // (or (or (and), (and)), (or (and), (and)))
3691     SDValue N000 = N00.getOperand(0);
3692     if (!isBSwapHWordElement(N000, Parts))
3693       return SDValue();
3694 
3695     SDValue N001 = N00.getOperand(1);
3696     if (!isBSwapHWordElement(N001, Parts))
3697       return SDValue();
3698     SDValue N010 = N01.getOperand(0);
3699     if (!isBSwapHWordElement(N010, Parts))
3700       return SDValue();
3701     SDValue N011 = N01.getOperand(1);
3702     if (!isBSwapHWordElement(N011, Parts))
3703       return SDValue();
3704   } else {
3705     // (or (or (or (and), (and)), (and)), (and))
3706     if (!isBSwapHWordElement(N1, Parts))
3707       return SDValue();
3708     if (!isBSwapHWordElement(N01, Parts))
3709       return SDValue();
3710     if (N00.getOpcode() != ISD::OR)
3711       return SDValue();
3712     SDValue N000 = N00.getOperand(0);
3713     if (!isBSwapHWordElement(N000, Parts))
3714       return SDValue();
3715     SDValue N001 = N00.getOperand(1);
3716     if (!isBSwapHWordElement(N001, Parts))
3717       return SDValue();
3718   }
3719 
3720   // Make sure the parts are all coming from the same node.
3721   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3722     return SDValue();
3723 
3724   SDLoc DL(N);
3725   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3726                               SDValue(Parts[0], 0));
3727 
3728   // Result of the bswap should be rotated by 16. If it's not legal, then
3729   // do  (x << 16) | (x >> 16).
3730   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3731   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3732     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3733   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3734     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3735   return DAG.getNode(ISD::OR, DL, VT,
3736                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3737                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3738 }
3739 
3740 /// This contains all DAGCombine rules which reduce two values combined by
3741 /// an Or operation to a single value \see visitANDLike().
3742 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3743   EVT VT = N1.getValueType();
3744   // fold (or x, undef) -> -1
3745   if (!LegalOperations &&
3746       (N0.isUndef() || N1.isUndef())) {
3747     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3748     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3749                            SDLoc(LocReference), VT);
3750   }
3751   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3752   SDValue LL, LR, RL, RR, CC0, CC1;
3753   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3754     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3755     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3756 
3757     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3758       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3759       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3760       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3761         EVT CCVT = getSetCCResultType(LR.getValueType());
3762         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3763           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3764                                        LR.getValueType(), LL, RL);
3765           AddToWorklist(ORNode.getNode());
3766           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3767         }
3768       }
3769       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3770       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3771       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3772         EVT CCVT = getSetCCResultType(LR.getValueType());
3773         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3774           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3775                                         LR.getValueType(), LL, RL);
3776           AddToWorklist(ANDNode.getNode());
3777           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3778         }
3779       }
3780     }
3781     // canonicalize equivalent to ll == rl
3782     if (LL == RR && LR == RL) {
3783       Op1 = ISD::getSetCCSwappedOperands(Op1);
3784       std::swap(RL, RR);
3785     }
3786     if (LL == RL && LR == RR) {
3787       bool isInteger = LL.getValueType().isInteger();
3788       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3789       if (Result != ISD::SETCC_INVALID &&
3790           (!LegalOperations ||
3791            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3792             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3793         EVT CCVT = getSetCCResultType(LL.getValueType());
3794         if (N0.getValueType() == CCVT ||
3795             (!LegalOperations && N0.getValueType() == MVT::i1))
3796           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3797                               LL, LR, Result);
3798       }
3799     }
3800   }
3801 
3802   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3803   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3804       // Don't increase # computations.
3805       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3806     // We can only do this xform if we know that bits from X that are set in C2
3807     // but not in C1 are already zero.  Likewise for Y.
3808     if (const ConstantSDNode *N0O1C =
3809         getAsNonOpaqueConstant(N0.getOperand(1))) {
3810       if (const ConstantSDNode *N1O1C =
3811           getAsNonOpaqueConstant(N1.getOperand(1))) {
3812         // We can only do this xform if we know that bits from X that are set in
3813         // C2 but not in C1 are already zero.  Likewise for Y.
3814         const APInt &LHSMask = N0O1C->getAPIntValue();
3815         const APInt &RHSMask = N1O1C->getAPIntValue();
3816 
3817         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3818             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3819           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3820                                   N0.getOperand(0), N1.getOperand(0));
3821           SDLoc DL(LocReference);
3822           return DAG.getNode(ISD::AND, DL, VT, X,
3823                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3824         }
3825       }
3826     }
3827   }
3828 
3829   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3830   if (N0.getOpcode() == ISD::AND &&
3831       N1.getOpcode() == ISD::AND &&
3832       N0.getOperand(0) == N1.getOperand(0) &&
3833       // Don't increase # computations.
3834       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3835     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3836                             N0.getOperand(1), N1.getOperand(1));
3837     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3838   }
3839 
3840   return SDValue();
3841 }
3842 
3843 SDValue DAGCombiner::visitOR(SDNode *N) {
3844   SDValue N0 = N->getOperand(0);
3845   SDValue N1 = N->getOperand(1);
3846   EVT VT = N1.getValueType();
3847 
3848   // x | x --> x
3849   if (N0 == N1)
3850     return N0;
3851 
3852   // fold vector ops
3853   if (VT.isVector()) {
3854     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3855       return FoldedVOp;
3856 
3857     // fold (or x, 0) -> x, vector edition
3858     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3859       return N1;
3860     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3861       return N0;
3862 
3863     // fold (or x, -1) -> -1, vector edition
3864     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3865       // do not return N0, because undef node may exist in N0
3866       return DAG.getConstant(
3867           APInt::getAllOnesValue(N0.getScalarValueSizeInBits()), SDLoc(N),
3868           N0.getValueType());
3869     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3870       // do not return N1, because undef node may exist in N1
3871       return DAG.getConstant(
3872           APInt::getAllOnesValue(N1.getScalarValueSizeInBits()), SDLoc(N),
3873           N1.getValueType());
3874 
3875     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3876     // Do this only if the resulting shuffle is legal.
3877     if (isa<ShuffleVectorSDNode>(N0) &&
3878         isa<ShuffleVectorSDNode>(N1) &&
3879         // Avoid folding a node with illegal type.
3880         TLI.isTypeLegal(VT)) {
3881       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3882       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3883       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3884       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3885       // Ensure both shuffles have a zero input.
3886       if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3887         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3888         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3889         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3890         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3891         bool CanFold = true;
3892         int NumElts = VT.getVectorNumElements();
3893         SmallVector<int, 4> Mask(NumElts);
3894 
3895         for (int i = 0; i != NumElts; ++i) {
3896           int M0 = SV0->getMaskElt(i);
3897           int M1 = SV1->getMaskElt(i);
3898 
3899           // Determine if either index is pointing to a zero vector.
3900           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
3901           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
3902 
3903           // If one element is zero and the otherside is undef, keep undef.
3904           // This also handles the case that both are undef.
3905           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
3906             Mask[i] = -1;
3907             continue;
3908           }
3909 
3910           // Make sure only one of the elements is zero.
3911           if (M0Zero == M1Zero) {
3912             CanFold = false;
3913             break;
3914           }
3915 
3916           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
3917 
3918           // We have a zero and non-zero element. If the non-zero came from
3919           // SV0 make the index a LHS index. If it came from SV1, make it
3920           // a RHS index. We need to mod by NumElts because we don't care
3921           // which operand it came from in the original shuffles.
3922           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3923         }
3924 
3925         if (CanFold) {
3926           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3927           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3928 
3929           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3930           if (!LegalMask) {
3931             std::swap(NewLHS, NewRHS);
3932             ShuffleVectorSDNode::commuteMask(Mask);
3933             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3934           }
3935 
3936           if (LegalMask)
3937             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
3938         }
3939       }
3940     }
3941   }
3942 
3943   // fold (or c1, c2) -> c1|c2
3944   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3945   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3946   if (N0C && N1C && !N1C->isOpaque())
3947     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3948   // canonicalize constant to RHS
3949   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3950      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3951     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3952   // fold (or x, 0) -> x
3953   if (isNullConstant(N1))
3954     return N0;
3955   // fold (or x, -1) -> -1
3956   if (isAllOnesConstant(N1))
3957     return N1;
3958   // fold (or x, c) -> c iff (x & ~c) == 0
3959   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3960     return N1;
3961 
3962   if (SDValue Combined = visitORLike(N0, N1, N))
3963     return Combined;
3964 
3965   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3966   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3967     return BSwap;
3968   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3969     return BSwap;
3970 
3971   // reassociate or
3972   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3973     return ROR;
3974   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3975   // iff (c1 & c2) == 0.
3976   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3977              isa<ConstantSDNode>(N0.getOperand(1))) {
3978     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3979     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3980       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3981                                                    N1C, C1))
3982         return DAG.getNode(
3983             ISD::AND, SDLoc(N), VT,
3984             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3985       return SDValue();
3986     }
3987   }
3988   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3989   if (N0.getOpcode() == N1.getOpcode())
3990     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3991       return Tmp;
3992 
3993   // See if this is some rotate idiom.
3994   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3995     return SDValue(Rot, 0);
3996 
3997   if (SDValue Load = MatchLoadCombine(N))
3998     return Load;
3999 
4000   // Simplify the operands using demanded-bits information.
4001   if (!VT.isVector() &&
4002       SimplifyDemandedBits(SDValue(N, 0)))
4003     return SDValue(N, 0);
4004 
4005   return SDValue();
4006 }
4007 
4008 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4009 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4010   if (Op.getOpcode() == ISD::AND) {
4011     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4012       Mask = Op.getOperand(1);
4013       Op = Op.getOperand(0);
4014     } else {
4015       return false;
4016     }
4017   }
4018 
4019   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4020     Shift = Op;
4021     return true;
4022   }
4023 
4024   return false;
4025 }
4026 
4027 // Return true if we can prove that, whenever Neg and Pos are both in the
4028 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4029 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4030 //
4031 //     (or (shift1 X, Neg), (shift2 X, Pos))
4032 //
4033 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4034 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4035 // to consider shift amounts with defined behavior.
4036 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4037   // If EltSize is a power of 2 then:
4038   //
4039   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4040   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4041   //
4042   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4043   // for the stronger condition:
4044   //
4045   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4046   //
4047   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4048   // we can just replace Neg with Neg' for the rest of the function.
4049   //
4050   // In other cases we check for the even stronger condition:
4051   //
4052   //     Neg == EltSize - Pos                                    [B]
4053   //
4054   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4055   // behavior if Pos == 0 (and consequently Neg == EltSize).
4056   //
4057   // We could actually use [A] whenever EltSize is a power of 2, but the
4058   // only extra cases that it would match are those uninteresting ones
4059   // where Neg and Pos are never in range at the same time.  E.g. for
4060   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4061   // as well as (sub 32, Pos), but:
4062   //
4063   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4064   //
4065   // always invokes undefined behavior for 32-bit X.
4066   //
4067   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4068   unsigned MaskLoBits = 0;
4069   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4070     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4071       if (NegC->getAPIntValue() == EltSize - 1) {
4072         Neg = Neg.getOperand(0);
4073         MaskLoBits = Log2_64(EltSize);
4074       }
4075     }
4076   }
4077 
4078   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4079   if (Neg.getOpcode() != ISD::SUB)
4080     return false;
4081   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4082   if (!NegC)
4083     return false;
4084   SDValue NegOp1 = Neg.getOperand(1);
4085 
4086   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4087   // Pos'.  The truncation is redundant for the purpose of the equality.
4088   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4089     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4090       if (PosC->getAPIntValue() == EltSize - 1)
4091         Pos = Pos.getOperand(0);
4092 
4093   // The condition we need is now:
4094   //
4095   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4096   //
4097   // If NegOp1 == Pos then we need:
4098   //
4099   //              EltSize & Mask == NegC & Mask
4100   //
4101   // (because "x & Mask" is a truncation and distributes through subtraction).
4102   APInt Width;
4103   if (Pos == NegOp1)
4104     Width = NegC->getAPIntValue();
4105 
4106   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4107   // Then the condition we want to prove becomes:
4108   //
4109   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4110   //
4111   // which, again because "x & Mask" is a truncation, becomes:
4112   //
4113   //                NegC & Mask == (EltSize - PosC) & Mask
4114   //             EltSize & Mask == (NegC + PosC) & Mask
4115   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4116     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4117       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4118     else
4119       return false;
4120   } else
4121     return false;
4122 
4123   // Now we just need to check that EltSize & Mask == Width & Mask.
4124   if (MaskLoBits)
4125     // EltSize & Mask is 0 since Mask is EltSize - 1.
4126     return Width.getLoBits(MaskLoBits) == 0;
4127   return Width == EltSize;
4128 }
4129 
4130 // A subroutine of MatchRotate used once we have found an OR of two opposite
4131 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4132 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4133 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4134 // Neg with outer conversions stripped away.
4135 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4136                                        SDValue Neg, SDValue InnerPos,
4137                                        SDValue InnerNeg, unsigned PosOpcode,
4138                                        unsigned NegOpcode, const SDLoc &DL) {
4139   // fold (or (shl x, (*ext y)),
4140   //          (srl x, (*ext (sub 32, y)))) ->
4141   //   (rotl x, y) or (rotr x, (sub 32, y))
4142   //
4143   // fold (or (shl x, (*ext (sub 32, y))),
4144   //          (srl x, (*ext y))) ->
4145   //   (rotr x, y) or (rotl x, (sub 32, y))
4146   EVT VT = Shifted.getValueType();
4147   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4148     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4149     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4150                        HasPos ? Pos : Neg).getNode();
4151   }
4152 
4153   return nullptr;
4154 }
4155 
4156 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4157 // idioms for rotate, and if the target supports rotation instructions, generate
4158 // a rot[lr].
4159 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4160   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4161   EVT VT = LHS.getValueType();
4162   if (!TLI.isTypeLegal(VT)) return nullptr;
4163 
4164   // The target must have at least one rotate flavor.
4165   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4166   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4167   if (!HasROTL && !HasROTR) return nullptr;
4168 
4169   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4170   SDValue LHSShift;   // The shift.
4171   SDValue LHSMask;    // AND value if any.
4172   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4173     return nullptr; // Not part of a rotate.
4174 
4175   SDValue RHSShift;   // The shift.
4176   SDValue RHSMask;    // AND value if any.
4177   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4178     return nullptr; // Not part of a rotate.
4179 
4180   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4181     return nullptr;   // Not shifting the same value.
4182 
4183   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4184     return nullptr;   // Shifts must disagree.
4185 
4186   // Canonicalize shl to left side in a shl/srl pair.
4187   if (RHSShift.getOpcode() == ISD::SHL) {
4188     std::swap(LHS, RHS);
4189     std::swap(LHSShift, RHSShift);
4190     std::swap(LHSMask, RHSMask);
4191   }
4192 
4193   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4194   SDValue LHSShiftArg = LHSShift.getOperand(0);
4195   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4196   SDValue RHSShiftArg = RHSShift.getOperand(0);
4197   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4198 
4199   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4200   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4201   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4202     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4203     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4204     if ((LShVal + RShVal) != EltSizeInBits)
4205       return nullptr;
4206 
4207     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4208                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4209 
4210     // If there is an AND of either shifted operand, apply it to the result.
4211     if (LHSMask.getNode() || RHSMask.getNode()) {
4212       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4213       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4214 
4215       if (LHSMask.getNode()) {
4216         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4217         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4218                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4219                                        DAG.getConstant(RHSBits, DL, VT)));
4220       }
4221       if (RHSMask.getNode()) {
4222         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4223         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4224                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4225                                        DAG.getConstant(LHSBits, DL, VT)));
4226       }
4227 
4228       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4229     }
4230 
4231     return Rot.getNode();
4232   }
4233 
4234   // If there is a mask here, and we have a variable shift, we can't be sure
4235   // that we're masking out the right stuff.
4236   if (LHSMask.getNode() || RHSMask.getNode())
4237     return nullptr;
4238 
4239   // If the shift amount is sign/zext/any-extended just peel it off.
4240   SDValue LExtOp0 = LHSShiftAmt;
4241   SDValue RExtOp0 = RHSShiftAmt;
4242   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4243        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4244        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4245        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4246       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4247        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4248        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4249        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4250     LExtOp0 = LHSShiftAmt.getOperand(0);
4251     RExtOp0 = RHSShiftAmt.getOperand(0);
4252   }
4253 
4254   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4255                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4256   if (TryL)
4257     return TryL;
4258 
4259   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4260                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4261   if (TryR)
4262     return TryR;
4263 
4264   return nullptr;
4265 }
4266 
4267 namespace {
4268 /// Helper struct to parse and store a memory address as base + index + offset.
4269 /// We ignore sign extensions when it is safe to do so.
4270 /// The following two expressions are not equivalent. To differentiate we need
4271 /// to store whether there was a sign extension involved in the index
4272 /// computation.
4273 ///  (load (i64 add (i64 copyfromreg %c)
4274 ///                 (i64 signextend (add (i8 load %index)
4275 ///                                      (i8 1))))
4276 /// vs
4277 ///
4278 /// (load (i64 add (i64 copyfromreg %c)
4279 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
4280 ///                                         (i32 1)))))
4281 struct BaseIndexOffset {
4282   SDValue Base;
4283   SDValue Index;
4284   int64_t Offset;
4285   bool IsIndexSignExt;
4286 
4287   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
4288 
4289   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
4290                   bool IsIndexSignExt) :
4291     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
4292 
4293   bool equalBaseIndex(const BaseIndexOffset &Other) {
4294     return Other.Base == Base && Other.Index == Index &&
4295       Other.IsIndexSignExt == IsIndexSignExt;
4296   }
4297 
4298   /// Parses tree in Ptr for base, index, offset addresses.
4299   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG,
4300                                int64_t PartialOffset = 0) {
4301     bool IsIndexSignExt = false;
4302 
4303     // Split up a folded GlobalAddress+Offset into its component parts.
4304     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
4305       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
4306         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
4307                                                     SDLoc(GA),
4308                                                     GA->getValueType(0),
4309                                                     /*Offset=*/PartialOffset,
4310                                                     /*isTargetGA=*/false,
4311                                                     GA->getTargetFlags()),
4312                                SDValue(),
4313                                GA->getOffset(),
4314                                IsIndexSignExt);
4315       }
4316 
4317     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
4318     // instruction, then it could be just the BASE or everything else we don't
4319     // know how to handle. Just use Ptr as BASE and give up.
4320     if (Ptr->getOpcode() != ISD::ADD)
4321       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4322 
4323     // We know that we have at least an ADD instruction. Try to pattern match
4324     // the simple case of BASE + OFFSET.
4325     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
4326       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
4327       return match(Ptr->getOperand(0), DAG, Offset + PartialOffset);
4328     }
4329 
4330     // Inside a loop the current BASE pointer is calculated using an ADD and a
4331     // MUL instruction. In this case Ptr is the actual BASE pointer.
4332     // (i64 add (i64 %array_ptr)
4333     //          (i64 mul (i64 %induction_var)
4334     //                   (i64 %element_size)))
4335     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
4336       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4337 
4338     // Look at Base + Index + Offset cases.
4339     SDValue Base = Ptr->getOperand(0);
4340     SDValue IndexOffset = Ptr->getOperand(1);
4341 
4342     // Skip signextends.
4343     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
4344       IndexOffset = IndexOffset->getOperand(0);
4345       IsIndexSignExt = true;
4346     }
4347 
4348     // Either the case of Base + Index (no offset) or something else.
4349     if (IndexOffset->getOpcode() != ISD::ADD)
4350       return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt);
4351 
4352     // Now we have the case of Base + Index + offset.
4353     SDValue Index = IndexOffset->getOperand(0);
4354     SDValue Offset = IndexOffset->getOperand(1);
4355 
4356     if (!isa<ConstantSDNode>(Offset))
4357       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4358 
4359     // Ignore signextends.
4360     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
4361       Index = Index->getOperand(0);
4362       IsIndexSignExt = true;
4363     } else IsIndexSignExt = false;
4364 
4365     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
4366     return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt);
4367   }
4368 };
4369 } // namespace
4370 
4371 namespace {
4372 /// Represents known origin of an individual byte in load combine pattern. The
4373 /// value of the byte is either constant zero or comes from memory.
4374 struct ByteProvider {
4375   // For constant zero providers Load is set to nullptr. For memory providers
4376   // Load represents the node which loads the byte from memory.
4377   // ByteOffset is the offset of the byte in the value produced by the load.
4378   LoadSDNode *Load;
4379   unsigned ByteOffset;
4380 
4381   ByteProvider() : Load(nullptr), ByteOffset(0) {}
4382 
4383   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4384     return ByteProvider(Load, ByteOffset);
4385   }
4386   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4387 
4388   bool isConstantZero() { return !Load; }
4389   bool isMemory() { return Load; }
4390 
4391   bool operator==(const ByteProvider &Other) const {
4392     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4393   }
4394 
4395 private:
4396   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4397       : Load(Load), ByteOffset(ByteOffset) {}
4398 };
4399 
4400 /// Recursively traverses the expression calculating the origin of the requested
4401 /// byte of the given value. Returns None if the provider can't be calculated.
4402 ///
4403 /// For all the values except the root of the expression verifies that the value
4404 /// has exactly one use and if it's not true return None. This way if the origin
4405 /// of the byte is returned it's guaranteed that the values which contribute to
4406 /// the byte are not used outside of this expression.
4407 ///
4408 /// Because the parts of the expression are not allowed to have more than one
4409 /// use this function iterates over trees, not DAGs. So it never visits the same
4410 /// node more than once.
4411 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4412                                                    unsigned Depth,
4413                                                    bool Root = false) {
4414   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4415   if (Depth == 10)
4416     return None;
4417 
4418   if (!Root && !Op.hasOneUse())
4419     return None;
4420 
4421   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4422   unsigned BitWidth = Op.getValueSizeInBits();
4423   if (BitWidth % 8 != 0)
4424     return None;
4425   unsigned ByteWidth = BitWidth / 8;
4426   assert(Index < ByteWidth && "invalid index requested");
4427   (void) ByteWidth;
4428 
4429   switch (Op.getOpcode()) {
4430   case ISD::OR: {
4431     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4432     if (!LHS)
4433       return None;
4434     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4435     if (!RHS)
4436       return None;
4437 
4438     if (LHS->isConstantZero())
4439       return RHS;
4440     else if (RHS->isConstantZero())
4441       return LHS;
4442     else
4443       return None;
4444   }
4445   case ISD::SHL: {
4446     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4447     if (!ShiftOp)
4448       return None;
4449 
4450     uint64_t BitShift = ShiftOp->getZExtValue();
4451     if (BitShift % 8 != 0)
4452       return None;
4453     uint64_t ByteShift = BitShift / 8;
4454 
4455     return Index < ByteShift
4456                ? ByteProvider::getConstantZero()
4457                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4458                                        Depth + 1);
4459   }
4460   case ISD::ZERO_EXTEND: {
4461     SDValue NarrowOp = Op->getOperand(0);
4462     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4463     if (NarrowBitWidth % 8 != 0)
4464       return None;
4465     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4466 
4467     return Index >= NarrowByteWidth
4468                ? ByteProvider::getConstantZero()
4469                : calculateByteProvider(NarrowOp, Index, Depth + 1);
4470   }
4471   case ISD::LOAD: {
4472     auto L = cast<LoadSDNode>(Op.getNode());
4473 
4474     // TODO: support ext loads
4475     if (L->isVolatile() || L->isIndexed() ||
4476         L->getExtensionType() != ISD::NON_EXTLOAD)
4477       return None;
4478 
4479     return ByteProvider::getMemory(L, Index);
4480   }
4481   }
4482 
4483   return None;
4484 }
4485 } // namespace
4486 
4487 /// Match a pattern where a wide type scalar value is loaded by several narrow
4488 /// loads and combined by shifts and ors. Fold it into a single load or a load
4489 /// and a BSWAP if the targets supports it.
4490 ///
4491 /// Assuming little endian target:
4492 ///  i8 *a = ...
4493 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4494 /// =>
4495 ///  i32 val = *((i32)a)
4496 ///
4497 ///  i8 *a = ...
4498 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4499 /// =>
4500 ///  i32 val = BSWAP(*((i32)a))
4501 ///
4502 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4503 /// interact well with the worklist mechanism. When a part of the pattern is
4504 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4505 /// but the root node of the pattern which triggers the load combine is not
4506 /// necessarily a direct user of the changed node. For example, once the address
4507 /// of t28 load is reassociated load combine won't be triggered:
4508 ///             t25: i32 = add t4, Constant:i32<2>
4509 ///           t26: i64 = sign_extend t25
4510 ///        t27: i64 = add t2, t26
4511 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4512 ///     t29: i32 = zero_extend t28
4513 ///   t32: i32 = shl t29, Constant:i8<8>
4514 /// t33: i32 = or t23, t32
4515 /// As a possible fix visitLoad can check if the load can be a part of a load
4516 /// combine pattern and add corresponding OR roots to the worklist.
4517 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4518   assert(N->getOpcode() == ISD::OR &&
4519          "Can only match load combining against OR nodes");
4520 
4521   // Handles simple types only
4522   EVT VT = N->getValueType(0);
4523   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4524     return SDValue();
4525   unsigned ByteWidth = VT.getSizeInBits() / 8;
4526 
4527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4528   // Before legalize we can introduce too wide illegal loads which will be later
4529   // split into legal sized loads. This enables us to combine i64 load by i8
4530   // patterns to a couple of i32 loads on 32 bit targets.
4531   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4532     return SDValue();
4533 
4534   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4535     unsigned BW, unsigned i) { return i; };
4536   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4537     unsigned BW, unsigned i) { return BW - i - 1; };
4538 
4539   Optional<BaseIndexOffset> Base;
4540   SDValue Chain;
4541 
4542   SmallSet<LoadSDNode *, 8> Loads;
4543   LoadSDNode *FirstLoad = nullptr;
4544 
4545   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4546   auto ByteAt = IsBigEndianTarget ? BigEndianByteAt : LittleEndianByteAt;
4547 
4548   // Check if all the bytes of the OR we are looking at are loaded from the same
4549   // base address. Collect bytes offsets from Base address in ByteOffsets.
4550   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4551   for (unsigned i = 0; i < ByteWidth; i++) {
4552     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4553     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4554       return SDValue();
4555 
4556     LoadSDNode *L = P->Load;
4557     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4558            (L->getExtensionType() == ISD::NON_EXTLOAD) &&
4559            "Must be enforced by calculateByteProvider");
4560     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4561 
4562     // All loads must share the same chain
4563     SDValue LChain = L->getChain();
4564     if (!Chain)
4565       Chain = LChain;
4566     else if (Chain != LChain)
4567       return SDValue();
4568 
4569     // Loads must share the same base address
4570     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4571     if (!Base)
4572       Base = Ptr;
4573     else if (!Base->equalBaseIndex(Ptr))
4574       return SDValue();
4575 
4576     // Calculate the offset of the current byte from the base address
4577     unsigned LoadBitWidth = L->getMemoryVT().getSizeInBits();
4578     assert(LoadBitWidth % 8 == 0 &&
4579            "can only analyze providers for individual bytes not bit");
4580     unsigned LoadByteWidth = LoadBitWidth / 8;
4581     int64_t MemoryByteOffset = ByteAt(LoadByteWidth, P->ByteOffset);
4582     int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset;
4583     ByteOffsets[i] = ByteOffsetFromBase;
4584 
4585     // Remember the first byte load
4586     if (ByteOffsetFromBase == 0)
4587       FirstLoad = L;
4588 
4589     Loads.insert(L);
4590   }
4591   assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4592          "memory, so there must be at least one load which produces the value");
4593   assert(Base && "Base address of the accessed memory location must be set");
4594 
4595   // Check if the bytes of the OR we are looking at match with either big or
4596   // little endian value load
4597   bool BigEndian = true, LittleEndian = true;
4598   for (unsigned i = 0; i < ByteWidth; i++) {
4599     LittleEndian &= ByteOffsets[i] == LittleEndianByteAt(ByteWidth, i);
4600     BigEndian &= ByteOffsets[i] == BigEndianByteAt(ByteWidth, i);
4601     if (!BigEndian && !LittleEndian)
4602       return SDValue();
4603   }
4604   assert((BigEndian != LittleEndian) && "should be either or");
4605   assert(FirstLoad && "must be set");
4606 
4607   // The node we are looking at matches with the pattern, check if we can
4608   // replace it with a single load and bswap if needed.
4609 
4610   // If the load needs byte swap check if the target supports it
4611   bool NeedsBswap = IsBigEndianTarget != BigEndian;
4612 
4613   // Before legalize we can introduce illegal bswaps which will be later
4614   // converted to an explicit bswap sequence. This way we end up with a single
4615   // load and byte shuffling instead of several loads and byte shuffling.
4616   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4617     return SDValue();
4618 
4619   // Check that a load of the wide type is both allowed and fast on the target
4620   bool Fast = false;
4621   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4622                                         VT, FirstLoad->getAddressSpace(),
4623                                         FirstLoad->getAlignment(), &Fast);
4624   if (!Allowed || !Fast)
4625     return SDValue();
4626 
4627   SDValue NewLoad =
4628       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4629                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
4630 
4631   // Transfer chain users from old loads to the new load.
4632   for (LoadSDNode *L : Loads)
4633     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
4634 
4635   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
4636 }
4637 
4638 SDValue DAGCombiner::visitXOR(SDNode *N) {
4639   SDValue N0 = N->getOperand(0);
4640   SDValue N1 = N->getOperand(1);
4641   EVT VT = N0.getValueType();
4642 
4643   // fold vector ops
4644   if (VT.isVector()) {
4645     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4646       return FoldedVOp;
4647 
4648     // fold (xor x, 0) -> x, vector edition
4649     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4650       return N1;
4651     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4652       return N0;
4653   }
4654 
4655   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4656   if (N0.isUndef() && N1.isUndef())
4657     return DAG.getConstant(0, SDLoc(N), VT);
4658   // fold (xor x, undef) -> undef
4659   if (N0.isUndef())
4660     return N0;
4661   if (N1.isUndef())
4662     return N1;
4663   // fold (xor c1, c2) -> c1^c2
4664   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4665   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4666   if (N0C && N1C)
4667     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4668   // canonicalize constant to RHS
4669   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4670      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4671     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4672   // fold (xor x, 0) -> x
4673   if (isNullConstant(N1))
4674     return N0;
4675   // reassociate xor
4676   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4677     return RXOR;
4678 
4679   // fold !(x cc y) -> (x !cc y)
4680   SDValue LHS, RHS, CC;
4681   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4682     bool isInt = LHS.getValueType().isInteger();
4683     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4684                                                isInt);
4685 
4686     if (!LegalOperations ||
4687         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4688       switch (N0.getOpcode()) {
4689       default:
4690         llvm_unreachable("Unhandled SetCC Equivalent!");
4691       case ISD::SETCC:
4692         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4693       case ISD::SELECT_CC:
4694         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4695                                N0.getOperand(3), NotCC);
4696       }
4697     }
4698   }
4699 
4700   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4701   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4702       N0.getNode()->hasOneUse() &&
4703       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4704     SDValue V = N0.getOperand(0);
4705     SDLoc DL(N0);
4706     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4707                     DAG.getConstant(1, DL, V.getValueType()));
4708     AddToWorklist(V.getNode());
4709     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4710   }
4711 
4712   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4713   if (isOneConstant(N1) && VT == MVT::i1 &&
4714       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4715     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4716     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4717       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4718       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4719       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4720       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4721       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4722     }
4723   }
4724   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4725   if (isAllOnesConstant(N1) &&
4726       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4727     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4728     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4729       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4730       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4731       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4732       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4733       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4734     }
4735   }
4736   // fold (xor (and x, y), y) -> (and (not x), y)
4737   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4738       N0->getOperand(1) == N1) {
4739     SDValue X = N0->getOperand(0);
4740     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4741     AddToWorklist(NotX.getNode());
4742     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4743   }
4744   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4745   if (N1C && N0.getOpcode() == ISD::XOR) {
4746     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4747       SDLoc DL(N);
4748       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4749                          DAG.getConstant(N1C->getAPIntValue() ^
4750                                          N00C->getAPIntValue(), DL, VT));
4751     }
4752     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4753       SDLoc DL(N);
4754       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4755                          DAG.getConstant(N1C->getAPIntValue() ^
4756                                          N01C->getAPIntValue(), DL, VT));
4757     }
4758   }
4759   // fold (xor x, x) -> 0
4760   if (N0 == N1)
4761     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4762 
4763   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4764   // Here is a concrete example of this equivalence:
4765   // i16   x ==  14
4766   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4767   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4768   //
4769   // =>
4770   //
4771   // i16     ~1      == 0b1111111111111110
4772   // i16 rol(~1, 14) == 0b1011111111111111
4773   //
4774   // Some additional tips to help conceptualize this transform:
4775   // - Try to see the operation as placing a single zero in a value of all ones.
4776   // - There exists no value for x which would allow the result to contain zero.
4777   // - Values of x larger than the bitwidth are undefined and do not require a
4778   //   consistent result.
4779   // - Pushing the zero left requires shifting one bits in from the right.
4780   // A rotate left of ~1 is a nice way of achieving the desired result.
4781   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4782       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4783     SDLoc DL(N);
4784     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4785                        N0.getOperand(1));
4786   }
4787 
4788   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4789   if (N0.getOpcode() == N1.getOpcode())
4790     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4791       return Tmp;
4792 
4793   // Simplify the expression using non-local knowledge.
4794   if (!VT.isVector() &&
4795       SimplifyDemandedBits(SDValue(N, 0)))
4796     return SDValue(N, 0);
4797 
4798   return SDValue();
4799 }
4800 
4801 /// Handle transforms common to the three shifts, when the shift amount is a
4802 /// constant.
4803 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4804   SDNode *LHS = N->getOperand(0).getNode();
4805   if (!LHS->hasOneUse()) return SDValue();
4806 
4807   // We want to pull some binops through shifts, so that we have (and (shift))
4808   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4809   // thing happens with address calculations, so it's important to canonicalize
4810   // it.
4811   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4812 
4813   switch (LHS->getOpcode()) {
4814   default: return SDValue();
4815   case ISD::OR:
4816   case ISD::XOR:
4817     HighBitSet = false; // We can only transform sra if the high bit is clear.
4818     break;
4819   case ISD::AND:
4820     HighBitSet = true;  // We can only transform sra if the high bit is set.
4821     break;
4822   case ISD::ADD:
4823     if (N->getOpcode() != ISD::SHL)
4824       return SDValue(); // only shl(add) not sr[al](add).
4825     HighBitSet = false; // We can only transform sra if the high bit is clear.
4826     break;
4827   }
4828 
4829   // We require the RHS of the binop to be a constant and not opaque as well.
4830   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4831   if (!BinOpCst) return SDValue();
4832 
4833   // FIXME: disable this unless the input to the binop is a shift by a constant
4834   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
4835   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4836   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
4837                  BinOpLHSVal->getOpcode() == ISD::SRA ||
4838                  BinOpLHSVal->getOpcode() == ISD::SRL;
4839   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
4840                         BinOpLHSVal->getOpcode() == ISD::SELECT;
4841 
4842   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
4843       !isCopyOrSelect)
4844     return SDValue();
4845 
4846   if (isCopyOrSelect && N->hasOneUse())
4847     return SDValue();
4848 
4849   EVT VT = N->getValueType(0);
4850 
4851   // If this is a signed shift right, and the high bit is modified by the
4852   // logical operation, do not perform the transformation. The highBitSet
4853   // boolean indicates the value of the high bit of the constant which would
4854   // cause it to be modified for this operation.
4855   if (N->getOpcode() == ISD::SRA) {
4856     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4857     if (BinOpRHSSignSet != HighBitSet)
4858       return SDValue();
4859   }
4860 
4861   if (!TLI.isDesirableToCommuteWithShift(LHS))
4862     return SDValue();
4863 
4864   // Fold the constants, shifting the binop RHS by the shift amount.
4865   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4866                                N->getValueType(0),
4867                                LHS->getOperand(1), N->getOperand(1));
4868   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4869 
4870   // Create the new shift.
4871   SDValue NewShift = DAG.getNode(N->getOpcode(),
4872                                  SDLoc(LHS->getOperand(0)),
4873                                  VT, LHS->getOperand(0), N->getOperand(1));
4874 
4875   // Create the new binop.
4876   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4877 }
4878 
4879 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4880   assert(N->getOpcode() == ISD::TRUNCATE);
4881   assert(N->getOperand(0).getOpcode() == ISD::AND);
4882 
4883   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4884   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4885     SDValue N01 = N->getOperand(0).getOperand(1);
4886     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
4887       SDLoc DL(N);
4888       EVT TruncVT = N->getValueType(0);
4889       SDValue N00 = N->getOperand(0).getOperand(0);
4890       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
4891       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
4892       AddToWorklist(Trunc00.getNode());
4893       AddToWorklist(Trunc01.getNode());
4894       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
4895     }
4896   }
4897 
4898   return SDValue();
4899 }
4900 
4901 SDValue DAGCombiner::visitRotate(SDNode *N) {
4902   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4903   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4904       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4905     if (SDValue NewOp1 =
4906             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4907       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4908                          N->getOperand(0), NewOp1);
4909   }
4910   return SDValue();
4911 }
4912 
4913 SDValue DAGCombiner::visitSHL(SDNode *N) {
4914   SDValue N0 = N->getOperand(0);
4915   SDValue N1 = N->getOperand(1);
4916   EVT VT = N0.getValueType();
4917   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4918 
4919   // fold vector ops
4920   if (VT.isVector()) {
4921     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4922       return FoldedVOp;
4923 
4924     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4925     // If setcc produces all-one true value then:
4926     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4927     if (N1CV && N1CV->isConstant()) {
4928       if (N0.getOpcode() == ISD::AND) {
4929         SDValue N00 = N0->getOperand(0);
4930         SDValue N01 = N0->getOperand(1);
4931         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4932 
4933         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4934             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4935                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4936           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4937                                                      N01CV, N1CV))
4938             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4939         }
4940       }
4941     }
4942   }
4943 
4944   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4945 
4946   // fold (shl c1, c2) -> c1<<c2
4947   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4948   if (N0C && N1C && !N1C->isOpaque())
4949     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4950   // fold (shl 0, x) -> 0
4951   if (isNullConstant(N0))
4952     return N0;
4953   // fold (shl x, c >= size(x)) -> undef
4954   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4955     return DAG.getUNDEF(VT);
4956   // fold (shl x, 0) -> x
4957   if (N1C && N1C->isNullValue())
4958     return N0;
4959   // fold (shl undef, x) -> 0
4960   if (N0.isUndef())
4961     return DAG.getConstant(0, SDLoc(N), VT);
4962   // if (shl x, c) is known to be zero, return 0
4963   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4964                             APInt::getAllOnesValue(OpSizeInBits)))
4965     return DAG.getConstant(0, SDLoc(N), VT);
4966   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4967   if (N1.getOpcode() == ISD::TRUNCATE &&
4968       N1.getOperand(0).getOpcode() == ISD::AND) {
4969     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4970       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4971   }
4972 
4973   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4974     return SDValue(N, 0);
4975 
4976   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4977   if (N1C && N0.getOpcode() == ISD::SHL) {
4978     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4979       SDLoc DL(N);
4980       APInt c1 = N0C1->getAPIntValue();
4981       APInt c2 = N1C->getAPIntValue();
4982       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4983 
4984       APInt Sum = c1 + c2;
4985       if (Sum.uge(OpSizeInBits))
4986         return DAG.getConstant(0, DL, VT);
4987 
4988       return DAG.getNode(
4989           ISD::SHL, DL, VT, N0.getOperand(0),
4990           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4991     }
4992   }
4993 
4994   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4995   // For this to be valid, the second form must not preserve any of the bits
4996   // that are shifted out by the inner shift in the first form.  This means
4997   // the outer shift size must be >= the number of bits added by the ext.
4998   // As a corollary, we don't care what kind of ext it is.
4999   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5000               N0.getOpcode() == ISD::ANY_EXTEND ||
5001               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5002       N0.getOperand(0).getOpcode() == ISD::SHL) {
5003     SDValue N0Op0 = N0.getOperand(0);
5004     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5005       APInt c1 = N0Op0C1->getAPIntValue();
5006       APInt c2 = N1C->getAPIntValue();
5007       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5008 
5009       EVT InnerShiftVT = N0Op0.getValueType();
5010       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5011       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5012         SDLoc DL(N0);
5013         APInt Sum = c1 + c2;
5014         if (Sum.uge(OpSizeInBits))
5015           return DAG.getConstant(0, DL, VT);
5016 
5017         return DAG.getNode(
5018             ISD::SHL, DL, VT,
5019             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5020             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5021       }
5022     }
5023   }
5024 
5025   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5026   // Only fold this if the inner zext has no other uses to avoid increasing
5027   // the total number of instructions.
5028   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5029       N0.getOperand(0).getOpcode() == ISD::SRL) {
5030     SDValue N0Op0 = N0.getOperand(0);
5031     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5032       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5033         uint64_t c1 = N0Op0C1->getZExtValue();
5034         uint64_t c2 = N1C->getZExtValue();
5035         if (c1 == c2) {
5036           SDValue NewOp0 = N0.getOperand(0);
5037           EVT CountVT = NewOp0.getOperand(1).getValueType();
5038           SDLoc DL(N);
5039           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5040                                        NewOp0,
5041                                        DAG.getConstant(c2, DL, CountVT));
5042           AddToWorklist(NewSHL.getNode());
5043           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5044         }
5045       }
5046     }
5047   }
5048 
5049   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5050   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5051   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5052       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
5053     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5054       uint64_t C1 = N0C1->getZExtValue();
5055       uint64_t C2 = N1C->getZExtValue();
5056       SDLoc DL(N);
5057       if (C1 <= C2)
5058         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5059                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5060       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5061                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5062     }
5063   }
5064 
5065   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5066   //                               (and (srl x, (sub c1, c2), MASK)
5067   // Only fold this if the inner shift has no other uses -- if it does, folding
5068   // this will increase the total number of instructions.
5069   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5070     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5071       uint64_t c1 = N0C1->getZExtValue();
5072       if (c1 < OpSizeInBits) {
5073         uint64_t c2 = N1C->getZExtValue();
5074         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5075         SDValue Shift;
5076         if (c2 > c1) {
5077           Mask = Mask.shl(c2 - c1);
5078           SDLoc DL(N);
5079           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5080                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5081         } else {
5082           Mask = Mask.lshr(c1 - c2);
5083           SDLoc DL(N);
5084           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5085                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5086         }
5087         SDLoc DL(N0);
5088         return DAG.getNode(ISD::AND, DL, VT, Shift,
5089                            DAG.getConstant(Mask, DL, VT));
5090       }
5091     }
5092   }
5093 
5094   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5095   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5096       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5097     unsigned BitSize = VT.getScalarSizeInBits();
5098     SDLoc DL(N);
5099     SDValue AllBits = DAG.getConstant(APInt::getAllOnesValue(BitSize), DL, VT);
5100     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5101     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5102   }
5103 
5104   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5105   // Variant of version done on multiply, except mul by a power of 2 is turned
5106   // into a shift.
5107   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5108       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5109       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5110     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5111     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5112     AddToWorklist(Shl0.getNode());
5113     AddToWorklist(Shl1.getNode());
5114     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5115   }
5116 
5117   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5118   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5119       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5120       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5121     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5122     if (isConstantOrConstantVector(Shl))
5123       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5124   }
5125 
5126   if (N1C && !N1C->isOpaque())
5127     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5128       return NewSHL;
5129 
5130   return SDValue();
5131 }
5132 
5133 SDValue DAGCombiner::visitSRA(SDNode *N) {
5134   SDValue N0 = N->getOperand(0);
5135   SDValue N1 = N->getOperand(1);
5136   EVT VT = N0.getValueType();
5137   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5138 
5139   // Arithmetic shifting an all-sign-bit value is a no-op.
5140   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5141     return N0;
5142 
5143   // fold vector ops
5144   if (VT.isVector())
5145     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5146       return FoldedVOp;
5147 
5148   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5149 
5150   // fold (sra c1, c2) -> (sra c1, c2)
5151   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5152   if (N0C && N1C && !N1C->isOpaque())
5153     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5154   // fold (sra 0, x) -> 0
5155   if (isNullConstant(N0))
5156     return N0;
5157   // fold (sra -1, x) -> -1
5158   if (isAllOnesConstant(N0))
5159     return N0;
5160   // fold (sra x, c >= size(x)) -> undef
5161   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5162     return DAG.getUNDEF(VT);
5163   // fold (sra x, 0) -> x
5164   if (N1C && N1C->isNullValue())
5165     return N0;
5166   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5167   // sext_inreg.
5168   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5169     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5170     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5171     if (VT.isVector())
5172       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5173                                ExtVT, VT.getVectorNumElements());
5174     if ((!LegalOperations ||
5175          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5176       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5177                          N0.getOperand(0), DAG.getValueType(ExtVT));
5178   }
5179 
5180   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5181   if (N1C && N0.getOpcode() == ISD::SRA) {
5182     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5183       SDLoc DL(N);
5184       APInt c1 = N0C1->getAPIntValue();
5185       APInt c2 = N1C->getAPIntValue();
5186       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5187 
5188       APInt Sum = c1 + c2;
5189       if (Sum.uge(OpSizeInBits))
5190         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5191 
5192       return DAG.getNode(
5193           ISD::SRA, DL, VT, N0.getOperand(0),
5194           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5195     }
5196   }
5197 
5198   // fold (sra (shl X, m), (sub result_size, n))
5199   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5200   // result_size - n != m.
5201   // If truncate is free for the target sext(shl) is likely to result in better
5202   // code.
5203   if (N0.getOpcode() == ISD::SHL && N1C) {
5204     // Get the two constanst of the shifts, CN0 = m, CN = n.
5205     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5206     if (N01C) {
5207       LLVMContext &Ctx = *DAG.getContext();
5208       // Determine what the truncate's result bitsize and type would be.
5209       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5210 
5211       if (VT.isVector())
5212         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5213 
5214       // Determine the residual right-shift amount.
5215       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5216 
5217       // If the shift is not a no-op (in which case this should be just a sign
5218       // extend already), the truncated to type is legal, sign_extend is legal
5219       // on that type, and the truncate to that type is both legal and free,
5220       // perform the transform.
5221       if ((ShiftAmt > 0) &&
5222           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5223           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5224           TLI.isTruncateFree(VT, TruncVT)) {
5225 
5226         SDLoc DL(N);
5227         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5228             getShiftAmountTy(N0.getOperand(0).getValueType()));
5229         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5230                                     N0.getOperand(0), Amt);
5231         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5232                                     Shift);
5233         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5234                            N->getValueType(0), Trunc);
5235       }
5236     }
5237   }
5238 
5239   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5240   if (N1.getOpcode() == ISD::TRUNCATE &&
5241       N1.getOperand(0).getOpcode() == ISD::AND) {
5242     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5243       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5244   }
5245 
5246   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5247   //      if c1 is equal to the number of bits the trunc removes
5248   if (N0.getOpcode() == ISD::TRUNCATE &&
5249       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5250        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5251       N0.getOperand(0).hasOneUse() &&
5252       N0.getOperand(0).getOperand(1).hasOneUse() &&
5253       N1C) {
5254     SDValue N0Op0 = N0.getOperand(0);
5255     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5256       unsigned LargeShiftVal = LargeShift->getZExtValue();
5257       EVT LargeVT = N0Op0.getValueType();
5258 
5259       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5260         SDLoc DL(N);
5261         SDValue Amt =
5262           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5263                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5264         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5265                                   N0Op0.getOperand(0), Amt);
5266         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5267       }
5268     }
5269   }
5270 
5271   // Simplify, based on bits shifted out of the LHS.
5272   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5273     return SDValue(N, 0);
5274 
5275 
5276   // If the sign bit is known to be zero, switch this to a SRL.
5277   if (DAG.SignBitIsZero(N0))
5278     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5279 
5280   if (N1C && !N1C->isOpaque())
5281     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5282       return NewSRA;
5283 
5284   return SDValue();
5285 }
5286 
5287 SDValue DAGCombiner::visitSRL(SDNode *N) {
5288   SDValue N0 = N->getOperand(0);
5289   SDValue N1 = N->getOperand(1);
5290   EVT VT = N0.getValueType();
5291   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5292 
5293   // fold vector ops
5294   if (VT.isVector())
5295     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5296       return FoldedVOp;
5297 
5298   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5299 
5300   // fold (srl c1, c2) -> c1 >>u c2
5301   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5302   if (N0C && N1C && !N1C->isOpaque())
5303     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5304   // fold (srl 0, x) -> 0
5305   if (isNullConstant(N0))
5306     return N0;
5307   // fold (srl x, c >= size(x)) -> undef
5308   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5309     return DAG.getUNDEF(VT);
5310   // fold (srl x, 0) -> x
5311   if (N1C && N1C->isNullValue())
5312     return N0;
5313   // if (srl x, c) is known to be zero, return 0
5314   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5315                                    APInt::getAllOnesValue(OpSizeInBits)))
5316     return DAG.getConstant(0, SDLoc(N), VT);
5317 
5318   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5319   if (N1C && N0.getOpcode() == ISD::SRL) {
5320     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5321       SDLoc DL(N);
5322       APInt c1 = N0C1->getAPIntValue();
5323       APInt c2 = N1C->getAPIntValue();
5324       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5325 
5326       APInt Sum = c1 + c2;
5327       if (Sum.uge(OpSizeInBits))
5328         return DAG.getConstant(0, DL, VT);
5329 
5330       return DAG.getNode(
5331           ISD::SRL, DL, VT, N0.getOperand(0),
5332           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5333     }
5334   }
5335 
5336   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5337   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5338       N0.getOperand(0).getOpcode() == ISD::SRL &&
5339       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
5340     uint64_t c1 =
5341       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
5342     uint64_t c2 = N1C->getZExtValue();
5343     EVT InnerShiftVT = N0.getOperand(0).getValueType();
5344     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
5345     uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5346     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5347     if (c1 + OpSizeInBits == InnerShiftSize) {
5348       SDLoc DL(N0);
5349       if (c1 + c2 >= InnerShiftSize)
5350         return DAG.getConstant(0, DL, VT);
5351       return DAG.getNode(ISD::TRUNCATE, DL, VT,
5352                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5353                                      N0.getOperand(0)->getOperand(0),
5354                                      DAG.getConstant(c1 + c2, DL,
5355                                                      ShiftCountVT)));
5356     }
5357   }
5358 
5359   // fold (srl (shl x, c), c) -> (and x, cst2)
5360   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5361       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5362     SDLoc DL(N);
5363     APInt AllBits = APInt::getAllOnesValue(N0.getScalarValueSizeInBits());
5364     SDValue Mask =
5365         DAG.getNode(ISD::SRL, DL, VT, DAG.getConstant(AllBits, DL, VT), N1);
5366     AddToWorklist(Mask.getNode());
5367     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5368   }
5369 
5370   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5371   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5372     // Shifting in all undef bits?
5373     EVT SmallVT = N0.getOperand(0).getValueType();
5374     unsigned BitSize = SmallVT.getScalarSizeInBits();
5375     if (N1C->getZExtValue() >= BitSize)
5376       return DAG.getUNDEF(VT);
5377 
5378     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5379       uint64_t ShiftAmt = N1C->getZExtValue();
5380       SDLoc DL0(N0);
5381       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5382                                        N0.getOperand(0),
5383                           DAG.getConstant(ShiftAmt, DL0,
5384                                           getShiftAmountTy(SmallVT)));
5385       AddToWorklist(SmallShift.getNode());
5386       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
5387       SDLoc DL(N);
5388       return DAG.getNode(ISD::AND, DL, VT,
5389                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5390                          DAG.getConstant(Mask, DL, VT));
5391     }
5392   }
5393 
5394   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5395   // bit, which is unmodified by sra.
5396   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5397     if (N0.getOpcode() == ISD::SRA)
5398       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5399   }
5400 
5401   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5402   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5403       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5404     APInt KnownZero, KnownOne;
5405     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
5406 
5407     // If any of the input bits are KnownOne, then the input couldn't be all
5408     // zeros, thus the result of the srl will always be zero.
5409     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5410 
5411     // If all of the bits input the to ctlz node are known to be zero, then
5412     // the result of the ctlz is "32" and the result of the shift is one.
5413     APInt UnknownBits = ~KnownZero;
5414     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5415 
5416     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5417     if ((UnknownBits & (UnknownBits - 1)) == 0) {
5418       // Okay, we know that only that the single bit specified by UnknownBits
5419       // could be set on input to the CTLZ node. If this bit is set, the SRL
5420       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5421       // to an SRL/XOR pair, which is likely to simplify more.
5422       unsigned ShAmt = UnknownBits.countTrailingZeros();
5423       SDValue Op = N0.getOperand(0);
5424 
5425       if (ShAmt) {
5426         SDLoc DL(N0);
5427         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5428                   DAG.getConstant(ShAmt, DL,
5429                                   getShiftAmountTy(Op.getValueType())));
5430         AddToWorklist(Op.getNode());
5431       }
5432 
5433       SDLoc DL(N);
5434       return DAG.getNode(ISD::XOR, DL, VT,
5435                          Op, DAG.getConstant(1, DL, VT));
5436     }
5437   }
5438 
5439   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5440   if (N1.getOpcode() == ISD::TRUNCATE &&
5441       N1.getOperand(0).getOpcode() == ISD::AND) {
5442     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5443       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5444   }
5445 
5446   // fold operands of srl based on knowledge that the low bits are not
5447   // demanded.
5448   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5449     return SDValue(N, 0);
5450 
5451   if (N1C && !N1C->isOpaque())
5452     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5453       return NewSRL;
5454 
5455   // Attempt to convert a srl of a load into a narrower zero-extending load.
5456   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5457     return NarrowLoad;
5458 
5459   // Here is a common situation. We want to optimize:
5460   //
5461   //   %a = ...
5462   //   %b = and i32 %a, 2
5463   //   %c = srl i32 %b, 1
5464   //   brcond i32 %c ...
5465   //
5466   // into
5467   //
5468   //   %a = ...
5469   //   %b = and %a, 2
5470   //   %c = setcc eq %b, 0
5471   //   brcond %c ...
5472   //
5473   // However when after the source operand of SRL is optimized into AND, the SRL
5474   // itself may not be optimized further. Look for it and add the BRCOND into
5475   // the worklist.
5476   if (N->hasOneUse()) {
5477     SDNode *Use = *N->use_begin();
5478     if (Use->getOpcode() == ISD::BRCOND)
5479       AddToWorklist(Use);
5480     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5481       // Also look pass the truncate.
5482       Use = *Use->use_begin();
5483       if (Use->getOpcode() == ISD::BRCOND)
5484         AddToWorklist(Use);
5485     }
5486   }
5487 
5488   return SDValue();
5489 }
5490 
5491 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5492   SDValue N0 = N->getOperand(0);
5493   EVT VT = N->getValueType(0);
5494 
5495   // fold (bswap c1) -> c2
5496   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5497     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5498   // fold (bswap (bswap x)) -> x
5499   if (N0.getOpcode() == ISD::BSWAP)
5500     return N0->getOperand(0);
5501   return SDValue();
5502 }
5503 
5504 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5505   SDValue N0 = N->getOperand(0);
5506   EVT VT = N->getValueType(0);
5507 
5508   // fold (bitreverse c1) -> c2
5509   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5510     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5511   // fold (bitreverse (bitreverse x)) -> x
5512   if (N0.getOpcode() == ISD::BITREVERSE)
5513     return N0.getOperand(0);
5514   return SDValue();
5515 }
5516 
5517 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5518   SDValue N0 = N->getOperand(0);
5519   EVT VT = N->getValueType(0);
5520 
5521   // fold (ctlz c1) -> c2
5522   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5523     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5524   return SDValue();
5525 }
5526 
5527 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5528   SDValue N0 = N->getOperand(0);
5529   EVT VT = N->getValueType(0);
5530 
5531   // fold (ctlz_zero_undef c1) -> c2
5532   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5533     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5534   return SDValue();
5535 }
5536 
5537 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5538   SDValue N0 = N->getOperand(0);
5539   EVT VT = N->getValueType(0);
5540 
5541   // fold (cttz c1) -> c2
5542   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5543     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5544   return SDValue();
5545 }
5546 
5547 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5548   SDValue N0 = N->getOperand(0);
5549   EVT VT = N->getValueType(0);
5550 
5551   // fold (cttz_zero_undef c1) -> c2
5552   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5553     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5554   return SDValue();
5555 }
5556 
5557 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5558   SDValue N0 = N->getOperand(0);
5559   EVT VT = N->getValueType(0);
5560 
5561   // fold (ctpop c1) -> c2
5562   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5563     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5564   return SDValue();
5565 }
5566 
5567 
5568 /// \brief Generate Min/Max node
5569 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5570                                    SDValue RHS, SDValue True, SDValue False,
5571                                    ISD::CondCode CC, const TargetLowering &TLI,
5572                                    SelectionDAG &DAG) {
5573   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5574     return SDValue();
5575 
5576   switch (CC) {
5577   case ISD::SETOLT:
5578   case ISD::SETOLE:
5579   case ISD::SETLT:
5580   case ISD::SETLE:
5581   case ISD::SETULT:
5582   case ISD::SETULE: {
5583     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5584     if (TLI.isOperationLegal(Opcode, VT))
5585       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5586     return SDValue();
5587   }
5588   case ISD::SETOGT:
5589   case ISD::SETOGE:
5590   case ISD::SETGT:
5591   case ISD::SETGE:
5592   case ISD::SETUGT:
5593   case ISD::SETUGE: {
5594     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5595     if (TLI.isOperationLegal(Opcode, VT))
5596       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5597     return SDValue();
5598   }
5599   default:
5600     return SDValue();
5601   }
5602 }
5603 
5604 // TODO: We should handle other cases of selecting between {-1,0,1} here.
5605 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5606   SDValue Cond = N->getOperand(0);
5607   SDValue N1 = N->getOperand(1);
5608   SDValue N2 = N->getOperand(2);
5609   EVT VT = N->getValueType(0);
5610   EVT CondVT = Cond.getValueType();
5611   SDLoc DL(N);
5612 
5613   // fold (select Cond, 0, 1) -> (xor Cond, 1)
5614   // We can't do this reliably if integer based booleans have different contents
5615   // to floating point based booleans. This is because we can't tell whether we
5616   // have an integer-based boolean or a floating-point-based boolean unless we
5617   // can find the SETCC that produced it and inspect its operands. This is
5618   // fairly easy if C is the SETCC node, but it can potentially be
5619   // undiscoverable (or not reasonably discoverable). For example, it could be
5620   // in another basic block or it could require searching a complicated
5621   // expression.
5622   if (VT.isInteger() &&
5623       (CondVT == MVT::i1 || (CondVT.isInteger() &&
5624                              TLI.getBooleanContents(false, true) ==
5625                                  TargetLowering::ZeroOrOneBooleanContent &&
5626                              TLI.getBooleanContents(false, false) ==
5627                                  TargetLowering::ZeroOrOneBooleanContent)) &&
5628       isNullConstant(N1) && isOneConstant(N2)) {
5629     SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
5630                                   DAG.getConstant(1, DL, CondVT));
5631     if (VT.bitsEq(CondVT))
5632       return NotCond;
5633     return DAG.getZExtOrTrunc(NotCond, DL, VT);
5634   }
5635 
5636   return SDValue();
5637 }
5638 
5639 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5640   SDValue N0 = N->getOperand(0);
5641   SDValue N1 = N->getOperand(1);
5642   SDValue N2 = N->getOperand(2);
5643   EVT VT = N->getValueType(0);
5644   EVT VT0 = N0.getValueType();
5645 
5646   // fold (select C, X, X) -> X
5647   if (N1 == N2)
5648     return N1;
5649   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5650     // fold (select true, X, Y) -> X
5651     // fold (select false, X, Y) -> Y
5652     return !N0C->isNullValue() ? N1 : N2;
5653   }
5654   // fold (select X, X, Y) -> (or X, Y)
5655   // fold (select X, 1, Y) -> (or C, Y)
5656   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5657     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5658 
5659   if (SDValue V = foldSelectOfConstants(N))
5660     return V;
5661 
5662   // fold (select C, 0, X) -> (and (not C), X)
5663   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5664     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5665     AddToWorklist(NOTNode.getNode());
5666     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5667   }
5668   // fold (select C, X, 1) -> (or (not C), X)
5669   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5670     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5671     AddToWorklist(NOTNode.getNode());
5672     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5673   }
5674   // fold (select X, Y, X) -> (and X, Y)
5675   // fold (select X, Y, 0) -> (and X, Y)
5676   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5677     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5678 
5679   // If we can fold this based on the true/false value, do so.
5680   if (SimplifySelectOps(N, N1, N2))
5681     return SDValue(N, 0);  // Don't revisit N.
5682 
5683   if (VT0 == MVT::i1) {
5684     // The code in this block deals with the following 2 equivalences:
5685     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5686     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5687     // The target can specify its preferred form with the
5688     // shouldNormalizeToSelectSequence() callback. However we always transform
5689     // to the right anyway if we find the inner select exists in the DAG anyway
5690     // and we always transform to the left side if we know that we can further
5691     // optimize the combination of the conditions.
5692     bool normalizeToSequence
5693       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5694     // select (and Cond0, Cond1), X, Y
5695     //   -> select Cond0, (select Cond1, X, Y), Y
5696     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5697       SDValue Cond0 = N0->getOperand(0);
5698       SDValue Cond1 = N0->getOperand(1);
5699       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5700                                         N1.getValueType(), Cond1, N1, N2);
5701       if (normalizeToSequence || !InnerSelect.use_empty())
5702         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5703                            InnerSelect, N2);
5704     }
5705     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5706     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5707       SDValue Cond0 = N0->getOperand(0);
5708       SDValue Cond1 = N0->getOperand(1);
5709       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5710                                         N1.getValueType(), Cond1, N1, N2);
5711       if (normalizeToSequence || !InnerSelect.use_empty())
5712         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5713                            InnerSelect);
5714     }
5715 
5716     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5717     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5718       SDValue N1_0 = N1->getOperand(0);
5719       SDValue N1_1 = N1->getOperand(1);
5720       SDValue N1_2 = N1->getOperand(2);
5721       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5722         // Create the actual and node if we can generate good code for it.
5723         if (!normalizeToSequence) {
5724           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5725                                     N0, N1_0);
5726           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5727                              N1_1, N2);
5728         }
5729         // Otherwise see if we can optimize the "and" to a better pattern.
5730         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5731           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5732                              N1_1, N2);
5733       }
5734     }
5735     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5736     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5737       SDValue N2_0 = N2->getOperand(0);
5738       SDValue N2_1 = N2->getOperand(1);
5739       SDValue N2_2 = N2->getOperand(2);
5740       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5741         // Create the actual or node if we can generate good code for it.
5742         if (!normalizeToSequence) {
5743           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5744                                    N0, N2_0);
5745           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5746                              N1, N2_2);
5747         }
5748         // Otherwise see if we can optimize to a better pattern.
5749         if (SDValue Combined = visitORLike(N0, N2_0, N))
5750           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5751                              N1, N2_2);
5752       }
5753     }
5754   }
5755 
5756   // select (xor Cond, 1), X, Y -> select Cond, Y, X
5757   if (VT0 == MVT::i1) {
5758     if (N0->getOpcode() == ISD::XOR) {
5759       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
5760         SDValue Cond0 = N0->getOperand(0);
5761         if (C->isOne())
5762           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5763                              Cond0, N2, N1);
5764       }
5765     }
5766   }
5767 
5768   // fold selects based on a setcc into other things, such as min/max/abs
5769   if (N0.getOpcode() == ISD::SETCC) {
5770     // select x, y (fcmp lt x, y) -> fminnum x, y
5771     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5772     //
5773     // This is OK if we don't care about what happens if either operand is a
5774     // NaN.
5775     //
5776 
5777     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5778     // no signed zeros as well as no nans.
5779     const TargetOptions &Options = DAG.getTarget().Options;
5780     if (Options.UnsafeFPMath &&
5781         VT.isFloatingPoint() && N0.hasOneUse() &&
5782         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5783       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5784 
5785       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5786                                                 N0.getOperand(1), N1, N2, CC,
5787                                                 TLI, DAG))
5788         return FMinMax;
5789     }
5790 
5791     if ((!LegalOperations &&
5792          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5793         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5794       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5795                          N0.getOperand(0), N0.getOperand(1),
5796                          N1, N2, N0.getOperand(2));
5797     return SimplifySelect(SDLoc(N), N0, N1, N2);
5798   }
5799 
5800   return SDValue();
5801 }
5802 
5803 static
5804 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5805   SDLoc DL(N);
5806   EVT LoVT, HiVT;
5807   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5808 
5809   // Split the inputs.
5810   SDValue Lo, Hi, LL, LH, RL, RH;
5811   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5812   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5813 
5814   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5815   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5816 
5817   return std::make_pair(Lo, Hi);
5818 }
5819 
5820 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5821 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5822 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5823   SDLoc DL(N);
5824   SDValue Cond = N->getOperand(0);
5825   SDValue LHS = N->getOperand(1);
5826   SDValue RHS = N->getOperand(2);
5827   EVT VT = N->getValueType(0);
5828   int NumElems = VT.getVectorNumElements();
5829   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5830          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5831          Cond.getOpcode() == ISD::BUILD_VECTOR);
5832 
5833   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5834   // binary ones here.
5835   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5836     return SDValue();
5837 
5838   // We're sure we have an even number of elements due to the
5839   // concat_vectors we have as arguments to vselect.
5840   // Skip BV elements until we find one that's not an UNDEF
5841   // After we find an UNDEF element, keep looping until we get to half the
5842   // length of the BV and see if all the non-undef nodes are the same.
5843   ConstantSDNode *BottomHalf = nullptr;
5844   for (int i = 0; i < NumElems / 2; ++i) {
5845     if (Cond->getOperand(i)->isUndef())
5846       continue;
5847 
5848     if (BottomHalf == nullptr)
5849       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5850     else if (Cond->getOperand(i).getNode() != BottomHalf)
5851       return SDValue();
5852   }
5853 
5854   // Do the same for the second half of the BuildVector
5855   ConstantSDNode *TopHalf = nullptr;
5856   for (int i = NumElems / 2; i < NumElems; ++i) {
5857     if (Cond->getOperand(i)->isUndef())
5858       continue;
5859 
5860     if (TopHalf == nullptr)
5861       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5862     else if (Cond->getOperand(i).getNode() != TopHalf)
5863       return SDValue();
5864   }
5865 
5866   assert(TopHalf && BottomHalf &&
5867          "One half of the selector was all UNDEFs and the other was all the "
5868          "same value. This should have been addressed before this function.");
5869   return DAG.getNode(
5870       ISD::CONCAT_VECTORS, DL, VT,
5871       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5872       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5873 }
5874 
5875 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5876 
5877   if (Level >= AfterLegalizeTypes)
5878     return SDValue();
5879 
5880   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5881   SDValue Mask = MSC->getMask();
5882   SDValue Data  = MSC->getValue();
5883   SDLoc DL(N);
5884 
5885   // If the MSCATTER data type requires splitting and the mask is provided by a
5886   // SETCC, then split both nodes and its operands before legalization. This
5887   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5888   // and enables future optimizations (e.g. min/max pattern matching on X86).
5889   if (Mask.getOpcode() != ISD::SETCC)
5890     return SDValue();
5891 
5892   // Check if any splitting is required.
5893   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5894       TargetLowering::TypeSplitVector)
5895     return SDValue();
5896   SDValue MaskLo, MaskHi, Lo, Hi;
5897   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5898 
5899   EVT LoVT, HiVT;
5900   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5901 
5902   SDValue Chain = MSC->getChain();
5903 
5904   EVT MemoryVT = MSC->getMemoryVT();
5905   unsigned Alignment = MSC->getOriginalAlignment();
5906 
5907   EVT LoMemVT, HiMemVT;
5908   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5909 
5910   SDValue DataLo, DataHi;
5911   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5912 
5913   SDValue BasePtr = MSC->getBasePtr();
5914   SDValue IndexLo, IndexHi;
5915   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5916 
5917   MachineMemOperand *MMO = DAG.getMachineFunction().
5918     getMachineMemOperand(MSC->getPointerInfo(),
5919                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5920                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5921 
5922   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5923   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5924                             DL, OpsLo, MMO);
5925 
5926   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5927   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5928                             DL, OpsHi, MMO);
5929 
5930   AddToWorklist(Lo.getNode());
5931   AddToWorklist(Hi.getNode());
5932 
5933   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5934 }
5935 
5936 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5937 
5938   if (Level >= AfterLegalizeTypes)
5939     return SDValue();
5940 
5941   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5942   SDValue Mask = MST->getMask();
5943   SDValue Data  = MST->getValue();
5944   EVT VT = Data.getValueType();
5945   SDLoc DL(N);
5946 
5947   // If the MSTORE data type requires splitting and the mask is provided by a
5948   // SETCC, then split both nodes and its operands before legalization. This
5949   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5950   // and enables future optimizations (e.g. min/max pattern matching on X86).
5951   if (Mask.getOpcode() == ISD::SETCC) {
5952 
5953     // Check if any splitting is required.
5954     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5955         TargetLowering::TypeSplitVector)
5956       return SDValue();
5957 
5958     SDValue MaskLo, MaskHi, Lo, Hi;
5959     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5960 
5961     SDValue Chain = MST->getChain();
5962     SDValue Ptr   = MST->getBasePtr();
5963 
5964     EVT MemoryVT = MST->getMemoryVT();
5965     unsigned Alignment = MST->getOriginalAlignment();
5966 
5967     // if Alignment is equal to the vector size,
5968     // take the half of it for the second part
5969     unsigned SecondHalfAlignment =
5970       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
5971 
5972     EVT LoMemVT, HiMemVT;
5973     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5974 
5975     SDValue DataLo, DataHi;
5976     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5977 
5978     MachineMemOperand *MMO = DAG.getMachineFunction().
5979       getMachineMemOperand(MST->getPointerInfo(),
5980                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5981                            Alignment, MST->getAAInfo(), MST->getRanges());
5982 
5983     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5984                             MST->isTruncatingStore(),
5985                             MST->isCompressingStore());
5986 
5987     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
5988                                      MST->isCompressingStore());
5989 
5990     MMO = DAG.getMachineFunction().
5991       getMachineMemOperand(MST->getPointerInfo(),
5992                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5993                            SecondHalfAlignment, MST->getAAInfo(),
5994                            MST->getRanges());
5995 
5996     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5997                             MST->isTruncatingStore(),
5998                             MST->isCompressingStore());
5999 
6000     AddToWorklist(Lo.getNode());
6001     AddToWorklist(Hi.getNode());
6002 
6003     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6004   }
6005   return SDValue();
6006 }
6007 
6008 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6009 
6010   if (Level >= AfterLegalizeTypes)
6011     return SDValue();
6012 
6013   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6014   SDValue Mask = MGT->getMask();
6015   SDLoc DL(N);
6016 
6017   // If the MGATHER result requires splitting and the mask is provided by a
6018   // SETCC, then split both nodes and its operands before legalization. This
6019   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6020   // and enables future optimizations (e.g. min/max pattern matching on X86).
6021 
6022   if (Mask.getOpcode() != ISD::SETCC)
6023     return SDValue();
6024 
6025   EVT VT = N->getValueType(0);
6026 
6027   // Check if any splitting is required.
6028   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6029       TargetLowering::TypeSplitVector)
6030     return SDValue();
6031 
6032   SDValue MaskLo, MaskHi, Lo, Hi;
6033   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6034 
6035   SDValue Src0 = MGT->getValue();
6036   SDValue Src0Lo, Src0Hi;
6037   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6038 
6039   EVT LoVT, HiVT;
6040   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6041 
6042   SDValue Chain = MGT->getChain();
6043   EVT MemoryVT = MGT->getMemoryVT();
6044   unsigned Alignment = MGT->getOriginalAlignment();
6045 
6046   EVT LoMemVT, HiMemVT;
6047   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6048 
6049   SDValue BasePtr = MGT->getBasePtr();
6050   SDValue Index = MGT->getIndex();
6051   SDValue IndexLo, IndexHi;
6052   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6053 
6054   MachineMemOperand *MMO = DAG.getMachineFunction().
6055     getMachineMemOperand(MGT->getPointerInfo(),
6056                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6057                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6058 
6059   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6060   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6061                             MMO);
6062 
6063   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6064   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6065                             MMO);
6066 
6067   AddToWorklist(Lo.getNode());
6068   AddToWorklist(Hi.getNode());
6069 
6070   // Build a factor node to remember that this load is independent of the
6071   // other one.
6072   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6073                       Hi.getValue(1));
6074 
6075   // Legalized the chain result - switch anything that used the old chain to
6076   // use the new one.
6077   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6078 
6079   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6080 
6081   SDValue RetOps[] = { GatherRes, Chain };
6082   return DAG.getMergeValues(RetOps, DL);
6083 }
6084 
6085 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6086 
6087   if (Level >= AfterLegalizeTypes)
6088     return SDValue();
6089 
6090   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6091   SDValue Mask = MLD->getMask();
6092   SDLoc DL(N);
6093 
6094   // If the MLOAD result requires splitting and the mask is provided by a
6095   // SETCC, then split both nodes and its operands before legalization. This
6096   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6097   // and enables future optimizations (e.g. min/max pattern matching on X86).
6098 
6099   if (Mask.getOpcode() == ISD::SETCC) {
6100     EVT VT = N->getValueType(0);
6101 
6102     // Check if any splitting is required.
6103     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6104         TargetLowering::TypeSplitVector)
6105       return SDValue();
6106 
6107     SDValue MaskLo, MaskHi, Lo, Hi;
6108     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6109 
6110     SDValue Src0 = MLD->getSrc0();
6111     SDValue Src0Lo, Src0Hi;
6112     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6113 
6114     EVT LoVT, HiVT;
6115     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6116 
6117     SDValue Chain = MLD->getChain();
6118     SDValue Ptr   = MLD->getBasePtr();
6119     EVT MemoryVT = MLD->getMemoryVT();
6120     unsigned Alignment = MLD->getOriginalAlignment();
6121 
6122     // if Alignment is equal to the vector size,
6123     // take the half of it for the second part
6124     unsigned SecondHalfAlignment =
6125       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6126          Alignment/2 : Alignment;
6127 
6128     EVT LoMemVT, HiMemVT;
6129     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6130 
6131     MachineMemOperand *MMO = DAG.getMachineFunction().
6132     getMachineMemOperand(MLD->getPointerInfo(),
6133                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6134                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6135 
6136     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6137                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6138 
6139     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6140                                      MLD->isExpandingLoad());
6141 
6142     MMO = DAG.getMachineFunction().
6143     getMachineMemOperand(MLD->getPointerInfo(),
6144                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6145                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6146 
6147     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6148                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6149 
6150     AddToWorklist(Lo.getNode());
6151     AddToWorklist(Hi.getNode());
6152 
6153     // Build a factor node to remember that this load is independent of the
6154     // other one.
6155     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6156                         Hi.getValue(1));
6157 
6158     // Legalized the chain result - switch anything that used the old chain to
6159     // use the new one.
6160     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6161 
6162     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6163 
6164     SDValue RetOps[] = { LoadRes, Chain };
6165     return DAG.getMergeValues(RetOps, DL);
6166   }
6167   return SDValue();
6168 }
6169 
6170 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6171   SDValue N0 = N->getOperand(0);
6172   SDValue N1 = N->getOperand(1);
6173   SDValue N2 = N->getOperand(2);
6174   SDLoc DL(N);
6175 
6176   // fold (vselect C, X, X) -> X
6177   if (N1 == N2)
6178     return N1;
6179 
6180   // Canonicalize integer abs.
6181   // vselect (setg[te] X,  0),  X, -X ->
6182   // vselect (setgt    X, -1),  X, -X ->
6183   // vselect (setl[te] X,  0), -X,  X ->
6184   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6185   if (N0.getOpcode() == ISD::SETCC) {
6186     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6187     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6188     bool isAbs = false;
6189     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6190 
6191     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6192          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6193         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6194       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6195     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6196              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6197       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6198 
6199     if (isAbs) {
6200       EVT VT = LHS.getValueType();
6201       SDValue Shift = DAG.getNode(
6202           ISD::SRA, DL, VT, LHS,
6203           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6204       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6205       AddToWorklist(Shift.getNode());
6206       AddToWorklist(Add.getNode());
6207       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6208     }
6209   }
6210 
6211   if (SimplifySelectOps(N, N1, N2))
6212     return SDValue(N, 0);  // Don't revisit N.
6213 
6214   // If the VSELECT result requires splitting and the mask is provided by a
6215   // SETCC, then split both nodes and its operands before legalization. This
6216   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6217   // and enables future optimizations (e.g. min/max pattern matching on X86).
6218   if (N0.getOpcode() == ISD::SETCC) {
6219     EVT VT = N->getValueType(0);
6220 
6221     // Check if any splitting is required.
6222     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6223         TargetLowering::TypeSplitVector)
6224       return SDValue();
6225 
6226     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
6227     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
6228     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
6229     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
6230 
6231     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
6232     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
6233 
6234     // Add the new VSELECT nodes to the work list in case they need to be split
6235     // again.
6236     AddToWorklist(Lo.getNode());
6237     AddToWorklist(Hi.getNode());
6238 
6239     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6240   }
6241 
6242   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6243   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6244     return N1;
6245   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6246   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6247     return N2;
6248 
6249   // The ConvertSelectToConcatVector function is assuming both the above
6250   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6251   // and addressed.
6252   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6253       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6254       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6255     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6256       return CV;
6257   }
6258 
6259   return SDValue();
6260 }
6261 
6262 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6263   SDValue N0 = N->getOperand(0);
6264   SDValue N1 = N->getOperand(1);
6265   SDValue N2 = N->getOperand(2);
6266   SDValue N3 = N->getOperand(3);
6267   SDValue N4 = N->getOperand(4);
6268   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6269 
6270   // fold select_cc lhs, rhs, x, x, cc -> x
6271   if (N2 == N3)
6272     return N2;
6273 
6274   // Determine if the condition we're dealing with is constant
6275   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6276                                   CC, SDLoc(N), false)) {
6277     AddToWorklist(SCC.getNode());
6278 
6279     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6280       if (!SCCC->isNullValue())
6281         return N2;    // cond always true -> true val
6282       else
6283         return N3;    // cond always false -> false val
6284     } else if (SCC->isUndef()) {
6285       // When the condition is UNDEF, just return the first operand. This is
6286       // coherent the DAG creation, no setcc node is created in this case
6287       return N2;
6288     } else if (SCC.getOpcode() == ISD::SETCC) {
6289       // Fold to a simpler select_cc
6290       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6291                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6292                          SCC.getOperand(2));
6293     }
6294   }
6295 
6296   // If we can fold this based on the true/false value, do so.
6297   if (SimplifySelectOps(N, N2, N3))
6298     return SDValue(N, 0);  // Don't revisit N.
6299 
6300   // fold select_cc into other things, such as min/max/abs
6301   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6302 }
6303 
6304 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6305   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6306                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6307                        SDLoc(N));
6308 }
6309 
6310 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6311   SDValue LHS = N->getOperand(0);
6312   SDValue RHS = N->getOperand(1);
6313   SDValue Carry = N->getOperand(2);
6314   SDValue Cond = N->getOperand(3);
6315 
6316   // If Carry is false, fold to a regular SETCC.
6317   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6318     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6319 
6320   return SDValue();
6321 }
6322 
6323 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6324 /// a build_vector of constants.
6325 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6326 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6327 /// Vector extends are not folded if operations are legal; this is to
6328 /// avoid introducing illegal build_vector dag nodes.
6329 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6330                                          SelectionDAG &DAG, bool LegalTypes,
6331                                          bool LegalOperations) {
6332   unsigned Opcode = N->getOpcode();
6333   SDValue N0 = N->getOperand(0);
6334   EVT VT = N->getValueType(0);
6335 
6336   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6337          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6338          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6339          && "Expected EXTEND dag node in input!");
6340 
6341   // fold (sext c1) -> c1
6342   // fold (zext c1) -> c1
6343   // fold (aext c1) -> c1
6344   if (isa<ConstantSDNode>(N0))
6345     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6346 
6347   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6348   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6349   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6350   EVT SVT = VT.getScalarType();
6351   if (!(VT.isVector() &&
6352       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6353       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6354     return nullptr;
6355 
6356   // We can fold this node into a build_vector.
6357   unsigned VTBits = SVT.getSizeInBits();
6358   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6359   SmallVector<SDValue, 8> Elts;
6360   unsigned NumElts = VT.getVectorNumElements();
6361   SDLoc DL(N);
6362 
6363   for (unsigned i=0; i != NumElts; ++i) {
6364     SDValue Op = N0->getOperand(i);
6365     if (Op->isUndef()) {
6366       Elts.push_back(DAG.getUNDEF(SVT));
6367       continue;
6368     }
6369 
6370     SDLoc DL(Op);
6371     // Get the constant value and if needed trunc it to the size of the type.
6372     // Nodes like build_vector might have constants wider than the scalar type.
6373     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6374     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6375       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6376     else
6377       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6378   }
6379 
6380   return DAG.getBuildVector(VT, DL, Elts).getNode();
6381 }
6382 
6383 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6384 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6385 // transformation. Returns true if extension are possible and the above
6386 // mentioned transformation is profitable.
6387 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6388                                     unsigned ExtOpc,
6389                                     SmallVectorImpl<SDNode *> &ExtendNodes,
6390                                     const TargetLowering &TLI) {
6391   bool HasCopyToRegUses = false;
6392   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6393   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6394                             UE = N0.getNode()->use_end();
6395        UI != UE; ++UI) {
6396     SDNode *User = *UI;
6397     if (User == N)
6398       continue;
6399     if (UI.getUse().getResNo() != N0.getResNo())
6400       continue;
6401     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6402     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6403       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6404       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6405         // Sign bits will be lost after a zext.
6406         return false;
6407       bool Add = false;
6408       for (unsigned i = 0; i != 2; ++i) {
6409         SDValue UseOp = User->getOperand(i);
6410         if (UseOp == N0)
6411           continue;
6412         if (!isa<ConstantSDNode>(UseOp))
6413           return false;
6414         Add = true;
6415       }
6416       if (Add)
6417         ExtendNodes.push_back(User);
6418       continue;
6419     }
6420     // If truncates aren't free and there are users we can't
6421     // extend, it isn't worthwhile.
6422     if (!isTruncFree)
6423       return false;
6424     // Remember if this value is live-out.
6425     if (User->getOpcode() == ISD::CopyToReg)
6426       HasCopyToRegUses = true;
6427   }
6428 
6429   if (HasCopyToRegUses) {
6430     bool BothLiveOut = false;
6431     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6432          UI != UE; ++UI) {
6433       SDUse &Use = UI.getUse();
6434       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6435         BothLiveOut = true;
6436         break;
6437       }
6438     }
6439     if (BothLiveOut)
6440       // Both unextended and extended values are live out. There had better be
6441       // a good reason for the transformation.
6442       return ExtendNodes.size();
6443   }
6444   return true;
6445 }
6446 
6447 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6448                                   SDValue Trunc, SDValue ExtLoad,
6449                                   const SDLoc &DL, ISD::NodeType ExtType) {
6450   // Extend SetCC uses if necessary.
6451   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6452     SDNode *SetCC = SetCCs[i];
6453     SmallVector<SDValue, 4> Ops;
6454 
6455     for (unsigned j = 0; j != 2; ++j) {
6456       SDValue SOp = SetCC->getOperand(j);
6457       if (SOp == Trunc)
6458         Ops.push_back(ExtLoad);
6459       else
6460         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6461     }
6462 
6463     Ops.push_back(SetCC->getOperand(2));
6464     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6465   }
6466 }
6467 
6468 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6469 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6470   SDValue N0 = N->getOperand(0);
6471   EVT DstVT = N->getValueType(0);
6472   EVT SrcVT = N0.getValueType();
6473 
6474   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6475           N->getOpcode() == ISD::ZERO_EXTEND) &&
6476          "Unexpected node type (not an extend)!");
6477 
6478   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6479   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6480   //   (v8i32 (sext (v8i16 (load x))))
6481   // into:
6482   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6483   //                          (v4i32 (sextload (x + 16)))))
6484   // Where uses of the original load, i.e.:
6485   //   (v8i16 (load x))
6486   // are replaced with:
6487   //   (v8i16 (truncate
6488   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6489   //                            (v4i32 (sextload (x + 16)))))))
6490   //
6491   // This combine is only applicable to illegal, but splittable, vectors.
6492   // All legal types, and illegal non-vector types, are handled elsewhere.
6493   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6494   //
6495   if (N0->getOpcode() != ISD::LOAD)
6496     return SDValue();
6497 
6498   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6499 
6500   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6501       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6502       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6503     return SDValue();
6504 
6505   SmallVector<SDNode *, 4> SetCCs;
6506   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6507     return SDValue();
6508 
6509   ISD::LoadExtType ExtType =
6510       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6511 
6512   // Try to split the vector types to get down to legal types.
6513   EVT SplitSrcVT = SrcVT;
6514   EVT SplitDstVT = DstVT;
6515   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6516          SplitSrcVT.getVectorNumElements() > 1) {
6517     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6518     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6519   }
6520 
6521   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6522     return SDValue();
6523 
6524   SDLoc DL(N);
6525   const unsigned NumSplits =
6526       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6527   const unsigned Stride = SplitSrcVT.getStoreSize();
6528   SmallVector<SDValue, 4> Loads;
6529   SmallVector<SDValue, 4> Chains;
6530 
6531   SDValue BasePtr = LN0->getBasePtr();
6532   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6533     const unsigned Offset = Idx * Stride;
6534     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6535 
6536     SDValue SplitLoad = DAG.getExtLoad(
6537         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6538         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6539         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6540 
6541     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6542                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6543 
6544     Loads.push_back(SplitLoad.getValue(0));
6545     Chains.push_back(SplitLoad.getValue(1));
6546   }
6547 
6548   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6549   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6550 
6551   CombineTo(N, NewValue);
6552 
6553   // Replace uses of the original load (before extension)
6554   // with a truncate of the concatenated sextloaded vectors.
6555   SDValue Trunc =
6556       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6557   CombineTo(N0.getNode(), Trunc, NewChain);
6558   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6559                   (ISD::NodeType)N->getOpcode());
6560   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6561 }
6562 
6563 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6564   SDValue N0 = N->getOperand(0);
6565   EVT VT = N->getValueType(0);
6566 
6567   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6568                                               LegalOperations))
6569     return SDValue(Res, 0);
6570 
6571   // fold (sext (sext x)) -> (sext x)
6572   // fold (sext (aext x)) -> (sext x)
6573   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6574     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6575                        N0.getOperand(0));
6576 
6577   if (N0.getOpcode() == ISD::TRUNCATE) {
6578     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6579     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6580     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6581       SDNode *oye = N0.getOperand(0).getNode();
6582       if (NarrowLoad.getNode() != N0.getNode()) {
6583         CombineTo(N0.getNode(), NarrowLoad);
6584         // CombineTo deleted the truncate, if needed, but not what's under it.
6585         AddToWorklist(oye);
6586       }
6587       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6588     }
6589 
6590     // See if the value being truncated is already sign extended.  If so, just
6591     // eliminate the trunc/sext pair.
6592     SDValue Op = N0.getOperand(0);
6593     unsigned OpBits   = Op.getScalarValueSizeInBits();
6594     unsigned MidBits  = N0.getScalarValueSizeInBits();
6595     unsigned DestBits = VT.getScalarSizeInBits();
6596     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6597 
6598     if (OpBits == DestBits) {
6599       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6600       // bits, it is already ready.
6601       if (NumSignBits > DestBits-MidBits)
6602         return Op;
6603     } else if (OpBits < DestBits) {
6604       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6605       // bits, just sext from i32.
6606       if (NumSignBits > OpBits-MidBits)
6607         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6608     } else {
6609       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6610       // bits, just truncate to i32.
6611       if (NumSignBits > OpBits-MidBits)
6612         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6613     }
6614 
6615     // fold (sext (truncate x)) -> (sextinreg x).
6616     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6617                                                  N0.getValueType())) {
6618       if (OpBits < DestBits)
6619         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6620       else if (OpBits > DestBits)
6621         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6622       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6623                          DAG.getValueType(N0.getValueType()));
6624     }
6625   }
6626 
6627   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6628   // Only generate vector extloads when 1) they're legal, and 2) they are
6629   // deemed desirable by the target.
6630   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6631       ((!LegalOperations && !VT.isVector() &&
6632         !cast<LoadSDNode>(N0)->isVolatile()) ||
6633        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6634     bool DoXform = true;
6635     SmallVector<SDNode*, 4> SetCCs;
6636     if (!N0.hasOneUse())
6637       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6638     if (VT.isVector())
6639       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6640     if (DoXform) {
6641       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6642       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6643                                        LN0->getChain(),
6644                                        LN0->getBasePtr(), N0.getValueType(),
6645                                        LN0->getMemOperand());
6646       CombineTo(N, ExtLoad);
6647       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6648                                   N0.getValueType(), ExtLoad);
6649       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6650       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6651                       ISD::SIGN_EXTEND);
6652       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6653     }
6654   }
6655 
6656   // fold (sext (load x)) to multiple smaller sextloads.
6657   // Only on illegal but splittable vectors.
6658   if (SDValue ExtLoad = CombineExtLoad(N))
6659     return ExtLoad;
6660 
6661   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6662   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6663   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6664       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6665     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6666     EVT MemVT = LN0->getMemoryVT();
6667     if ((!LegalOperations && !LN0->isVolatile()) ||
6668         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6669       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6670                                        LN0->getChain(),
6671                                        LN0->getBasePtr(), MemVT,
6672                                        LN0->getMemOperand());
6673       CombineTo(N, ExtLoad);
6674       CombineTo(N0.getNode(),
6675                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6676                             N0.getValueType(), ExtLoad),
6677                 ExtLoad.getValue(1));
6678       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6679     }
6680   }
6681 
6682   // fold (sext (and/or/xor (load x), cst)) ->
6683   //      (and/or/xor (sextload x), (sext cst))
6684   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6685        N0.getOpcode() == ISD::XOR) &&
6686       isa<LoadSDNode>(N0.getOperand(0)) &&
6687       N0.getOperand(1).getOpcode() == ISD::Constant &&
6688       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6689       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6690     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6691     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6692       bool DoXform = true;
6693       SmallVector<SDNode*, 4> SetCCs;
6694       if (!N0.hasOneUse())
6695         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6696                                           SetCCs, TLI);
6697       if (DoXform) {
6698         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6699                                          LN0->getChain(), LN0->getBasePtr(),
6700                                          LN0->getMemoryVT(),
6701                                          LN0->getMemOperand());
6702         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6703         Mask = Mask.sext(VT.getSizeInBits());
6704         SDLoc DL(N);
6705         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6706                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6707         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6708                                     SDLoc(N0.getOperand(0)),
6709                                     N0.getOperand(0).getValueType(), ExtLoad);
6710         CombineTo(N, And);
6711         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6712         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6713                         ISD::SIGN_EXTEND);
6714         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6715       }
6716     }
6717   }
6718 
6719   if (N0.getOpcode() == ISD::SETCC) {
6720     EVT N0VT = N0.getOperand(0).getValueType();
6721     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6722     // Only do this before legalize for now.
6723     if (VT.isVector() && !LegalOperations &&
6724         TLI.getBooleanContents(N0VT) ==
6725             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6726       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6727       // of the same size as the compared operands. Only optimize sext(setcc())
6728       // if this is the case.
6729       EVT SVT = getSetCCResultType(N0VT);
6730 
6731       // We know that the # elements of the results is the same as the
6732       // # elements of the compare (and the # elements of the compare result
6733       // for that matter).  Check to see that they are the same size.  If so,
6734       // we know that the element size of the sext'd result matches the
6735       // element size of the compare operands.
6736       if (VT.getSizeInBits() == SVT.getSizeInBits())
6737         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6738                              N0.getOperand(1),
6739                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6740 
6741       // If the desired elements are smaller or larger than the source
6742       // elements we can use a matching integer vector type and then
6743       // truncate/sign extend
6744       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6745       if (SVT == MatchingVectorType) {
6746         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6747                                N0.getOperand(0), N0.getOperand(1),
6748                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6749         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6750       }
6751     }
6752 
6753     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6754     // Here, T can be 1 or -1, depending on the type of the setcc and
6755     // getBooleanContents().
6756     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
6757 
6758     SDLoc DL(N);
6759     // To determine the "true" side of the select, we need to know the high bit
6760     // of the value returned by the setcc if it evaluates to true.
6761     // If the type of the setcc is i1, then the true case of the select is just
6762     // sext(i1 1), that is, -1.
6763     // If the type of the setcc is larger (say, i8) then the value of the high
6764     // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6765     // of the appropriate width.
6766     SDValue ExtTrueVal =
6767         (SetCCWidth == 1)
6768             ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6769                               DL, VT)
6770             : TLI.getConstTrueVal(DAG, VT, DL);
6771 
6772     if (SDValue SCC = SimplifySelectCC(
6773             DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6774             DAG.getConstant(0, DL, VT),
6775             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6776       return SCC;
6777 
6778     if (!VT.isVector()) {
6779       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6780       if (!LegalOperations ||
6781           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6782         SDLoc DL(N);
6783         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6784         SDValue SetCC =
6785             DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6786         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6787                              DAG.getConstant(0, DL, VT));
6788       }
6789     }
6790   }
6791 
6792   // fold (sext x) -> (zext x) if the sign bit is known zero.
6793   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6794       DAG.SignBitIsZero(N0))
6795     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6796 
6797   return SDValue();
6798 }
6799 
6800 // isTruncateOf - If N is a truncate of some other value, return true, record
6801 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6802 // This function computes KnownZero to avoid a duplicated call to
6803 // computeKnownBits in the caller.
6804 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6805                          APInt &KnownZero) {
6806   APInt KnownOne;
6807   if (N->getOpcode() == ISD::TRUNCATE) {
6808     Op = N->getOperand(0);
6809     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6810     return true;
6811   }
6812 
6813   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6814       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6815     return false;
6816 
6817   SDValue Op0 = N->getOperand(0);
6818   SDValue Op1 = N->getOperand(1);
6819   assert(Op0.getValueType() == Op1.getValueType());
6820 
6821   if (isNullConstant(Op0))
6822     Op = Op1;
6823   else if (isNullConstant(Op1))
6824     Op = Op0;
6825   else
6826     return false;
6827 
6828   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6829 
6830   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6831     return false;
6832 
6833   return true;
6834 }
6835 
6836 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6837   SDValue N0 = N->getOperand(0);
6838   EVT VT = N->getValueType(0);
6839 
6840   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6841                                               LegalOperations))
6842     return SDValue(Res, 0);
6843 
6844   // fold (zext (zext x)) -> (zext x)
6845   // fold (zext (aext x)) -> (zext x)
6846   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6847     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6848                        N0.getOperand(0));
6849 
6850   // fold (zext (truncate x)) -> (zext x) or
6851   //      (zext (truncate x)) -> (truncate x)
6852   // This is valid when the truncated bits of x are already zero.
6853   // FIXME: We should extend this to work for vectors too.
6854   SDValue Op;
6855   APInt KnownZero;
6856   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6857     APInt TruncatedBits =
6858       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6859       APInt(Op.getValueSizeInBits(), 0) :
6860       APInt::getBitsSet(Op.getValueSizeInBits(),
6861                         N0.getValueSizeInBits(),
6862                         std::min(Op.getValueSizeInBits(),
6863                                  VT.getSizeInBits()));
6864     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6865       if (VT.bitsGT(Op.getValueType()))
6866         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6867       if (VT.bitsLT(Op.getValueType()))
6868         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6869 
6870       return Op;
6871     }
6872   }
6873 
6874   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6875   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6876   if (N0.getOpcode() == ISD::TRUNCATE) {
6877     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6878       SDNode *oye = N0.getOperand(0).getNode();
6879       if (NarrowLoad.getNode() != N0.getNode()) {
6880         CombineTo(N0.getNode(), NarrowLoad);
6881         // CombineTo deleted the truncate, if needed, but not what's under it.
6882         AddToWorklist(oye);
6883       }
6884       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6885     }
6886   }
6887 
6888   // fold (zext (truncate x)) -> (and x, mask)
6889   if (N0.getOpcode() == ISD::TRUNCATE) {
6890     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6891     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6892     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6893       SDNode *oye = N0.getOperand(0).getNode();
6894       if (NarrowLoad.getNode() != N0.getNode()) {
6895         CombineTo(N0.getNode(), NarrowLoad);
6896         // CombineTo deleted the truncate, if needed, but not what's under it.
6897         AddToWorklist(oye);
6898       }
6899       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6900     }
6901 
6902     EVT SrcVT = N0.getOperand(0).getValueType();
6903     EVT MinVT = N0.getValueType();
6904 
6905     // Try to mask before the extension to avoid having to generate a larger mask,
6906     // possibly over several sub-vectors.
6907     if (SrcVT.bitsLT(VT)) {
6908       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6909                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6910         SDValue Op = N0.getOperand(0);
6911         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6912         AddToWorklist(Op.getNode());
6913         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6914       }
6915     }
6916 
6917     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6918       SDValue Op = N0.getOperand(0);
6919       if (SrcVT.bitsLT(VT)) {
6920         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6921         AddToWorklist(Op.getNode());
6922       } else if (SrcVT.bitsGT(VT)) {
6923         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6924         AddToWorklist(Op.getNode());
6925       }
6926       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6927     }
6928   }
6929 
6930   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6931   // if either of the casts is not free.
6932   if (N0.getOpcode() == ISD::AND &&
6933       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6934       N0.getOperand(1).getOpcode() == ISD::Constant &&
6935       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6936                            N0.getValueType()) ||
6937        !TLI.isZExtFree(N0.getValueType(), VT))) {
6938     SDValue X = N0.getOperand(0).getOperand(0);
6939     if (X.getValueType().bitsLT(VT)) {
6940       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6941     } else if (X.getValueType().bitsGT(VT)) {
6942       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6943     }
6944     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6945     Mask = Mask.zext(VT.getSizeInBits());
6946     SDLoc DL(N);
6947     return DAG.getNode(ISD::AND, DL, VT,
6948                        X, DAG.getConstant(Mask, DL, VT));
6949   }
6950 
6951   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6952   // Only generate vector extloads when 1) they're legal, and 2) they are
6953   // deemed desirable by the target.
6954   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6955       ((!LegalOperations && !VT.isVector() &&
6956         !cast<LoadSDNode>(N0)->isVolatile()) ||
6957        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6958     bool DoXform = true;
6959     SmallVector<SDNode*, 4> SetCCs;
6960     if (!N0.hasOneUse())
6961       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6962     if (VT.isVector())
6963       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6964     if (DoXform) {
6965       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6966       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6967                                        LN0->getChain(),
6968                                        LN0->getBasePtr(), N0.getValueType(),
6969                                        LN0->getMemOperand());
6970       CombineTo(N, ExtLoad);
6971       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6972                                   N0.getValueType(), ExtLoad);
6973       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6974 
6975       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6976                       ISD::ZERO_EXTEND);
6977       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6978     }
6979   }
6980 
6981   // fold (zext (load x)) to multiple smaller zextloads.
6982   // Only on illegal but splittable vectors.
6983   if (SDValue ExtLoad = CombineExtLoad(N))
6984     return ExtLoad;
6985 
6986   // fold (zext (and/or/xor (load x), cst)) ->
6987   //      (and/or/xor (zextload x), (zext cst))
6988   // Unless (and (load x) cst) will match as a zextload already and has
6989   // additional users.
6990   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6991        N0.getOpcode() == ISD::XOR) &&
6992       isa<LoadSDNode>(N0.getOperand(0)) &&
6993       N0.getOperand(1).getOpcode() == ISD::Constant &&
6994       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6995       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6996     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6997     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6998       bool DoXform = true;
6999       SmallVector<SDNode*, 4> SetCCs;
7000       if (!N0.hasOneUse()) {
7001         if (N0.getOpcode() == ISD::AND) {
7002           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7003           auto NarrowLoad = false;
7004           EVT LoadResultTy = AndC->getValueType(0);
7005           EVT ExtVT, LoadedVT;
7006           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7007                                NarrowLoad))
7008             DoXform = false;
7009         }
7010         if (DoXform)
7011           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7012                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7013       }
7014       if (DoXform) {
7015         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7016                                          LN0->getChain(), LN0->getBasePtr(),
7017                                          LN0->getMemoryVT(),
7018                                          LN0->getMemOperand());
7019         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7020         Mask = Mask.zext(VT.getSizeInBits());
7021         SDLoc DL(N);
7022         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7023                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7024         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7025                                     SDLoc(N0.getOperand(0)),
7026                                     N0.getOperand(0).getValueType(), ExtLoad);
7027         CombineTo(N, And);
7028         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7029         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
7030                         ISD::ZERO_EXTEND);
7031         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7032       }
7033     }
7034   }
7035 
7036   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7037   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7038   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7039       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7040     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7041     EVT MemVT = LN0->getMemoryVT();
7042     if ((!LegalOperations && !LN0->isVolatile()) ||
7043         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7044       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7045                                        LN0->getChain(),
7046                                        LN0->getBasePtr(), MemVT,
7047                                        LN0->getMemOperand());
7048       CombineTo(N, ExtLoad);
7049       CombineTo(N0.getNode(),
7050                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7051                             ExtLoad),
7052                 ExtLoad.getValue(1));
7053       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7054     }
7055   }
7056 
7057   if (N0.getOpcode() == ISD::SETCC) {
7058     // Only do this before legalize for now.
7059     if (!LegalOperations && VT.isVector() &&
7060         N0.getValueType().getVectorElementType() == MVT::i1) {
7061       EVT N00VT = N0.getOperand(0).getValueType();
7062       if (getSetCCResultType(N00VT) == N0.getValueType())
7063         return SDValue();
7064 
7065       // We know that the # elements of the results is the same as the #
7066       // elements of the compare (and the # elements of the compare result for
7067       // that matter). Check to see that they are the same size. If so, we know
7068       // that the element size of the sext'd result matches the element size of
7069       // the compare operands.
7070       SDLoc DL(N);
7071       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7072       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7073         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7074         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7075                                      N0.getOperand(1), N0.getOperand(2));
7076         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7077       }
7078 
7079       // If the desired elements are smaller or larger than the source
7080       // elements we can use a matching integer vector type and then
7081       // truncate/sign extend.
7082       EVT MatchingElementType = EVT::getIntegerVT(
7083           *DAG.getContext(), N00VT.getScalarSizeInBits());
7084       EVT MatchingVectorType = EVT::getVectorVT(
7085           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7086       SDValue VsetCC =
7087           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7088                       N0.getOperand(1), N0.getOperand(2));
7089       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7090                          VecOnes);
7091     }
7092 
7093     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7094     SDLoc DL(N);
7095     if (SDValue SCC = SimplifySelectCC(
7096             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7097             DAG.getConstant(0, DL, VT),
7098             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7099       return SCC;
7100   }
7101 
7102   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7103   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7104       isa<ConstantSDNode>(N0.getOperand(1)) &&
7105       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7106       N0.hasOneUse()) {
7107     SDValue ShAmt = N0.getOperand(1);
7108     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7109     if (N0.getOpcode() == ISD::SHL) {
7110       SDValue InnerZExt = N0.getOperand(0);
7111       // If the original shl may be shifting out bits, do not perform this
7112       // transformation.
7113       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7114         InnerZExt.getOperand(0).getValueSizeInBits();
7115       if (ShAmtVal > KnownZeroBits)
7116         return SDValue();
7117     }
7118 
7119     SDLoc DL(N);
7120 
7121     // Ensure that the shift amount is wide enough for the shifted value.
7122     if (VT.getSizeInBits() >= 256)
7123       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7124 
7125     return DAG.getNode(N0.getOpcode(), DL, VT,
7126                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7127                        ShAmt);
7128   }
7129 
7130   return SDValue();
7131 }
7132 
7133 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7134   SDValue N0 = N->getOperand(0);
7135   EVT VT = N->getValueType(0);
7136 
7137   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7138                                               LegalOperations))
7139     return SDValue(Res, 0);
7140 
7141   // fold (aext (aext x)) -> (aext x)
7142   // fold (aext (zext x)) -> (zext x)
7143   // fold (aext (sext x)) -> (sext x)
7144   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7145       N0.getOpcode() == ISD::ZERO_EXTEND ||
7146       N0.getOpcode() == ISD::SIGN_EXTEND)
7147     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7148 
7149   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7150   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7151   if (N0.getOpcode() == ISD::TRUNCATE) {
7152     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7153       SDNode *oye = N0.getOperand(0).getNode();
7154       if (NarrowLoad.getNode() != N0.getNode()) {
7155         CombineTo(N0.getNode(), NarrowLoad);
7156         // CombineTo deleted the truncate, if needed, but not what's under it.
7157         AddToWorklist(oye);
7158       }
7159       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7160     }
7161   }
7162 
7163   // fold (aext (truncate x))
7164   if (N0.getOpcode() == ISD::TRUNCATE) {
7165     SDValue TruncOp = N0.getOperand(0);
7166     if (TruncOp.getValueType() == VT)
7167       return TruncOp; // x iff x size == zext size.
7168     if (TruncOp.getValueType().bitsGT(VT))
7169       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
7170     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
7171   }
7172 
7173   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7174   // if the trunc is not free.
7175   if (N0.getOpcode() == ISD::AND &&
7176       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7177       N0.getOperand(1).getOpcode() == ISD::Constant &&
7178       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7179                           N0.getValueType())) {
7180     SDLoc DL(N);
7181     SDValue X = N0.getOperand(0).getOperand(0);
7182     if (X.getValueType().bitsLT(VT)) {
7183       X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
7184     } else if (X.getValueType().bitsGT(VT)) {
7185       X = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
7186     }
7187     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7188     Mask = Mask.zext(VT.getSizeInBits());
7189     return DAG.getNode(ISD::AND, DL, VT,
7190                        X, DAG.getConstant(Mask, DL, VT));
7191   }
7192 
7193   // fold (aext (load x)) -> (aext (truncate (extload x)))
7194   // None of the supported targets knows how to perform load and any_ext
7195   // on vectors in one instruction.  We only perform this transformation on
7196   // scalars.
7197   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7198       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7199       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7200     bool DoXform = true;
7201     SmallVector<SDNode*, 4> SetCCs;
7202     if (!N0.hasOneUse())
7203       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7204     if (DoXform) {
7205       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7206       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7207                                        LN0->getChain(),
7208                                        LN0->getBasePtr(), N0.getValueType(),
7209                                        LN0->getMemOperand());
7210       CombineTo(N, ExtLoad);
7211       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7212                                   N0.getValueType(), ExtLoad);
7213       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7214       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7215                       ISD::ANY_EXTEND);
7216       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7217     }
7218   }
7219 
7220   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7221   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7222   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7223   if (N0.getOpcode() == ISD::LOAD &&
7224       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7225       N0.hasOneUse()) {
7226     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7227     ISD::LoadExtType ExtType = LN0->getExtensionType();
7228     EVT MemVT = LN0->getMemoryVT();
7229     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7230       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7231                                        VT, LN0->getChain(), LN0->getBasePtr(),
7232                                        MemVT, LN0->getMemOperand());
7233       CombineTo(N, ExtLoad);
7234       CombineTo(N0.getNode(),
7235                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7236                             N0.getValueType(), ExtLoad),
7237                 ExtLoad.getValue(1));
7238       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7239     }
7240   }
7241 
7242   if (N0.getOpcode() == ISD::SETCC) {
7243     // For vectors:
7244     // aext(setcc) -> vsetcc
7245     // aext(setcc) -> truncate(vsetcc)
7246     // aext(setcc) -> aext(vsetcc)
7247     // Only do this before legalize for now.
7248     if (VT.isVector() && !LegalOperations) {
7249       EVT N0VT = N0.getOperand(0).getValueType();
7250         // We know that the # elements of the results is the same as the
7251         // # elements of the compare (and the # elements of the compare result
7252         // for that matter).  Check to see that they are the same size.  If so,
7253         // we know that the element size of the sext'd result matches the
7254         // element size of the compare operands.
7255       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7256         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7257                              N0.getOperand(1),
7258                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7259       // If the desired elements are smaller or larger than the source
7260       // elements we can use a matching integer vector type and then
7261       // truncate/any extend
7262       else {
7263         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7264         SDValue VsetCC =
7265           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7266                         N0.getOperand(1),
7267                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7268         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7269       }
7270     }
7271 
7272     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7273     SDLoc DL(N);
7274     if (SDValue SCC = SimplifySelectCC(
7275             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7276             DAG.getConstant(0, DL, VT),
7277             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7278       return SCC;
7279   }
7280 
7281   return SDValue();
7282 }
7283 
7284 /// See if the specified operand can be simplified with the knowledge that only
7285 /// the bits specified by Mask are used.  If so, return the simpler operand,
7286 /// otherwise return a null SDValue.
7287 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7288   switch (V.getOpcode()) {
7289   default: break;
7290   case ISD::Constant: {
7291     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7292     assert(CV && "Const value should be ConstSDNode.");
7293     const APInt &CVal = CV->getAPIntValue();
7294     APInt NewVal = CVal & Mask;
7295     if (NewVal != CVal)
7296       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7297     break;
7298   }
7299   case ISD::OR:
7300   case ISD::XOR:
7301     // If the LHS or RHS don't contribute bits to the or, drop them.
7302     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7303       return V.getOperand(1);
7304     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7305       return V.getOperand(0);
7306     break;
7307   case ISD::SRL:
7308     // Only look at single-use SRLs.
7309     if (!V.getNode()->hasOneUse())
7310       break;
7311     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7312       // See if we can recursively simplify the LHS.
7313       unsigned Amt = RHSC->getZExtValue();
7314 
7315       // Watch out for shift count overflow though.
7316       if (Amt >= Mask.getBitWidth()) break;
7317       APInt NewMask = Mask << Amt;
7318       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7319         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7320                            SimplifyLHS, V.getOperand(1));
7321     }
7322   }
7323   return SDValue();
7324 }
7325 
7326 /// If the result of a wider load is shifted to right of N  bits and then
7327 /// truncated to a narrower type and where N is a multiple of number of bits of
7328 /// the narrower type, transform it to a narrower load from address + N / num of
7329 /// bits of new type. If the result is to be extended, also fold the extension
7330 /// to form a extending load.
7331 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7332   unsigned Opc = N->getOpcode();
7333 
7334   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7335   SDValue N0 = N->getOperand(0);
7336   EVT VT = N->getValueType(0);
7337   EVT ExtVT = VT;
7338 
7339   // This transformation isn't valid for vector loads.
7340   if (VT.isVector())
7341     return SDValue();
7342 
7343   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7344   // extended to VT.
7345   if (Opc == ISD::SIGN_EXTEND_INREG) {
7346     ExtType = ISD::SEXTLOAD;
7347     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7348   } else if (Opc == ISD::SRL) {
7349     // Another special-case: SRL is basically zero-extending a narrower value.
7350     ExtType = ISD::ZEXTLOAD;
7351     N0 = SDValue(N, 0);
7352     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7353     if (!N01) return SDValue();
7354     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7355                               VT.getSizeInBits() - N01->getZExtValue());
7356   }
7357   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7358     return SDValue();
7359 
7360   unsigned EVTBits = ExtVT.getSizeInBits();
7361 
7362   // Do not generate loads of non-round integer types since these can
7363   // be expensive (and would be wrong if the type is not byte sized).
7364   if (!ExtVT.isRound())
7365     return SDValue();
7366 
7367   unsigned ShAmt = 0;
7368   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7369     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7370       ShAmt = N01->getZExtValue();
7371       // Is the shift amount a multiple of size of VT?
7372       if ((ShAmt & (EVTBits-1)) == 0) {
7373         N0 = N0.getOperand(0);
7374         // Is the load width a multiple of size of VT?
7375         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7376           return SDValue();
7377       }
7378 
7379       // At this point, we must have a load or else we can't do the transform.
7380       if (!isa<LoadSDNode>(N0)) return SDValue();
7381 
7382       // Because a SRL must be assumed to *need* to zero-extend the high bits
7383       // (as opposed to anyext the high bits), we can't combine the zextload
7384       // lowering of SRL and an sextload.
7385       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7386         return SDValue();
7387 
7388       // If the shift amount is larger than the input type then we're not
7389       // accessing any of the loaded bytes.  If the load was a zextload/extload
7390       // then the result of the shift+trunc is zero/undef (handled elsewhere).
7391       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7392         return SDValue();
7393     }
7394   }
7395 
7396   // If the load is shifted left (and the result isn't shifted back right),
7397   // we can fold the truncate through the shift.
7398   unsigned ShLeftAmt = 0;
7399   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7400       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7401     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7402       ShLeftAmt = N01->getZExtValue();
7403       N0 = N0.getOperand(0);
7404     }
7405   }
7406 
7407   // If we haven't found a load, we can't narrow it.  Don't transform one with
7408   // multiple uses, this would require adding a new load.
7409   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7410     return SDValue();
7411 
7412   // Don't change the width of a volatile load.
7413   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7414   if (LN0->isVolatile())
7415     return SDValue();
7416 
7417   // Verify that we are actually reducing a load width here.
7418   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7419     return SDValue();
7420 
7421   // For the transform to be legal, the load must produce only two values
7422   // (the value loaded and the chain).  Don't transform a pre-increment
7423   // load, for example, which produces an extra value.  Otherwise the
7424   // transformation is not equivalent, and the downstream logic to replace
7425   // uses gets things wrong.
7426   if (LN0->getNumValues() > 2)
7427     return SDValue();
7428 
7429   // If the load that we're shrinking is an extload and we're not just
7430   // discarding the extension we can't simply shrink the load. Bail.
7431   // TODO: It would be possible to merge the extensions in some cases.
7432   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7433       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7434     return SDValue();
7435 
7436   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7437     return SDValue();
7438 
7439   EVT PtrType = N0.getOperand(1).getValueType();
7440 
7441   if (PtrType == MVT::Untyped || PtrType.isExtended())
7442     // It's not possible to generate a constant of extended or untyped type.
7443     return SDValue();
7444 
7445   // For big endian targets, we need to adjust the offset to the pointer to
7446   // load the correct bytes.
7447   if (DAG.getDataLayout().isBigEndian()) {
7448     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7449     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7450     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7451   }
7452 
7453   uint64_t PtrOff = ShAmt / 8;
7454   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7455   SDLoc DL(LN0);
7456   // The original load itself didn't wrap, so an offset within it doesn't.
7457   SDNodeFlags Flags;
7458   Flags.setNoUnsignedWrap(true);
7459   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7460                                PtrType, LN0->getBasePtr(),
7461                                DAG.getConstant(PtrOff, DL, PtrType),
7462                                &Flags);
7463   AddToWorklist(NewPtr.getNode());
7464 
7465   SDValue Load;
7466   if (ExtType == ISD::NON_EXTLOAD)
7467     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7468                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7469                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7470   else
7471     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7472                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7473                           NewAlign, LN0->getMemOperand()->getFlags(),
7474                           LN0->getAAInfo());
7475 
7476   // Replace the old load's chain with the new load's chain.
7477   WorklistRemover DeadNodes(*this);
7478   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7479 
7480   // Shift the result left, if we've swallowed a left shift.
7481   SDValue Result = Load;
7482   if (ShLeftAmt != 0) {
7483     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7484     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7485       ShImmTy = VT;
7486     // If the shift amount is as large as the result size (but, presumably,
7487     // no larger than the source) then the useful bits of the result are
7488     // zero; we can't simply return the shortened shift, because the result
7489     // of that operation is undefined.
7490     SDLoc DL(N0);
7491     if (ShLeftAmt >= VT.getSizeInBits())
7492       Result = DAG.getConstant(0, DL, VT);
7493     else
7494       Result = DAG.getNode(ISD::SHL, DL, VT,
7495                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7496   }
7497 
7498   // Return the new loaded value.
7499   return Result;
7500 }
7501 
7502 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7503   SDValue N0 = N->getOperand(0);
7504   SDValue N1 = N->getOperand(1);
7505   EVT VT = N->getValueType(0);
7506   EVT EVT = cast<VTSDNode>(N1)->getVT();
7507   unsigned VTBits = VT.getScalarSizeInBits();
7508   unsigned EVTBits = EVT.getScalarSizeInBits();
7509 
7510   if (N0.isUndef())
7511     return DAG.getUNDEF(VT);
7512 
7513   // fold (sext_in_reg c1) -> c1
7514   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7515     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7516 
7517   // If the input is already sign extended, just drop the extension.
7518   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7519     return N0;
7520 
7521   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7522   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7523       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7524     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7525                        N0.getOperand(0), N1);
7526 
7527   // fold (sext_in_reg (sext x)) -> (sext x)
7528   // fold (sext_in_reg (aext x)) -> (sext x)
7529   // if x is small enough.
7530   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7531     SDValue N00 = N0.getOperand(0);
7532     if (N00.getScalarValueSizeInBits() <= EVTBits &&
7533         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7534       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7535   }
7536 
7537   // fold (sext_in_reg (zext x)) -> (sext x)
7538   // iff we are extending the source sign bit.
7539   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
7540     SDValue N00 = N0.getOperand(0);
7541     if (N00.getScalarValueSizeInBits() == EVTBits &&
7542         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7543       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7544   }
7545 
7546   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7547   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7548     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7549 
7550   // fold operands of sext_in_reg based on knowledge that the top bits are not
7551   // demanded.
7552   if (SimplifyDemandedBits(SDValue(N, 0)))
7553     return SDValue(N, 0);
7554 
7555   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7556   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7557   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7558     return NarrowLoad;
7559 
7560   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7561   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7562   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7563   if (N0.getOpcode() == ISD::SRL) {
7564     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7565       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7566         // We can turn this into an SRA iff the input to the SRL is already sign
7567         // extended enough.
7568         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7569         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7570           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7571                              N0.getOperand(0), N0.getOperand(1));
7572       }
7573   }
7574 
7575   // fold (sext_inreg (extload x)) -> (sextload x)
7576   if (ISD::isEXTLoad(N0.getNode()) &&
7577       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7578       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7579       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7580        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7581     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7582     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7583                                      LN0->getChain(),
7584                                      LN0->getBasePtr(), EVT,
7585                                      LN0->getMemOperand());
7586     CombineTo(N, ExtLoad);
7587     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7588     AddToWorklist(ExtLoad.getNode());
7589     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7590   }
7591   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7592   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7593       N0.hasOneUse() &&
7594       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7595       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7596        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7597     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7598     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7599                                      LN0->getChain(),
7600                                      LN0->getBasePtr(), EVT,
7601                                      LN0->getMemOperand());
7602     CombineTo(N, ExtLoad);
7603     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7604     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7605   }
7606 
7607   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7608   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7609     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7610                                            N0.getOperand(1), false))
7611       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7612                          BSwap, N1);
7613   }
7614 
7615   return SDValue();
7616 }
7617 
7618 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7619   SDValue N0 = N->getOperand(0);
7620   EVT VT = N->getValueType(0);
7621 
7622   if (N0.isUndef())
7623     return DAG.getUNDEF(VT);
7624 
7625   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7626                                               LegalOperations))
7627     return SDValue(Res, 0);
7628 
7629   return SDValue();
7630 }
7631 
7632 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7633   SDValue N0 = N->getOperand(0);
7634   EVT VT = N->getValueType(0);
7635 
7636   if (N0.isUndef())
7637     return DAG.getUNDEF(VT);
7638 
7639   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7640                                               LegalOperations))
7641     return SDValue(Res, 0);
7642 
7643   return SDValue();
7644 }
7645 
7646 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7647   SDValue N0 = N->getOperand(0);
7648   EVT VT = N->getValueType(0);
7649   bool isLE = DAG.getDataLayout().isLittleEndian();
7650 
7651   // noop truncate
7652   if (N0.getValueType() == N->getValueType(0))
7653     return N0;
7654   // fold (truncate c1) -> c1
7655   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7656     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7657   // fold (truncate (truncate x)) -> (truncate x)
7658   if (N0.getOpcode() == ISD::TRUNCATE)
7659     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7660   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7661   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7662       N0.getOpcode() == ISD::SIGN_EXTEND ||
7663       N0.getOpcode() == ISD::ANY_EXTEND) {
7664     // if the source is smaller than the dest, we still need an extend.
7665     if (N0.getOperand(0).getValueType().bitsLT(VT))
7666       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7667     // if the source is larger than the dest, than we just need the truncate.
7668     if (N0.getOperand(0).getValueType().bitsGT(VT))
7669       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7670     // if the source and dest are the same type, we can drop both the extend
7671     // and the truncate.
7672     return N0.getOperand(0);
7673   }
7674 
7675   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
7676   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
7677     return SDValue();
7678 
7679   // Fold extract-and-trunc into a narrow extract. For example:
7680   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7681   //   i32 y = TRUNCATE(i64 x)
7682   //        -- becomes --
7683   //   v16i8 b = BITCAST (v2i64 val)
7684   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7685   //
7686   // Note: We only run this optimization after type legalization (which often
7687   // creates this pattern) and before operation legalization after which
7688   // we need to be more careful about the vector instructions that we generate.
7689   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7690       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7691 
7692     EVT VecTy = N0.getOperand(0).getValueType();
7693     EVT ExTy = N0.getValueType();
7694     EVT TrTy = N->getValueType(0);
7695 
7696     unsigned NumElem = VecTy.getVectorNumElements();
7697     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7698 
7699     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7700     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7701 
7702     SDValue EltNo = N0->getOperand(1);
7703     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7704       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7705       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7706       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7707 
7708       SDLoc DL(N);
7709       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7710                          DAG.getBitcast(NVT, N0.getOperand(0)),
7711                          DAG.getConstant(Index, DL, IndexTy));
7712     }
7713   }
7714 
7715   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7716   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
7717     EVT SrcVT = N0.getValueType();
7718     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7719         TLI.isTruncateFree(SrcVT, VT)) {
7720       SDLoc SL(N0);
7721       SDValue Cond = N0.getOperand(0);
7722       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7723       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7724       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7725     }
7726   }
7727 
7728   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
7729   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7730       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7731       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7732     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7733       uint64_t Amt = CAmt->getZExtValue();
7734       unsigned Size = VT.getScalarSizeInBits();
7735 
7736       if (Amt < Size) {
7737         SDLoc SL(N);
7738         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7739 
7740         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7741         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7742                            DAG.getConstant(Amt, SL, AmtVT));
7743       }
7744     }
7745   }
7746 
7747   // Fold a series of buildvector, bitcast, and truncate if possible.
7748   // For example fold
7749   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7750   //   (2xi32 (buildvector x, y)).
7751   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7752       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7753       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7754       N0.getOperand(0).hasOneUse()) {
7755 
7756     SDValue BuildVect = N0.getOperand(0);
7757     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7758     EVT TruncVecEltTy = VT.getVectorElementType();
7759 
7760     // Check that the element types match.
7761     if (BuildVectEltTy == TruncVecEltTy) {
7762       // Now we only need to compute the offset of the truncated elements.
7763       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7764       unsigned TruncVecNumElts = VT.getVectorNumElements();
7765       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7766 
7767       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7768              "Invalid number of elements");
7769 
7770       SmallVector<SDValue, 8> Opnds;
7771       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7772         Opnds.push_back(BuildVect.getOperand(i));
7773 
7774       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7775     }
7776   }
7777 
7778   // See if we can simplify the input to this truncate through knowledge that
7779   // only the low bits are being used.
7780   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7781   // Currently we only perform this optimization on scalars because vectors
7782   // may have different active low bits.
7783   if (!VT.isVector()) {
7784     if (SDValue Shorter =
7785             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7786                                                      VT.getSizeInBits())))
7787       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7788   }
7789 
7790   // fold (truncate (load x)) -> (smaller load x)
7791   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7792   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7793     if (SDValue Reduced = ReduceLoadWidth(N))
7794       return Reduced;
7795 
7796     // Handle the case where the load remains an extending load even
7797     // after truncation.
7798     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7799       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7800       if (!LN0->isVolatile() &&
7801           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7802         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7803                                          VT, LN0->getChain(), LN0->getBasePtr(),
7804                                          LN0->getMemoryVT(),
7805                                          LN0->getMemOperand());
7806         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7807         return NewLoad;
7808       }
7809     }
7810   }
7811 
7812   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7813   // where ... are all 'undef'.
7814   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7815     SmallVector<EVT, 8> VTs;
7816     SDValue V;
7817     unsigned Idx = 0;
7818     unsigned NumDefs = 0;
7819 
7820     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7821       SDValue X = N0.getOperand(i);
7822       if (!X.isUndef()) {
7823         V = X;
7824         Idx = i;
7825         NumDefs++;
7826       }
7827       // Stop if more than one members are non-undef.
7828       if (NumDefs > 1)
7829         break;
7830       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7831                                      VT.getVectorElementType(),
7832                                      X.getValueType().getVectorNumElements()));
7833     }
7834 
7835     if (NumDefs == 0)
7836       return DAG.getUNDEF(VT);
7837 
7838     if (NumDefs == 1) {
7839       assert(V.getNode() && "The single defined operand is empty!");
7840       SmallVector<SDValue, 8> Opnds;
7841       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7842         if (i != Idx) {
7843           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7844           continue;
7845         }
7846         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7847         AddToWorklist(NV.getNode());
7848         Opnds.push_back(NV);
7849       }
7850       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7851     }
7852   }
7853 
7854   // Fold truncate of a bitcast of a vector to an extract of the low vector
7855   // element.
7856   //
7857   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7858   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7859     SDValue VecSrc = N0.getOperand(0);
7860     EVT SrcVT = VecSrc.getValueType();
7861     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7862         (!LegalOperations ||
7863          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7864       SDLoc SL(N);
7865 
7866       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7867       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7868                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7869     }
7870   }
7871 
7872   // Simplify the operands using demanded-bits information.
7873   if (!VT.isVector() &&
7874       SimplifyDemandedBits(SDValue(N, 0)))
7875     return SDValue(N, 0);
7876 
7877   return SDValue();
7878 }
7879 
7880 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7881   SDValue Elt = N->getOperand(i);
7882   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7883     return Elt.getNode();
7884   return Elt.getOperand(Elt.getResNo()).getNode();
7885 }
7886 
7887 /// build_pair (load, load) -> load
7888 /// if load locations are consecutive.
7889 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7890   assert(N->getOpcode() == ISD::BUILD_PAIR);
7891 
7892   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7893   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7894   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7895       LD1->getAddressSpace() != LD2->getAddressSpace())
7896     return SDValue();
7897   EVT LD1VT = LD1->getValueType(0);
7898   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7899   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7900       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7901     unsigned Align = LD1->getAlignment();
7902     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7903         VT.getTypeForEVT(*DAG.getContext()));
7904 
7905     if (NewAlign <= Align &&
7906         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7907       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
7908                          LD1->getPointerInfo(), Align);
7909   }
7910 
7911   return SDValue();
7912 }
7913 
7914 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7915   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7916   // and Lo parts; on big-endian machines it doesn't.
7917   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7918 }
7919 
7920 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7921                                     const TargetLowering &TLI) {
7922   // If this is not a bitcast to an FP type or if the target doesn't have
7923   // IEEE754-compliant FP logic, we're done.
7924   EVT VT = N->getValueType(0);
7925   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7926     return SDValue();
7927 
7928   // TODO: Use splat values for the constant-checking below and remove this
7929   // restriction.
7930   SDValue N0 = N->getOperand(0);
7931   EVT SourceVT = N0.getValueType();
7932   if (SourceVT.isVector())
7933     return SDValue();
7934 
7935   unsigned FPOpcode;
7936   APInt SignMask;
7937   switch (N0.getOpcode()) {
7938   case ISD::AND:
7939     FPOpcode = ISD::FABS;
7940     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7941     break;
7942   case ISD::XOR:
7943     FPOpcode = ISD::FNEG;
7944     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7945     break;
7946   // TODO: ISD::OR --> ISD::FNABS?
7947   default:
7948     return SDValue();
7949   }
7950 
7951   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7952   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7953   SDValue LogicOp0 = N0.getOperand(0);
7954   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7955   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7956       LogicOp0.getOpcode() == ISD::BITCAST &&
7957       LogicOp0->getOperand(0).getValueType() == VT)
7958     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7959 
7960   return SDValue();
7961 }
7962 
7963 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7964   SDValue N0 = N->getOperand(0);
7965   EVT VT = N->getValueType(0);
7966 
7967   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7968   // Only do this before legalize, since afterward the target may be depending
7969   // on the bitconvert.
7970   // First check to see if this is all constant.
7971   if (!LegalTypes &&
7972       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7973       VT.isVector()) {
7974     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7975 
7976     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7977     assert(!DestEltVT.isVector() &&
7978            "Element type of vector ValueType must not be vector!");
7979     if (isSimple)
7980       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7981   }
7982 
7983   // If the input is a constant, let getNode fold it.
7984   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7985     // If we can't allow illegal operations, we need to check that this is just
7986     // a fp -> int or int -> conversion and that the resulting operation will
7987     // be legal.
7988     if (!LegalOperations ||
7989         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7990          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7991         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7992          TLI.isOperationLegal(ISD::Constant, VT)))
7993       return DAG.getBitcast(VT, N0);
7994   }
7995 
7996   // (conv (conv x, t1), t2) -> (conv x, t2)
7997   if (N0.getOpcode() == ISD::BITCAST)
7998     return DAG.getBitcast(VT, N0.getOperand(0));
7999 
8000   // fold (conv (load x)) -> (load (conv*)x)
8001   // If the resultant load doesn't need a higher alignment than the original!
8002   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8003       // Do not change the width of a volatile load.
8004       !cast<LoadSDNode>(N0)->isVolatile() &&
8005       // Do not remove the cast if the types differ in endian layout.
8006       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8007           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8008       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8009       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8010     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8011     unsigned OrigAlign = LN0->getAlignment();
8012 
8013     bool Fast = false;
8014     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8015                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8016         Fast) {
8017       SDValue Load =
8018           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8019                       LN0->getPointerInfo(), OrigAlign,
8020                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8021       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8022       return Load;
8023     }
8024   }
8025 
8026   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8027     return V;
8028 
8029   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8030   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8031   //
8032   // For ppc_fp128:
8033   // fold (bitcast (fneg x)) ->
8034   //     flipbit = signbit
8035   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8036   //
8037   // fold (bitcast (fabs x)) ->
8038   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8039   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8040   // This often reduces constant pool loads.
8041   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8042        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8043       N0.getNode()->hasOneUse() && VT.isInteger() &&
8044       !VT.isVector() && !N0.getValueType().isVector()) {
8045     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8046     AddToWorklist(NewConv.getNode());
8047 
8048     SDLoc DL(N);
8049     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8050       assert(VT.getSizeInBits() == 128);
8051       SDValue SignBit = DAG.getConstant(
8052           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8053       SDValue FlipBit;
8054       if (N0.getOpcode() == ISD::FNEG) {
8055         FlipBit = SignBit;
8056         AddToWorklist(FlipBit.getNode());
8057       } else {
8058         assert(N0.getOpcode() == ISD::FABS);
8059         SDValue Hi =
8060             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8061                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8062                                               SDLoc(NewConv)));
8063         AddToWorklist(Hi.getNode());
8064         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8065         AddToWorklist(FlipBit.getNode());
8066       }
8067       SDValue FlipBits =
8068           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8069       AddToWorklist(FlipBits.getNode());
8070       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8071     }
8072     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
8073     if (N0.getOpcode() == ISD::FNEG)
8074       return DAG.getNode(ISD::XOR, DL, VT,
8075                          NewConv, DAG.getConstant(SignBit, DL, VT));
8076     assert(N0.getOpcode() == ISD::FABS);
8077     return DAG.getNode(ISD::AND, DL, VT,
8078                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8079   }
8080 
8081   // fold (bitconvert (fcopysign cst, x)) ->
8082   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8083   // Note that we don't handle (copysign x, cst) because this can always be
8084   // folded to an fneg or fabs.
8085   //
8086   // For ppc_fp128:
8087   // fold (bitcast (fcopysign cst, x)) ->
8088   //     flipbit = (and (extract_element
8089   //                     (xor (bitcast cst), (bitcast x)), 0),
8090   //                    signbit)
8091   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8092   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8093       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8094       VT.isInteger() && !VT.isVector()) {
8095     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8096     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8097     if (isTypeLegal(IntXVT)) {
8098       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8099       AddToWorklist(X.getNode());
8100 
8101       // If X has a different width than the result/lhs, sext it or truncate it.
8102       unsigned VTWidth = VT.getSizeInBits();
8103       if (OrigXWidth < VTWidth) {
8104         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8105         AddToWorklist(X.getNode());
8106       } else if (OrigXWidth > VTWidth) {
8107         // To get the sign bit in the right place, we have to shift it right
8108         // before truncating.
8109         SDLoc DL(X);
8110         X = DAG.getNode(ISD::SRL, DL,
8111                         X.getValueType(), X,
8112                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8113                                         X.getValueType()));
8114         AddToWorklist(X.getNode());
8115         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8116         AddToWorklist(X.getNode());
8117       }
8118 
8119       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8120         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
8121         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8122         AddToWorklist(Cst.getNode());
8123         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8124         AddToWorklist(X.getNode());
8125         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8126         AddToWorklist(XorResult.getNode());
8127         SDValue XorResult64 = DAG.getNode(
8128             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8129             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8130                                   SDLoc(XorResult)));
8131         AddToWorklist(XorResult64.getNode());
8132         SDValue FlipBit =
8133             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8134                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8135         AddToWorklist(FlipBit.getNode());
8136         SDValue FlipBits =
8137             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8138         AddToWorklist(FlipBits.getNode());
8139         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8140       }
8141       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
8142       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8143                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8144       AddToWorklist(X.getNode());
8145 
8146       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8147       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8148                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8149       AddToWorklist(Cst.getNode());
8150 
8151       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8152     }
8153   }
8154 
8155   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8156   if (N0.getOpcode() == ISD::BUILD_PAIR)
8157     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8158       return CombineLD;
8159 
8160   // Remove double bitcasts from shuffles - this is often a legacy of
8161   // XformToShuffleWithZero being used to combine bitmaskings (of
8162   // float vectors bitcast to integer vectors) into shuffles.
8163   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8164   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8165       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8166       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8167       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8168     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8169 
8170     // If operands are a bitcast, peek through if it casts the original VT.
8171     // If operands are a constant, just bitcast back to original VT.
8172     auto PeekThroughBitcast = [&](SDValue Op) {
8173       if (Op.getOpcode() == ISD::BITCAST &&
8174           Op.getOperand(0).getValueType() == VT)
8175         return SDValue(Op.getOperand(0));
8176       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8177           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8178         return DAG.getBitcast(VT, Op);
8179       return SDValue();
8180     };
8181 
8182     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8183     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8184     if (!(SV0 && SV1))
8185       return SDValue();
8186 
8187     int MaskScale =
8188         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8189     SmallVector<int, 8> NewMask;
8190     for (int M : SVN->getMask())
8191       for (int i = 0; i != MaskScale; ++i)
8192         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8193 
8194     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8195     if (!LegalMask) {
8196       std::swap(SV0, SV1);
8197       ShuffleVectorSDNode::commuteMask(NewMask);
8198       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8199     }
8200 
8201     if (LegalMask)
8202       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8203   }
8204 
8205   return SDValue();
8206 }
8207 
8208 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8209   EVT VT = N->getValueType(0);
8210   return CombineConsecutiveLoads(N, VT);
8211 }
8212 
8213 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8214 /// operands. DstEltVT indicates the destination element value type.
8215 SDValue DAGCombiner::
8216 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8217   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8218 
8219   // If this is already the right type, we're done.
8220   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8221 
8222   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8223   unsigned DstBitSize = DstEltVT.getSizeInBits();
8224 
8225   // If this is a conversion of N elements of one type to N elements of another
8226   // type, convert each element.  This handles FP<->INT cases.
8227   if (SrcBitSize == DstBitSize) {
8228     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8229                               BV->getValueType(0).getVectorNumElements());
8230 
8231     // Due to the FP element handling below calling this routine recursively,
8232     // we can end up with a scalar-to-vector node here.
8233     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8234       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8235                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8236 
8237     SmallVector<SDValue, 8> Ops;
8238     for (SDValue Op : BV->op_values()) {
8239       // If the vector element type is not legal, the BUILD_VECTOR operands
8240       // are promoted and implicitly truncated.  Make that explicit here.
8241       if (Op.getValueType() != SrcEltVT)
8242         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8243       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8244       AddToWorklist(Ops.back().getNode());
8245     }
8246     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8247   }
8248 
8249   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8250   // handle annoying details of growing/shrinking FP values, we convert them to
8251   // int first.
8252   if (SrcEltVT.isFloatingPoint()) {
8253     // Convert the input float vector to a int vector where the elements are the
8254     // same sizes.
8255     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8256     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8257     SrcEltVT = IntVT;
8258   }
8259 
8260   // Now we know the input is an integer vector.  If the output is a FP type,
8261   // convert to integer first, then to FP of the right size.
8262   if (DstEltVT.isFloatingPoint()) {
8263     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8264     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8265 
8266     // Next, convert to FP elements of the same size.
8267     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8268   }
8269 
8270   SDLoc DL(BV);
8271 
8272   // Okay, we know the src/dst types are both integers of differing types.
8273   // Handling growing first.
8274   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8275   if (SrcBitSize < DstBitSize) {
8276     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8277 
8278     SmallVector<SDValue, 8> Ops;
8279     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8280          i += NumInputsPerOutput) {
8281       bool isLE = DAG.getDataLayout().isLittleEndian();
8282       APInt NewBits = APInt(DstBitSize, 0);
8283       bool EltIsUndef = true;
8284       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8285         // Shift the previously computed bits over.
8286         NewBits <<= SrcBitSize;
8287         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8288         if (Op.isUndef()) continue;
8289         EltIsUndef = false;
8290 
8291         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8292                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
8293       }
8294 
8295       if (EltIsUndef)
8296         Ops.push_back(DAG.getUNDEF(DstEltVT));
8297       else
8298         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8299     }
8300 
8301     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8302     return DAG.getBuildVector(VT, DL, Ops);
8303   }
8304 
8305   // Finally, this must be the case where we are shrinking elements: each input
8306   // turns into multiple outputs.
8307   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8308   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8309                             NumOutputsPerInput*BV->getNumOperands());
8310   SmallVector<SDValue, 8> Ops;
8311 
8312   for (const SDValue &Op : BV->op_values()) {
8313     if (Op.isUndef()) {
8314       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8315       continue;
8316     }
8317 
8318     APInt OpVal = cast<ConstantSDNode>(Op)->
8319                   getAPIntValue().zextOrTrunc(SrcBitSize);
8320 
8321     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8322       APInt ThisVal = OpVal.trunc(DstBitSize);
8323       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8324       OpVal = OpVal.lshr(DstBitSize);
8325     }
8326 
8327     // For big endian targets, swap the order of the pieces of each element.
8328     if (DAG.getDataLayout().isBigEndian())
8329       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8330   }
8331 
8332   return DAG.getBuildVector(VT, DL, Ops);
8333 }
8334 
8335 /// Try to perform FMA combining on a given FADD node.
8336 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8337   SDValue N0 = N->getOperand(0);
8338   SDValue N1 = N->getOperand(1);
8339   EVT VT = N->getValueType(0);
8340   SDLoc SL(N);
8341 
8342   const TargetOptions &Options = DAG.getTarget().Options;
8343   bool AllowFusion =
8344       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8345 
8346   // Floating-point multiply-add with intermediate rounding.
8347   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8348 
8349   // Floating-point multiply-add without intermediate rounding.
8350   bool HasFMA =
8351       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8352       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8353 
8354   // No valid opcode, do not combine.
8355   if (!HasFMAD && !HasFMA)
8356     return SDValue();
8357 
8358   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8359   ;
8360   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8361     return SDValue();
8362 
8363   // Always prefer FMAD to FMA for precision.
8364   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8365   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8366   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8367 
8368   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8369   // prefer to fold the multiply with fewer uses.
8370   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
8371       N1.getOpcode() == ISD::FMUL) {
8372     if (N0.getNode()->use_size() > N1.getNode()->use_size())
8373       std::swap(N0, N1);
8374   }
8375 
8376   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8377   if (N0.getOpcode() == ISD::FMUL &&
8378       (Aggressive || N0->hasOneUse())) {
8379     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8380                        N0.getOperand(0), N0.getOperand(1), N1);
8381   }
8382 
8383   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8384   // Note: Commutes FADD operands.
8385   if (N1.getOpcode() == ISD::FMUL &&
8386       (Aggressive || N1->hasOneUse())) {
8387     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8388                        N1.getOperand(0), N1.getOperand(1), N0);
8389   }
8390 
8391   // Look through FP_EXTEND nodes to do more combining.
8392   if (AllowFusion && LookThroughFPExt) {
8393     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8394     if (N0.getOpcode() == ISD::FP_EXTEND) {
8395       SDValue N00 = N0.getOperand(0);
8396       if (N00.getOpcode() == ISD::FMUL)
8397         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8398                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8399                                        N00.getOperand(0)),
8400                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8401                                        N00.getOperand(1)), N1);
8402     }
8403 
8404     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8405     // Note: Commutes FADD operands.
8406     if (N1.getOpcode() == ISD::FP_EXTEND) {
8407       SDValue N10 = N1.getOperand(0);
8408       if (N10.getOpcode() == ISD::FMUL)
8409         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8410                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8411                                        N10.getOperand(0)),
8412                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8413                                        N10.getOperand(1)), N0);
8414     }
8415   }
8416 
8417   // More folding opportunities when target permits.
8418   if (Aggressive) {
8419     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8420     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8421     // are currently only supported on binary nodes.
8422     if (Options.UnsafeFPMath &&
8423         N0.getOpcode() == PreferredFusedOpcode &&
8424         N0.getOperand(2).getOpcode() == ISD::FMUL &&
8425         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
8426       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8427                          N0.getOperand(0), N0.getOperand(1),
8428                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8429                                      N0.getOperand(2).getOperand(0),
8430                                      N0.getOperand(2).getOperand(1),
8431                                      N1));
8432     }
8433 
8434     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8435     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8436     // are currently only supported on binary nodes.
8437     if (Options.UnsafeFPMath &&
8438         N1->getOpcode() == PreferredFusedOpcode &&
8439         N1.getOperand(2).getOpcode() == ISD::FMUL &&
8440         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
8441       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8442                          N1.getOperand(0), N1.getOperand(1),
8443                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8444                                      N1.getOperand(2).getOperand(0),
8445                                      N1.getOperand(2).getOperand(1),
8446                                      N0));
8447     }
8448 
8449     if (AllowFusion && LookThroughFPExt) {
8450       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8451       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8452       auto FoldFAddFMAFPExtFMul = [&] (
8453           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8454         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8455                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8456                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8457                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8458                                        Z));
8459       };
8460       if (N0.getOpcode() == PreferredFusedOpcode) {
8461         SDValue N02 = N0.getOperand(2);
8462         if (N02.getOpcode() == ISD::FP_EXTEND) {
8463           SDValue N020 = N02.getOperand(0);
8464           if (N020.getOpcode() == ISD::FMUL)
8465             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8466                                         N020.getOperand(0), N020.getOperand(1),
8467                                         N1);
8468         }
8469       }
8470 
8471       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8472       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8473       // FIXME: This turns two single-precision and one double-precision
8474       // operation into two double-precision operations, which might not be
8475       // interesting for all targets, especially GPUs.
8476       auto FoldFAddFPExtFMAFMul = [&] (
8477           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8478         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8479                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8480                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8481                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8482                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8483                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8484                                        Z));
8485       };
8486       if (N0.getOpcode() == ISD::FP_EXTEND) {
8487         SDValue N00 = N0.getOperand(0);
8488         if (N00.getOpcode() == PreferredFusedOpcode) {
8489           SDValue N002 = N00.getOperand(2);
8490           if (N002.getOpcode() == ISD::FMUL)
8491             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8492                                         N002.getOperand(0), N002.getOperand(1),
8493                                         N1);
8494         }
8495       }
8496 
8497       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8498       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
8499       if (N1.getOpcode() == PreferredFusedOpcode) {
8500         SDValue N12 = N1.getOperand(2);
8501         if (N12.getOpcode() == ISD::FP_EXTEND) {
8502           SDValue N120 = N12.getOperand(0);
8503           if (N120.getOpcode() == ISD::FMUL)
8504             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8505                                         N120.getOperand(0), N120.getOperand(1),
8506                                         N0);
8507         }
8508       }
8509 
8510       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8511       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8512       // FIXME: This turns two single-precision and one double-precision
8513       // operation into two double-precision operations, which might not be
8514       // interesting for all targets, especially GPUs.
8515       if (N1.getOpcode() == ISD::FP_EXTEND) {
8516         SDValue N10 = N1.getOperand(0);
8517         if (N10.getOpcode() == PreferredFusedOpcode) {
8518           SDValue N102 = N10.getOperand(2);
8519           if (N102.getOpcode() == ISD::FMUL)
8520             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8521                                         N102.getOperand(0), N102.getOperand(1),
8522                                         N0);
8523         }
8524       }
8525     }
8526   }
8527 
8528   return SDValue();
8529 }
8530 
8531 /// Try to perform FMA combining on a given FSUB node.
8532 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8533   SDValue N0 = N->getOperand(0);
8534   SDValue N1 = N->getOperand(1);
8535   EVT VT = N->getValueType(0);
8536   SDLoc SL(N);
8537 
8538   const TargetOptions &Options = DAG.getTarget().Options;
8539   bool AllowFusion =
8540       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8541 
8542   // Floating-point multiply-add with intermediate rounding.
8543   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8544 
8545   // Floating-point multiply-add without intermediate rounding.
8546   bool HasFMA =
8547       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8548       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8549 
8550   // No valid opcode, do not combine.
8551   if (!HasFMAD && !HasFMA)
8552     return SDValue();
8553 
8554   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8555   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8556     return SDValue();
8557 
8558   // Always prefer FMAD to FMA for precision.
8559   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8560   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8561   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8562 
8563   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8564   if (N0.getOpcode() == ISD::FMUL &&
8565       (Aggressive || N0->hasOneUse())) {
8566     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8567                        N0.getOperand(0), N0.getOperand(1),
8568                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8569   }
8570 
8571   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8572   // Note: Commutes FSUB operands.
8573   if (N1.getOpcode() == ISD::FMUL &&
8574       (Aggressive || N1->hasOneUse()))
8575     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8576                        DAG.getNode(ISD::FNEG, SL, VT,
8577                                    N1.getOperand(0)),
8578                        N1.getOperand(1), N0);
8579 
8580   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8581   if (N0.getOpcode() == ISD::FNEG &&
8582       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8583       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8584     SDValue N00 = N0.getOperand(0).getOperand(0);
8585     SDValue N01 = N0.getOperand(0).getOperand(1);
8586     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8587                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8588                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8589   }
8590 
8591   // Look through FP_EXTEND nodes to do more combining.
8592   if (AllowFusion && LookThroughFPExt) {
8593     // fold (fsub (fpext (fmul x, y)), z)
8594     //   -> (fma (fpext x), (fpext y), (fneg z))
8595     if (N0.getOpcode() == ISD::FP_EXTEND) {
8596       SDValue N00 = N0.getOperand(0);
8597       if (N00.getOpcode() == ISD::FMUL)
8598         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8599                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8600                                        N00.getOperand(0)),
8601                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8602                                        N00.getOperand(1)),
8603                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8604     }
8605 
8606     // fold (fsub x, (fpext (fmul y, z)))
8607     //   -> (fma (fneg (fpext y)), (fpext z), x)
8608     // Note: Commutes FSUB operands.
8609     if (N1.getOpcode() == ISD::FP_EXTEND) {
8610       SDValue N10 = N1.getOperand(0);
8611       if (N10.getOpcode() == ISD::FMUL)
8612         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8613                            DAG.getNode(ISD::FNEG, SL, VT,
8614                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8615                                                    N10.getOperand(0))),
8616                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8617                                        N10.getOperand(1)),
8618                            N0);
8619     }
8620 
8621     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8622     //   -> (fneg (fma (fpext x), (fpext y), z))
8623     // Note: This could be removed with appropriate canonicalization of the
8624     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8625     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8626     // from implementing the canonicalization in visitFSUB.
8627     if (N0.getOpcode() == ISD::FP_EXTEND) {
8628       SDValue N00 = N0.getOperand(0);
8629       if (N00.getOpcode() == ISD::FNEG) {
8630         SDValue N000 = N00.getOperand(0);
8631         if (N000.getOpcode() == ISD::FMUL) {
8632           return DAG.getNode(ISD::FNEG, SL, VT,
8633                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8634                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8635                                                      N000.getOperand(0)),
8636                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8637                                                      N000.getOperand(1)),
8638                                          N1));
8639         }
8640       }
8641     }
8642 
8643     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8644     //   -> (fneg (fma (fpext x)), (fpext y), z)
8645     // Note: This could be removed with appropriate canonicalization of the
8646     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8647     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8648     // from implementing the canonicalization in visitFSUB.
8649     if (N0.getOpcode() == ISD::FNEG) {
8650       SDValue N00 = N0.getOperand(0);
8651       if (N00.getOpcode() == ISD::FP_EXTEND) {
8652         SDValue N000 = N00.getOperand(0);
8653         if (N000.getOpcode() == ISD::FMUL) {
8654           return DAG.getNode(ISD::FNEG, SL, VT,
8655                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8656                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8657                                                      N000.getOperand(0)),
8658                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8659                                                      N000.getOperand(1)),
8660                                          N1));
8661         }
8662       }
8663     }
8664 
8665   }
8666 
8667   // More folding opportunities when target permits.
8668   if (Aggressive) {
8669     // fold (fsub (fma x, y, (fmul u, v)), z)
8670     //   -> (fma x, y (fma u, v, (fneg z)))
8671     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8672     // are currently only supported on binary nodes.
8673     if (Options.UnsafeFPMath &&
8674         N0.getOpcode() == PreferredFusedOpcode &&
8675         N0.getOperand(2).getOpcode() == ISD::FMUL &&
8676         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
8677       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8678                          N0.getOperand(0), N0.getOperand(1),
8679                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8680                                      N0.getOperand(2).getOperand(0),
8681                                      N0.getOperand(2).getOperand(1),
8682                                      DAG.getNode(ISD::FNEG, SL, VT,
8683                                                  N1)));
8684     }
8685 
8686     // fold (fsub x, (fma y, z, (fmul u, v)))
8687     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8688     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8689     // are currently only supported on binary nodes.
8690     if (Options.UnsafeFPMath &&
8691         N1.getOpcode() == PreferredFusedOpcode &&
8692         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8693       SDValue N20 = N1.getOperand(2).getOperand(0);
8694       SDValue N21 = N1.getOperand(2).getOperand(1);
8695       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8696                          DAG.getNode(ISD::FNEG, SL, VT,
8697                                      N1.getOperand(0)),
8698                          N1.getOperand(1),
8699                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8700                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8701 
8702                                      N21, N0));
8703     }
8704 
8705     if (AllowFusion && LookThroughFPExt) {
8706       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8707       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8708       if (N0.getOpcode() == PreferredFusedOpcode) {
8709         SDValue N02 = N0.getOperand(2);
8710         if (N02.getOpcode() == ISD::FP_EXTEND) {
8711           SDValue N020 = N02.getOperand(0);
8712           if (N020.getOpcode() == ISD::FMUL)
8713             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8714                                N0.getOperand(0), N0.getOperand(1),
8715                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8716                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8717                                                        N020.getOperand(0)),
8718                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8719                                                        N020.getOperand(1)),
8720                                            DAG.getNode(ISD::FNEG, SL, VT,
8721                                                        N1)));
8722         }
8723       }
8724 
8725       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8726       //   -> (fma (fpext x), (fpext y),
8727       //           (fma (fpext u), (fpext v), (fneg z)))
8728       // FIXME: This turns two single-precision and one double-precision
8729       // operation into two double-precision operations, which might not be
8730       // interesting for all targets, especially GPUs.
8731       if (N0.getOpcode() == ISD::FP_EXTEND) {
8732         SDValue N00 = N0.getOperand(0);
8733         if (N00.getOpcode() == PreferredFusedOpcode) {
8734           SDValue N002 = N00.getOperand(2);
8735           if (N002.getOpcode() == ISD::FMUL)
8736             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8737                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8738                                            N00.getOperand(0)),
8739                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8740                                            N00.getOperand(1)),
8741                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8742                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8743                                                        N002.getOperand(0)),
8744                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8745                                                        N002.getOperand(1)),
8746                                            DAG.getNode(ISD::FNEG, SL, VT,
8747                                                        N1)));
8748         }
8749       }
8750 
8751       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8752       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8753       if (N1.getOpcode() == PreferredFusedOpcode &&
8754         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8755         SDValue N120 = N1.getOperand(2).getOperand(0);
8756         if (N120.getOpcode() == ISD::FMUL) {
8757           SDValue N1200 = N120.getOperand(0);
8758           SDValue N1201 = N120.getOperand(1);
8759           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8760                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8761                              N1.getOperand(1),
8762                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8763                                          DAG.getNode(ISD::FNEG, SL, VT,
8764                                              DAG.getNode(ISD::FP_EXTEND, SL,
8765                                                          VT, N1200)),
8766                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8767                                                      N1201),
8768                                          N0));
8769         }
8770       }
8771 
8772       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8773       //   -> (fma (fneg (fpext y)), (fpext z),
8774       //           (fma (fneg (fpext u)), (fpext v), x))
8775       // FIXME: This turns two single-precision and one double-precision
8776       // operation into two double-precision operations, which might not be
8777       // interesting for all targets, especially GPUs.
8778       if (N1.getOpcode() == ISD::FP_EXTEND &&
8779         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8780         SDValue N100 = N1.getOperand(0).getOperand(0);
8781         SDValue N101 = N1.getOperand(0).getOperand(1);
8782         SDValue N102 = N1.getOperand(0).getOperand(2);
8783         if (N102.getOpcode() == ISD::FMUL) {
8784           SDValue N1020 = N102.getOperand(0);
8785           SDValue N1021 = N102.getOperand(1);
8786           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8787                              DAG.getNode(ISD::FNEG, SL, VT,
8788                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8789                                                      N100)),
8790                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8791                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8792                                          DAG.getNode(ISD::FNEG, SL, VT,
8793                                              DAG.getNode(ISD::FP_EXTEND, SL,
8794                                                          VT, N1020)),
8795                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8796                                                      N1021),
8797                                          N0));
8798         }
8799       }
8800     }
8801   }
8802 
8803   return SDValue();
8804 }
8805 
8806 /// Try to perform FMA combining on a given FMUL node based on the distributive
8807 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
8808 /// subtraction instead of addition).
8809 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
8810   SDValue N0 = N->getOperand(0);
8811   SDValue N1 = N->getOperand(1);
8812   EVT VT = N->getValueType(0);
8813   SDLoc SL(N);
8814 
8815   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8816 
8817   const TargetOptions &Options = DAG.getTarget().Options;
8818 
8819   // The transforms below are incorrect when x == 0 and y == inf, because the
8820   // intermediate multiplication produces a nan.
8821   if (!Options.NoInfsFPMath)
8822     return SDValue();
8823 
8824   // Floating-point multiply-add without intermediate rounding.
8825   bool HasFMA =
8826       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
8827       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8828       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8829 
8830   // Floating-point multiply-add with intermediate rounding. This can result
8831   // in a less precise result due to the changed rounding order.
8832   bool HasFMAD = Options.UnsafeFPMath &&
8833                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8834 
8835   // No valid opcode, do not combine.
8836   if (!HasFMAD && !HasFMA)
8837     return SDValue();
8838 
8839   // Always prefer FMAD to FMA for precision.
8840   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8841   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8842 
8843   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8844   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8845   auto FuseFADD = [&](SDValue X, SDValue Y) {
8846     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8847       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8848       if (XC1 && XC1->isExactlyValue(+1.0))
8849         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8850       if (XC1 && XC1->isExactlyValue(-1.0))
8851         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8852                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8853     }
8854     return SDValue();
8855   };
8856 
8857   if (SDValue FMA = FuseFADD(N0, N1))
8858     return FMA;
8859   if (SDValue FMA = FuseFADD(N1, N0))
8860     return FMA;
8861 
8862   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8863   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8864   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8865   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8866   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8867     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8868       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8869       if (XC0 && XC0->isExactlyValue(+1.0))
8870         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8871                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8872                            Y);
8873       if (XC0 && XC0->isExactlyValue(-1.0))
8874         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8875                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8876                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8877 
8878       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8879       if (XC1 && XC1->isExactlyValue(+1.0))
8880         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8881                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8882       if (XC1 && XC1->isExactlyValue(-1.0))
8883         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8884     }
8885     return SDValue();
8886   };
8887 
8888   if (SDValue FMA = FuseFSUB(N0, N1))
8889     return FMA;
8890   if (SDValue FMA = FuseFSUB(N1, N0))
8891     return FMA;
8892 
8893   return SDValue();
8894 }
8895 
8896 SDValue DAGCombiner::visitFADD(SDNode *N) {
8897   SDValue N0 = N->getOperand(0);
8898   SDValue N1 = N->getOperand(1);
8899   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8900   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8901   EVT VT = N->getValueType(0);
8902   SDLoc DL(N);
8903   const TargetOptions &Options = DAG.getTarget().Options;
8904   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8905 
8906   // fold vector ops
8907   if (VT.isVector())
8908     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8909       return FoldedVOp;
8910 
8911   // fold (fadd c1, c2) -> c1 + c2
8912   if (N0CFP && N1CFP)
8913     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8914 
8915   // canonicalize constant to RHS
8916   if (N0CFP && !N1CFP)
8917     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8918 
8919   // fold (fadd A, (fneg B)) -> (fsub A, B)
8920   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8921       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8922     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8923                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8924 
8925   // fold (fadd (fneg A), B) -> (fsub B, A)
8926   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8927       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8928     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8929                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8930 
8931   // FIXME: Auto-upgrade the target/function-level option.
8932   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8933     // fold (fadd A, 0) -> A
8934     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8935       if (N1C->isZero())
8936         return N0;
8937   }
8938 
8939   // If 'unsafe math' is enabled, fold lots of things.
8940   if (Options.UnsafeFPMath) {
8941     // No FP constant should be created after legalization as Instruction
8942     // Selection pass has a hard time dealing with FP constants.
8943     bool AllowNewConst = (Level < AfterLegalizeDAG);
8944 
8945     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8946     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8947         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8948       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8949                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8950                                      Flags),
8951                          Flags);
8952 
8953     // If allowed, fold (fadd (fneg x), x) -> 0.0
8954     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8955       return DAG.getConstantFP(0.0, DL, VT);
8956 
8957     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8958     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8959       return DAG.getConstantFP(0.0, DL, VT);
8960 
8961     // We can fold chains of FADD's of the same value into multiplications.
8962     // This transform is not safe in general because we are reducing the number
8963     // of rounding steps.
8964     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8965       if (N0.getOpcode() == ISD::FMUL) {
8966         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8967         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8968 
8969         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8970         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8971           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8972                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8973           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8974         }
8975 
8976         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8977         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8978             N1.getOperand(0) == N1.getOperand(1) &&
8979             N0.getOperand(0) == N1.getOperand(0)) {
8980           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8981                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8982           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8983         }
8984       }
8985 
8986       if (N1.getOpcode() == ISD::FMUL) {
8987         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8988         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8989 
8990         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8991         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8992           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8993                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8994           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8995         }
8996 
8997         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8998         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8999             N0.getOperand(0) == N0.getOperand(1) &&
9000             N1.getOperand(0) == N0.getOperand(0)) {
9001           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9002                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9003           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9004         }
9005       }
9006 
9007       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9008         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9009         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9010         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9011             (N0.getOperand(0) == N1)) {
9012           return DAG.getNode(ISD::FMUL, DL, VT,
9013                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9014         }
9015       }
9016 
9017       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9018         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9019         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9020         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9021             N1.getOperand(0) == N0) {
9022           return DAG.getNode(ISD::FMUL, DL, VT,
9023                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9024         }
9025       }
9026 
9027       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9028       if (AllowNewConst &&
9029           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9030           N0.getOperand(0) == N0.getOperand(1) &&
9031           N1.getOperand(0) == N1.getOperand(1) &&
9032           N0.getOperand(0) == N1.getOperand(0)) {
9033         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9034                            DAG.getConstantFP(4.0, DL, VT), Flags);
9035       }
9036     }
9037   } // enable-unsafe-fp-math
9038 
9039   // FADD -> FMA combines:
9040   if (SDValue Fused = visitFADDForFMACombine(N)) {
9041     AddToWorklist(Fused.getNode());
9042     return Fused;
9043   }
9044   return SDValue();
9045 }
9046 
9047 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9048   SDValue N0 = N->getOperand(0);
9049   SDValue N1 = N->getOperand(1);
9050   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9051   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9052   EVT VT = N->getValueType(0);
9053   SDLoc DL(N);
9054   const TargetOptions &Options = DAG.getTarget().Options;
9055   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9056 
9057   // fold vector ops
9058   if (VT.isVector())
9059     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9060       return FoldedVOp;
9061 
9062   // fold (fsub c1, c2) -> c1-c2
9063   if (N0CFP && N1CFP)
9064     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9065 
9066   // fold (fsub A, (fneg B)) -> (fadd A, B)
9067   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9068     return DAG.getNode(ISD::FADD, DL, VT, N0,
9069                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9070 
9071   // FIXME: Auto-upgrade the target/function-level option.
9072   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
9073     // (fsub 0, B) -> -B
9074     if (N0CFP && N0CFP->isZero()) {
9075       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9076         return GetNegatedExpression(N1, DAG, LegalOperations);
9077       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9078         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9079     }
9080   }
9081 
9082   // If 'unsafe math' is enabled, fold lots of things.
9083   if (Options.UnsafeFPMath) {
9084     // (fsub A, 0) -> A
9085     if (N1CFP && N1CFP->isZero())
9086       return N0;
9087 
9088     // (fsub x, x) -> 0.0
9089     if (N0 == N1)
9090       return DAG.getConstantFP(0.0f, DL, VT);
9091 
9092     // (fsub x, (fadd x, y)) -> (fneg y)
9093     // (fsub x, (fadd y, x)) -> (fneg y)
9094     if (N1.getOpcode() == ISD::FADD) {
9095       SDValue N10 = N1->getOperand(0);
9096       SDValue N11 = N1->getOperand(1);
9097 
9098       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9099         return GetNegatedExpression(N11, DAG, LegalOperations);
9100 
9101       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9102         return GetNegatedExpression(N10, DAG, LegalOperations);
9103     }
9104   }
9105 
9106   // FSUB -> FMA combines:
9107   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9108     AddToWorklist(Fused.getNode());
9109     return Fused;
9110   }
9111 
9112   return SDValue();
9113 }
9114 
9115 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9116   SDValue N0 = N->getOperand(0);
9117   SDValue N1 = N->getOperand(1);
9118   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9119   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9120   EVT VT = N->getValueType(0);
9121   SDLoc DL(N);
9122   const TargetOptions &Options = DAG.getTarget().Options;
9123   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9124 
9125   // fold vector ops
9126   if (VT.isVector()) {
9127     // This just handles C1 * C2 for vectors. Other vector folds are below.
9128     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9129       return FoldedVOp;
9130   }
9131 
9132   // fold (fmul c1, c2) -> c1*c2
9133   if (N0CFP && N1CFP)
9134     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9135 
9136   // canonicalize constant to RHS
9137   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9138      !isConstantFPBuildVectorOrConstantFP(N1))
9139     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9140 
9141   // fold (fmul A, 1.0) -> A
9142   if (N1CFP && N1CFP->isExactlyValue(1.0))
9143     return N0;
9144 
9145   if (Options.UnsafeFPMath) {
9146     // fold (fmul A, 0) -> 0
9147     if (N1CFP && N1CFP->isZero())
9148       return N1;
9149 
9150     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9151     if (N0.getOpcode() == ISD::FMUL) {
9152       // Fold scalars or any vector constants (not just splats).
9153       // This fold is done in general by InstCombine, but extra fmul insts
9154       // may have been generated during lowering.
9155       SDValue N00 = N0.getOperand(0);
9156       SDValue N01 = N0.getOperand(1);
9157       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9158       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9159       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9160 
9161       // Check 1: Make sure that the first operand of the inner multiply is NOT
9162       // a constant. Otherwise, we may induce infinite looping.
9163       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9164         // Check 2: Make sure that the second operand of the inner multiply and
9165         // the second operand of the outer multiply are constants.
9166         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9167             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9168           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9169           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9170         }
9171       }
9172     }
9173 
9174     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9175     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9176     // during an early run of DAGCombiner can prevent folding with fmuls
9177     // inserted during lowering.
9178     if (N0.getOpcode() == ISD::FADD &&
9179         (N0.getOperand(0) == N0.getOperand(1)) &&
9180         N0.hasOneUse()) {
9181       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9182       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9183       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9184     }
9185   }
9186 
9187   // fold (fmul X, 2.0) -> (fadd X, X)
9188   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9189     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9190 
9191   // fold (fmul X, -1.0) -> (fneg X)
9192   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9193     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9194       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9195 
9196   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9197   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9198     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9199       // Both can be negated for free, check to see if at least one is cheaper
9200       // negated.
9201       if (LHSNeg == 2 || RHSNeg == 2)
9202         return DAG.getNode(ISD::FMUL, DL, VT,
9203                            GetNegatedExpression(N0, DAG, LegalOperations),
9204                            GetNegatedExpression(N1, DAG, LegalOperations),
9205                            Flags);
9206     }
9207   }
9208 
9209   // FMUL -> FMA combines:
9210   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9211     AddToWorklist(Fused.getNode());
9212     return Fused;
9213   }
9214 
9215   return SDValue();
9216 }
9217 
9218 SDValue DAGCombiner::visitFMA(SDNode *N) {
9219   SDValue N0 = N->getOperand(0);
9220   SDValue N1 = N->getOperand(1);
9221   SDValue N2 = N->getOperand(2);
9222   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9223   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9224   EVT VT = N->getValueType(0);
9225   SDLoc DL(N);
9226   const TargetOptions &Options = DAG.getTarget().Options;
9227 
9228   // Constant fold FMA.
9229   if (isa<ConstantFPSDNode>(N0) &&
9230       isa<ConstantFPSDNode>(N1) &&
9231       isa<ConstantFPSDNode>(N2)) {
9232     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9233   }
9234 
9235   if (Options.UnsafeFPMath) {
9236     if (N0CFP && N0CFP->isZero())
9237       return N2;
9238     if (N1CFP && N1CFP->isZero())
9239       return N2;
9240   }
9241   // TODO: The FMA node should have flags that propagate to these nodes.
9242   if (N0CFP && N0CFP->isExactlyValue(1.0))
9243     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9244   if (N1CFP && N1CFP->isExactlyValue(1.0))
9245     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9246 
9247   // Canonicalize (fma c, x, y) -> (fma x, c, y)
9248   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9249      !isConstantFPBuildVectorOrConstantFP(N1))
9250     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9251 
9252   // TODO: FMA nodes should have flags that propagate to the created nodes.
9253   // For now, create a Flags object for use with all unsafe math transforms.
9254   SDNodeFlags Flags;
9255   Flags.setUnsafeAlgebra(true);
9256 
9257   if (Options.UnsafeFPMath) {
9258     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9259     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9260         isConstantFPBuildVectorOrConstantFP(N1) &&
9261         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9262       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9263                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9264                                      &Flags), &Flags);
9265     }
9266 
9267     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9268     if (N0.getOpcode() == ISD::FMUL &&
9269         isConstantFPBuildVectorOrConstantFP(N1) &&
9270         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9271       return DAG.getNode(ISD::FMA, DL, VT,
9272                          N0.getOperand(0),
9273                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9274                                      &Flags),
9275                          N2);
9276     }
9277   }
9278 
9279   // (fma x, 1, y) -> (fadd x, y)
9280   // (fma x, -1, y) -> (fadd (fneg x), y)
9281   if (N1CFP) {
9282     if (N1CFP->isExactlyValue(1.0))
9283       // TODO: The FMA node should have flags that propagate to this node.
9284       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9285 
9286     if (N1CFP->isExactlyValue(-1.0) &&
9287         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9288       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9289       AddToWorklist(RHSNeg.getNode());
9290       // TODO: The FMA node should have flags that propagate to this node.
9291       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9292     }
9293   }
9294 
9295   if (Options.UnsafeFPMath) {
9296     // (fma x, c, x) -> (fmul x, (c+1))
9297     if (N1CFP && N0 == N2) {
9298       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9299                          DAG.getNode(ISD::FADD, DL, VT, N1,
9300                                      DAG.getConstantFP(1.0, DL, VT), &Flags),
9301                          &Flags);
9302     }
9303 
9304     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9305     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9306       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9307                          DAG.getNode(ISD::FADD, DL, VT, N1,
9308                                      DAG.getConstantFP(-1.0, DL, VT), &Flags),
9309                          &Flags);
9310     }
9311   }
9312 
9313   return SDValue();
9314 }
9315 
9316 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9317 // reciprocal.
9318 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9319 // Notice that this is not always beneficial. One reason is different targets
9320 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9321 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9322 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9323 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9324   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9325   const SDNodeFlags *Flags = N->getFlags();
9326   if (!UnsafeMath && !Flags->hasAllowReciprocal())
9327     return SDValue();
9328 
9329   // Skip if current node is a reciprocal.
9330   SDValue N0 = N->getOperand(0);
9331   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9332   if (N0CFP && N0CFP->isExactlyValue(1.0))
9333     return SDValue();
9334 
9335   // Exit early if the target does not want this transform or if there can't
9336   // possibly be enough uses of the divisor to make the transform worthwhile.
9337   SDValue N1 = N->getOperand(1);
9338   unsigned MinUses = TLI.combineRepeatedFPDivisors();
9339   if (!MinUses || N1->use_size() < MinUses)
9340     return SDValue();
9341 
9342   // Find all FDIV users of the same divisor.
9343   // Use a set because duplicates may be present in the user list.
9344   SetVector<SDNode *> Users;
9345   for (auto *U : N1->uses()) {
9346     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
9347       // This division is eligible for optimization only if global unsafe math
9348       // is enabled or if this division allows reciprocal formation.
9349       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
9350         Users.insert(U);
9351     }
9352   }
9353 
9354   // Now that we have the actual number of divisor uses, make sure it meets
9355   // the minimum threshold specified by the target.
9356   if (Users.size() < MinUses)
9357     return SDValue();
9358 
9359   EVT VT = N->getValueType(0);
9360   SDLoc DL(N);
9361   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
9362   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
9363 
9364   // Dividend / Divisor -> Dividend * Reciprocal
9365   for (auto *U : Users) {
9366     SDValue Dividend = U->getOperand(0);
9367     if (Dividend != FPOne) {
9368       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
9369                                     Reciprocal, Flags);
9370       CombineTo(U, NewNode);
9371     } else if (U != Reciprocal.getNode()) {
9372       // In the absence of fast-math-flags, this user node is always the
9373       // same node as Reciprocal, but with FMF they may be different nodes.
9374       CombineTo(U, Reciprocal);
9375     }
9376   }
9377   return SDValue(N, 0);  // N was replaced.
9378 }
9379 
9380 SDValue DAGCombiner::visitFDIV(SDNode *N) {
9381   SDValue N0 = N->getOperand(0);
9382   SDValue N1 = N->getOperand(1);
9383   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9384   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9385   EVT VT = N->getValueType(0);
9386   SDLoc DL(N);
9387   const TargetOptions &Options = DAG.getTarget().Options;
9388   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9389 
9390   // fold vector ops
9391   if (VT.isVector())
9392     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9393       return FoldedVOp;
9394 
9395   // fold (fdiv c1, c2) -> c1/c2
9396   if (N0CFP && N1CFP)
9397     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
9398 
9399   if (Options.UnsafeFPMath) {
9400     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
9401     if (N1CFP) {
9402       // Compute the reciprocal 1.0 / c2.
9403       const APFloat &N1APF = N1CFP->getValueAPF();
9404       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
9405       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
9406       // Only do the transform if the reciprocal is a legal fp immediate that
9407       // isn't too nasty (eg NaN, denormal, ...).
9408       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
9409           (!LegalOperations ||
9410            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
9411            // backend)... we should handle this gracefully after Legalize.
9412            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
9413            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
9414            TLI.isFPImmLegal(Recip, VT)))
9415         return DAG.getNode(ISD::FMUL, DL, VT, N0,
9416                            DAG.getConstantFP(Recip, DL, VT), Flags);
9417     }
9418 
9419     // If this FDIV is part of a reciprocal square root, it may be folded
9420     // into a target-specific square root estimate instruction.
9421     if (N1.getOpcode() == ISD::FSQRT) {
9422       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
9423         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9424       }
9425     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
9426                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9427       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9428                                           Flags)) {
9429         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
9430         AddToWorklist(RV.getNode());
9431         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9432       }
9433     } else if (N1.getOpcode() == ISD::FP_ROUND &&
9434                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9435       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9436                                           Flags)) {
9437         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9438         AddToWorklist(RV.getNode());
9439         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9440       }
9441     } else if (N1.getOpcode() == ISD::FMUL) {
9442       // Look through an FMUL. Even though this won't remove the FDIV directly,
9443       // it's still worthwhile to get rid of the FSQRT if possible.
9444       SDValue SqrtOp;
9445       SDValue OtherOp;
9446       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9447         SqrtOp = N1.getOperand(0);
9448         OtherOp = N1.getOperand(1);
9449       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9450         SqrtOp = N1.getOperand(1);
9451         OtherOp = N1.getOperand(0);
9452       }
9453       if (SqrtOp.getNode()) {
9454         // We found a FSQRT, so try to make this fold:
9455         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9456         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9457           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9458           AddToWorklist(RV.getNode());
9459           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9460         }
9461       }
9462     }
9463 
9464     // Fold into a reciprocal estimate and multiply instead of a real divide.
9465     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9466       AddToWorklist(RV.getNode());
9467       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9468     }
9469   }
9470 
9471   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9472   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9473     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9474       // Both can be negated for free, check to see if at least one is cheaper
9475       // negated.
9476       if (LHSNeg == 2 || RHSNeg == 2)
9477         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9478                            GetNegatedExpression(N0, DAG, LegalOperations),
9479                            GetNegatedExpression(N1, DAG, LegalOperations),
9480                            Flags);
9481     }
9482   }
9483 
9484   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9485     return CombineRepeatedDivisors;
9486 
9487   return SDValue();
9488 }
9489 
9490 SDValue DAGCombiner::visitFREM(SDNode *N) {
9491   SDValue N0 = N->getOperand(0);
9492   SDValue N1 = N->getOperand(1);
9493   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9494   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9495   EVT VT = N->getValueType(0);
9496 
9497   // fold (frem c1, c2) -> fmod(c1,c2)
9498   if (N0CFP && N1CFP)
9499     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9500                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
9501 
9502   return SDValue();
9503 }
9504 
9505 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9506   if (!DAG.getTarget().Options.UnsafeFPMath)
9507     return SDValue();
9508 
9509   SDValue N0 = N->getOperand(0);
9510   if (TLI.isFsqrtCheap(N0, DAG))
9511     return SDValue();
9512 
9513   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9514   // For now, create a Flags object for use with all unsafe math transforms.
9515   SDNodeFlags Flags;
9516   Flags.setUnsafeAlgebra(true);
9517   return buildSqrtEstimate(N0, &Flags);
9518 }
9519 
9520 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9521 /// copysign(x, fp_round(y)) -> copysign(x, y)
9522 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9523   SDValue N1 = N->getOperand(1);
9524   if ((N1.getOpcode() == ISD::FP_EXTEND ||
9525        N1.getOpcode() == ISD::FP_ROUND)) {
9526     // Do not optimize out type conversion of f128 type yet.
9527     // For some targets like x86_64, configuration is changed to keep one f128
9528     // value in one SSE register, but instruction selection cannot handle
9529     // FCOPYSIGN on SSE registers yet.
9530     EVT N1VT = N1->getValueType(0);
9531     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9532     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9533   }
9534   return false;
9535 }
9536 
9537 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9538   SDValue N0 = N->getOperand(0);
9539   SDValue N1 = N->getOperand(1);
9540   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9541   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9542   EVT VT = N->getValueType(0);
9543 
9544   if (N0CFP && N1CFP) // Constant fold
9545     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9546 
9547   if (N1CFP) {
9548     const APFloat &V = N1CFP->getValueAPF();
9549     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
9550     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9551     if (!V.isNegative()) {
9552       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9553         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9554     } else {
9555       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9556         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9557                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9558     }
9559   }
9560 
9561   // copysign(fabs(x), y) -> copysign(x, y)
9562   // copysign(fneg(x), y) -> copysign(x, y)
9563   // copysign(copysign(x,z), y) -> copysign(x, y)
9564   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9565       N0.getOpcode() == ISD::FCOPYSIGN)
9566     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9567 
9568   // copysign(x, abs(y)) -> abs(x)
9569   if (N1.getOpcode() == ISD::FABS)
9570     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9571 
9572   // copysign(x, copysign(y,z)) -> copysign(x, z)
9573   if (N1.getOpcode() == ISD::FCOPYSIGN)
9574     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9575 
9576   // copysign(x, fp_extend(y)) -> copysign(x, y)
9577   // copysign(x, fp_round(y)) -> copysign(x, y)
9578   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9579     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9580 
9581   return SDValue();
9582 }
9583 
9584 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9585   SDValue N0 = N->getOperand(0);
9586   EVT VT = N->getValueType(0);
9587   EVT OpVT = N0.getValueType();
9588 
9589   // fold (sint_to_fp c1) -> c1fp
9590   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9591       // ...but only if the target supports immediate floating-point values
9592       (!LegalOperations ||
9593        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9594     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9595 
9596   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9597   // but UINT_TO_FP is legal on this target, try to convert.
9598   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9599       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9600     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9601     if (DAG.SignBitIsZero(N0))
9602       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9603   }
9604 
9605   // The next optimizations are desirable only if SELECT_CC can be lowered.
9606   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9607     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9608     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9609         !VT.isVector() &&
9610         (!LegalOperations ||
9611          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9612       SDLoc DL(N);
9613       SDValue Ops[] =
9614         { N0.getOperand(0), N0.getOperand(1),
9615           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9616           N0.getOperand(2) };
9617       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9618     }
9619 
9620     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9621     //      (select_cc x, y, 1.0, 0.0,, cc)
9622     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9623         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9624         (!LegalOperations ||
9625          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9626       SDLoc DL(N);
9627       SDValue Ops[] =
9628         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9629           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9630           N0.getOperand(0).getOperand(2) };
9631       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9632     }
9633   }
9634 
9635   return SDValue();
9636 }
9637 
9638 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9639   SDValue N0 = N->getOperand(0);
9640   EVT VT = N->getValueType(0);
9641   EVT OpVT = N0.getValueType();
9642 
9643   // fold (uint_to_fp c1) -> c1fp
9644   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9645       // ...but only if the target supports immediate floating-point values
9646       (!LegalOperations ||
9647        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9648     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9649 
9650   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9651   // but SINT_TO_FP is legal on this target, try to convert.
9652   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9653       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9654     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9655     if (DAG.SignBitIsZero(N0))
9656       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9657   }
9658 
9659   // The next optimizations are desirable only if SELECT_CC can be lowered.
9660   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9661     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9662 
9663     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9664         (!LegalOperations ||
9665          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9666       SDLoc DL(N);
9667       SDValue Ops[] =
9668         { N0.getOperand(0), N0.getOperand(1),
9669           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9670           N0.getOperand(2) };
9671       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9672     }
9673   }
9674 
9675   return SDValue();
9676 }
9677 
9678 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9679 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9680   SDValue N0 = N->getOperand(0);
9681   EVT VT = N->getValueType(0);
9682 
9683   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9684     return SDValue();
9685 
9686   SDValue Src = N0.getOperand(0);
9687   EVT SrcVT = Src.getValueType();
9688   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9689   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9690 
9691   // We can safely assume the conversion won't overflow the output range,
9692   // because (for example) (uint8_t)18293.f is undefined behavior.
9693 
9694   // Since we can assume the conversion won't overflow, our decision as to
9695   // whether the input will fit in the float should depend on the minimum
9696   // of the input range and output range.
9697 
9698   // This means this is also safe for a signed input and unsigned output, since
9699   // a negative input would lead to undefined behavior.
9700   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9701   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9702   unsigned ActualSize = std::min(InputSize, OutputSize);
9703   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9704 
9705   // We can only fold away the float conversion if the input range can be
9706   // represented exactly in the float range.
9707   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9708     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9709       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9710                                                        : ISD::ZERO_EXTEND;
9711       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9712     }
9713     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9714       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9715     return DAG.getBitcast(VT, Src);
9716   }
9717   return SDValue();
9718 }
9719 
9720 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9721   SDValue N0 = N->getOperand(0);
9722   EVT VT = N->getValueType(0);
9723 
9724   // fold (fp_to_sint c1fp) -> c1
9725   if (isConstantFPBuildVectorOrConstantFP(N0))
9726     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9727 
9728   return FoldIntToFPToInt(N, DAG);
9729 }
9730 
9731 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9732   SDValue N0 = N->getOperand(0);
9733   EVT VT = N->getValueType(0);
9734 
9735   // fold (fp_to_uint c1fp) -> c1
9736   if (isConstantFPBuildVectorOrConstantFP(N0))
9737     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9738 
9739   return FoldIntToFPToInt(N, DAG);
9740 }
9741 
9742 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9743   SDValue N0 = N->getOperand(0);
9744   SDValue N1 = N->getOperand(1);
9745   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9746   EVT VT = N->getValueType(0);
9747 
9748   // fold (fp_round c1fp) -> c1fp
9749   if (N0CFP)
9750     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9751 
9752   // fold (fp_round (fp_extend x)) -> x
9753   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9754     return N0.getOperand(0);
9755 
9756   // fold (fp_round (fp_round x)) -> (fp_round x)
9757   if (N0.getOpcode() == ISD::FP_ROUND) {
9758     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9759     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
9760 
9761     // Skip this folding if it results in an fp_round from f80 to f16.
9762     //
9763     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9764     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9765     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9766     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9767     // x86.
9768     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9769       return SDValue();
9770 
9771     // If the first fp_round isn't a value preserving truncation, it might
9772     // introduce a tie in the second fp_round, that wouldn't occur in the
9773     // single-step fp_round we want to fold to.
9774     // In other words, double rounding isn't the same as rounding.
9775     // Also, this is a value preserving truncation iff both fp_round's are.
9776     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9777       SDLoc DL(N);
9778       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9779                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9780     }
9781   }
9782 
9783   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9784   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9785     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9786                               N0.getOperand(0), N1);
9787     AddToWorklist(Tmp.getNode());
9788     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9789                        Tmp, N0.getOperand(1));
9790   }
9791 
9792   return SDValue();
9793 }
9794 
9795 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9796   SDValue N0 = N->getOperand(0);
9797   EVT VT = N->getValueType(0);
9798   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9799   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9800 
9801   // fold (fp_round_inreg c1fp) -> c1fp
9802   if (N0CFP && isTypeLegal(EVT)) {
9803     SDLoc DL(N);
9804     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9805     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9806   }
9807 
9808   return SDValue();
9809 }
9810 
9811 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9812   SDValue N0 = N->getOperand(0);
9813   EVT VT = N->getValueType(0);
9814 
9815   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9816   if (N->hasOneUse() &&
9817       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9818     return SDValue();
9819 
9820   // fold (fp_extend c1fp) -> c1fp
9821   if (isConstantFPBuildVectorOrConstantFP(N0))
9822     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9823 
9824   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9825   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9826       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9827     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9828 
9829   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9830   // value of X.
9831   if (N0.getOpcode() == ISD::FP_ROUND
9832       && N0.getConstantOperandVal(1) == 1) {
9833     SDValue In = N0.getOperand(0);
9834     if (In.getValueType() == VT) return In;
9835     if (VT.bitsLT(In.getValueType()))
9836       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9837                          In, N0.getOperand(1));
9838     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9839   }
9840 
9841   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9842   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9843        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9844     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9845     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9846                                      LN0->getChain(),
9847                                      LN0->getBasePtr(), N0.getValueType(),
9848                                      LN0->getMemOperand());
9849     CombineTo(N, ExtLoad);
9850     CombineTo(N0.getNode(),
9851               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9852                           N0.getValueType(), ExtLoad,
9853                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9854               ExtLoad.getValue(1));
9855     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9856   }
9857 
9858   return SDValue();
9859 }
9860 
9861 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9862   SDValue N0 = N->getOperand(0);
9863   EVT VT = N->getValueType(0);
9864 
9865   // fold (fceil c1) -> fceil(c1)
9866   if (isConstantFPBuildVectorOrConstantFP(N0))
9867     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9868 
9869   return SDValue();
9870 }
9871 
9872 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9873   SDValue N0 = N->getOperand(0);
9874   EVT VT = N->getValueType(0);
9875 
9876   // fold (ftrunc c1) -> ftrunc(c1)
9877   if (isConstantFPBuildVectorOrConstantFP(N0))
9878     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9879 
9880   return SDValue();
9881 }
9882 
9883 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9884   SDValue N0 = N->getOperand(0);
9885   EVT VT = N->getValueType(0);
9886 
9887   // fold (ffloor c1) -> ffloor(c1)
9888   if (isConstantFPBuildVectorOrConstantFP(N0))
9889     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9890 
9891   return SDValue();
9892 }
9893 
9894 // FIXME: FNEG and FABS have a lot in common; refactor.
9895 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9896   SDValue N0 = N->getOperand(0);
9897   EVT VT = N->getValueType(0);
9898 
9899   // Constant fold FNEG.
9900   if (isConstantFPBuildVectorOrConstantFP(N0))
9901     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9902 
9903   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9904                          &DAG.getTarget().Options))
9905     return GetNegatedExpression(N0, DAG, LegalOperations);
9906 
9907   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9908   // constant pool values.
9909   if (!TLI.isFNegFree(VT) &&
9910       N0.getOpcode() == ISD::BITCAST &&
9911       N0.getNode()->hasOneUse()) {
9912     SDValue Int = N0.getOperand(0);
9913     EVT IntVT = Int.getValueType();
9914     if (IntVT.isInteger() && !IntVT.isVector()) {
9915       APInt SignMask;
9916       if (N0.getValueType().isVector()) {
9917         // For a vector, get a mask such as 0x80... per scalar element
9918         // and splat it.
9919         SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits());
9920         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9921       } else {
9922         // For a scalar, just generate 0x80...
9923         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9924       }
9925       SDLoc DL0(N0);
9926       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9927                         DAG.getConstant(SignMask, DL0, IntVT));
9928       AddToWorklist(Int.getNode());
9929       return DAG.getBitcast(VT, Int);
9930     }
9931   }
9932 
9933   // (fneg (fmul c, x)) -> (fmul -c, x)
9934   if (N0.getOpcode() == ISD::FMUL &&
9935       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9936     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9937     if (CFP1) {
9938       APFloat CVal = CFP1->getValueAPF();
9939       CVal.changeSign();
9940       if (Level >= AfterLegalizeDAG &&
9941           (TLI.isFPImmLegal(CVal, VT) ||
9942            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9943         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9944                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9945                                        N0.getOperand(1)),
9946                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9947     }
9948   }
9949 
9950   return SDValue();
9951 }
9952 
9953 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9954   SDValue N0 = N->getOperand(0);
9955   SDValue N1 = N->getOperand(1);
9956   EVT VT = N->getValueType(0);
9957   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9958   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9959 
9960   if (N0CFP && N1CFP) {
9961     const APFloat &C0 = N0CFP->getValueAPF();
9962     const APFloat &C1 = N1CFP->getValueAPF();
9963     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9964   }
9965 
9966   // Canonicalize to constant on RHS.
9967   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9968      !isConstantFPBuildVectorOrConstantFP(N1))
9969     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9970 
9971   return SDValue();
9972 }
9973 
9974 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9975   SDValue N0 = N->getOperand(0);
9976   SDValue N1 = N->getOperand(1);
9977   EVT VT = N->getValueType(0);
9978   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9979   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9980 
9981   if (N0CFP && N1CFP) {
9982     const APFloat &C0 = N0CFP->getValueAPF();
9983     const APFloat &C1 = N1CFP->getValueAPF();
9984     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9985   }
9986 
9987   // Canonicalize to constant on RHS.
9988   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9989      !isConstantFPBuildVectorOrConstantFP(N1))
9990     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9991 
9992   return SDValue();
9993 }
9994 
9995 SDValue DAGCombiner::visitFABS(SDNode *N) {
9996   SDValue N0 = N->getOperand(0);
9997   EVT VT = N->getValueType(0);
9998 
9999   // fold (fabs c1) -> fabs(c1)
10000   if (isConstantFPBuildVectorOrConstantFP(N0))
10001     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10002 
10003   // fold (fabs (fabs x)) -> (fabs x)
10004   if (N0.getOpcode() == ISD::FABS)
10005     return N->getOperand(0);
10006 
10007   // fold (fabs (fneg x)) -> (fabs x)
10008   // fold (fabs (fcopysign x, y)) -> (fabs x)
10009   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10010     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10011 
10012   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10013   // constant pool values.
10014   if (!TLI.isFAbsFree(VT) &&
10015       N0.getOpcode() == ISD::BITCAST &&
10016       N0.getNode()->hasOneUse()) {
10017     SDValue Int = N0.getOperand(0);
10018     EVT IntVT = Int.getValueType();
10019     if (IntVT.isInteger() && !IntVT.isVector()) {
10020       APInt SignMask;
10021       if (N0.getValueType().isVector()) {
10022         // For a vector, get a mask such as 0x7f... per scalar element
10023         // and splat it.
10024         SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits());
10025         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10026       } else {
10027         // For a scalar, just generate 0x7f...
10028         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
10029       }
10030       SDLoc DL(N0);
10031       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10032                         DAG.getConstant(SignMask, DL, IntVT));
10033       AddToWorklist(Int.getNode());
10034       return DAG.getBitcast(N->getValueType(0), Int);
10035     }
10036   }
10037 
10038   return SDValue();
10039 }
10040 
10041 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10042   SDValue Chain = N->getOperand(0);
10043   SDValue N1 = N->getOperand(1);
10044   SDValue N2 = N->getOperand(2);
10045 
10046   // If N is a constant we could fold this into a fallthrough or unconditional
10047   // branch. However that doesn't happen very often in normal code, because
10048   // Instcombine/SimplifyCFG should have handled the available opportunities.
10049   // If we did this folding here, it would be necessary to update the
10050   // MachineBasicBlock CFG, which is awkward.
10051 
10052   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10053   // on the target.
10054   if (N1.getOpcode() == ISD::SETCC &&
10055       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10056                                    N1.getOperand(0).getValueType())) {
10057     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10058                        Chain, N1.getOperand(2),
10059                        N1.getOperand(0), N1.getOperand(1), N2);
10060   }
10061 
10062   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10063       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10064        (N1.getOperand(0).hasOneUse() &&
10065         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10066     SDNode *Trunc = nullptr;
10067     if (N1.getOpcode() == ISD::TRUNCATE) {
10068       // Look pass the truncate.
10069       Trunc = N1.getNode();
10070       N1 = N1.getOperand(0);
10071     }
10072 
10073     // Match this pattern so that we can generate simpler code:
10074     //
10075     //   %a = ...
10076     //   %b = and i32 %a, 2
10077     //   %c = srl i32 %b, 1
10078     //   brcond i32 %c ...
10079     //
10080     // into
10081     //
10082     //   %a = ...
10083     //   %b = and i32 %a, 2
10084     //   %c = setcc eq %b, 0
10085     //   brcond %c ...
10086     //
10087     // This applies only when the AND constant value has one bit set and the
10088     // SRL constant is equal to the log2 of the AND constant. The back-end is
10089     // smart enough to convert the result into a TEST/JMP sequence.
10090     SDValue Op0 = N1.getOperand(0);
10091     SDValue Op1 = N1.getOperand(1);
10092 
10093     if (Op0.getOpcode() == ISD::AND &&
10094         Op1.getOpcode() == ISD::Constant) {
10095       SDValue AndOp1 = Op0.getOperand(1);
10096 
10097       if (AndOp1.getOpcode() == ISD::Constant) {
10098         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10099 
10100         if (AndConst.isPowerOf2() &&
10101             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10102           SDLoc DL(N);
10103           SDValue SetCC =
10104             DAG.getSetCC(DL,
10105                          getSetCCResultType(Op0.getValueType()),
10106                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10107                          ISD::SETNE);
10108 
10109           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10110                                           MVT::Other, Chain, SetCC, N2);
10111           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10112           // will convert it back to (X & C1) >> C2.
10113           CombineTo(N, NewBRCond, false);
10114           // Truncate is dead.
10115           if (Trunc)
10116             deleteAndRecombine(Trunc);
10117           // Replace the uses of SRL with SETCC
10118           WorklistRemover DeadNodes(*this);
10119           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10120           deleteAndRecombine(N1.getNode());
10121           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10122         }
10123       }
10124     }
10125 
10126     if (Trunc)
10127       // Restore N1 if the above transformation doesn't match.
10128       N1 = N->getOperand(1);
10129   }
10130 
10131   // Transform br(xor(x, y)) -> br(x != y)
10132   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10133   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10134     SDNode *TheXor = N1.getNode();
10135     SDValue Op0 = TheXor->getOperand(0);
10136     SDValue Op1 = TheXor->getOperand(1);
10137     if (Op0.getOpcode() == Op1.getOpcode()) {
10138       // Avoid missing important xor optimizations.
10139       if (SDValue Tmp = visitXOR(TheXor)) {
10140         if (Tmp.getNode() != TheXor) {
10141           DEBUG(dbgs() << "\nReplacing.8 ";
10142                 TheXor->dump(&DAG);
10143                 dbgs() << "\nWith: ";
10144                 Tmp.getNode()->dump(&DAG);
10145                 dbgs() << '\n');
10146           WorklistRemover DeadNodes(*this);
10147           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10148           deleteAndRecombine(TheXor);
10149           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10150                              MVT::Other, Chain, Tmp, N2);
10151         }
10152 
10153         // visitXOR has changed XOR's operands or replaced the XOR completely,
10154         // bail out.
10155         return SDValue(N, 0);
10156       }
10157     }
10158 
10159     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10160       bool Equal = false;
10161       if (isOneConstant(Op0) && Op0.hasOneUse() &&
10162           Op0.getOpcode() == ISD::XOR) {
10163         TheXor = Op0.getNode();
10164         Equal = true;
10165       }
10166 
10167       EVT SetCCVT = N1.getValueType();
10168       if (LegalTypes)
10169         SetCCVT = getSetCCResultType(SetCCVT);
10170       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10171                                    SetCCVT,
10172                                    Op0, Op1,
10173                                    Equal ? ISD::SETEQ : ISD::SETNE);
10174       // Replace the uses of XOR with SETCC
10175       WorklistRemover DeadNodes(*this);
10176       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10177       deleteAndRecombine(N1.getNode());
10178       return DAG.getNode(ISD::BRCOND, SDLoc(N),
10179                          MVT::Other, Chain, SetCC, N2);
10180     }
10181   }
10182 
10183   return SDValue();
10184 }
10185 
10186 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10187 //
10188 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10189   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10190   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10191 
10192   // If N is a constant we could fold this into a fallthrough or unconditional
10193   // branch. However that doesn't happen very often in normal code, because
10194   // Instcombine/SimplifyCFG should have handled the available opportunities.
10195   // If we did this folding here, it would be necessary to update the
10196   // MachineBasicBlock CFG, which is awkward.
10197 
10198   // Use SimplifySetCC to simplify SETCC's.
10199   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10200                                CondLHS, CondRHS, CC->get(), SDLoc(N),
10201                                false);
10202   if (Simp.getNode()) AddToWorklist(Simp.getNode());
10203 
10204   // fold to a simpler setcc
10205   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10206     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10207                        N->getOperand(0), Simp.getOperand(2),
10208                        Simp.getOperand(0), Simp.getOperand(1),
10209                        N->getOperand(4));
10210 
10211   return SDValue();
10212 }
10213 
10214 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10215 /// and that N may be folded in the load / store addressing mode.
10216 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10217                                     SelectionDAG &DAG,
10218                                     const TargetLowering &TLI) {
10219   EVT VT;
10220   unsigned AS;
10221 
10222   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
10223     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10224       return false;
10225     VT = LD->getMemoryVT();
10226     AS = LD->getAddressSpace();
10227   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
10228     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10229       return false;
10230     VT = ST->getMemoryVT();
10231     AS = ST->getAddressSpace();
10232   } else
10233     return false;
10234 
10235   TargetLowering::AddrMode AM;
10236   if (N->getOpcode() == ISD::ADD) {
10237     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10238     if (Offset)
10239       // [reg +/- imm]
10240       AM.BaseOffs = Offset->getSExtValue();
10241     else
10242       // [reg +/- reg]
10243       AM.Scale = 1;
10244   } else if (N->getOpcode() == ISD::SUB) {
10245     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10246     if (Offset)
10247       // [reg +/- imm]
10248       AM.BaseOffs = -Offset->getSExtValue();
10249     else
10250       // [reg +/- reg]
10251       AM.Scale = 1;
10252   } else
10253     return false;
10254 
10255   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10256                                    VT.getTypeForEVT(*DAG.getContext()), AS);
10257 }
10258 
10259 /// Try turning a load/store into a pre-indexed load/store when the base
10260 /// pointer is an add or subtract and it has other uses besides the load/store.
10261 /// After the transformation, the new indexed load/store has effectively folded
10262 /// the add/subtract in and all of its other uses are redirected to the
10263 /// new load/store.
10264 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10265   if (Level < AfterLegalizeDAG)
10266     return false;
10267 
10268   bool isLoad = true;
10269   SDValue Ptr;
10270   EVT VT;
10271   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10272     if (LD->isIndexed())
10273       return false;
10274     VT = LD->getMemoryVT();
10275     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10276         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10277       return false;
10278     Ptr = LD->getBasePtr();
10279   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10280     if (ST->isIndexed())
10281       return false;
10282     VT = ST->getMemoryVT();
10283     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10284         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10285       return false;
10286     Ptr = ST->getBasePtr();
10287     isLoad = false;
10288   } else {
10289     return false;
10290   }
10291 
10292   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10293   // out.  There is no reason to make this a preinc/predec.
10294   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10295       Ptr.getNode()->hasOneUse())
10296     return false;
10297 
10298   // Ask the target to do addressing mode selection.
10299   SDValue BasePtr;
10300   SDValue Offset;
10301   ISD::MemIndexedMode AM = ISD::UNINDEXED;
10302   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10303     return false;
10304 
10305   // Backends without true r+i pre-indexed forms may need to pass a
10306   // constant base with a variable offset so that constant coercion
10307   // will work with the patterns in canonical form.
10308   bool Swapped = false;
10309   if (isa<ConstantSDNode>(BasePtr)) {
10310     std::swap(BasePtr, Offset);
10311     Swapped = true;
10312   }
10313 
10314   // Don't create a indexed load / store with zero offset.
10315   if (isNullConstant(Offset))
10316     return false;
10317 
10318   // Try turning it into a pre-indexed load / store except when:
10319   // 1) The new base ptr is a frame index.
10320   // 2) If N is a store and the new base ptr is either the same as or is a
10321   //    predecessor of the value being stored.
10322   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10323   //    that would create a cycle.
10324   // 4) All uses are load / store ops that use it as old base ptr.
10325 
10326   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
10327   // (plus the implicit offset) to a register to preinc anyway.
10328   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10329     return false;
10330 
10331   // Check #2.
10332   if (!isLoad) {
10333     SDValue Val = cast<StoreSDNode>(N)->getValue();
10334     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
10335       return false;
10336   }
10337 
10338   // Caches for hasPredecessorHelper.
10339   SmallPtrSet<const SDNode *, 32> Visited;
10340   SmallVector<const SDNode *, 16> Worklist;
10341   Worklist.push_back(N);
10342 
10343   // If the offset is a constant, there may be other adds of constants that
10344   // can be folded with this one. We should do this to avoid having to keep
10345   // a copy of the original base pointer.
10346   SmallVector<SDNode *, 16> OtherUses;
10347   if (isa<ConstantSDNode>(Offset))
10348     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
10349                               UE = BasePtr.getNode()->use_end();
10350          UI != UE; ++UI) {
10351       SDUse &Use = UI.getUse();
10352       // Skip the use that is Ptr and uses of other results from BasePtr's
10353       // node (important for nodes that return multiple results).
10354       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
10355         continue;
10356 
10357       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
10358         continue;
10359 
10360       if (Use.getUser()->getOpcode() != ISD::ADD &&
10361           Use.getUser()->getOpcode() != ISD::SUB) {
10362         OtherUses.clear();
10363         break;
10364       }
10365 
10366       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
10367       if (!isa<ConstantSDNode>(Op1)) {
10368         OtherUses.clear();
10369         break;
10370       }
10371 
10372       // FIXME: In some cases, we can be smarter about this.
10373       if (Op1.getValueType() != Offset.getValueType()) {
10374         OtherUses.clear();
10375         break;
10376       }
10377 
10378       OtherUses.push_back(Use.getUser());
10379     }
10380 
10381   if (Swapped)
10382     std::swap(BasePtr, Offset);
10383 
10384   // Now check for #3 and #4.
10385   bool RealUse = false;
10386 
10387   for (SDNode *Use : Ptr.getNode()->uses()) {
10388     if (Use == N)
10389       continue;
10390     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
10391       return false;
10392 
10393     // If Ptr may be folded in addressing mode of other use, then it's
10394     // not profitable to do this transformation.
10395     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
10396       RealUse = true;
10397   }
10398 
10399   if (!RealUse)
10400     return false;
10401 
10402   SDValue Result;
10403   if (isLoad)
10404     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10405                                 BasePtr, Offset, AM);
10406   else
10407     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10408                                  BasePtr, Offset, AM);
10409   ++PreIndexedNodes;
10410   ++NodesCombined;
10411   DEBUG(dbgs() << "\nReplacing.4 ";
10412         N->dump(&DAG);
10413         dbgs() << "\nWith: ";
10414         Result.getNode()->dump(&DAG);
10415         dbgs() << '\n');
10416   WorklistRemover DeadNodes(*this);
10417   if (isLoad) {
10418     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10419     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10420   } else {
10421     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10422   }
10423 
10424   // Finally, since the node is now dead, remove it from the graph.
10425   deleteAndRecombine(N);
10426 
10427   if (Swapped)
10428     std::swap(BasePtr, Offset);
10429 
10430   // Replace other uses of BasePtr that can be updated to use Ptr
10431   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
10432     unsigned OffsetIdx = 1;
10433     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
10434       OffsetIdx = 0;
10435     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10436            BasePtr.getNode() && "Expected BasePtr operand");
10437 
10438     // We need to replace ptr0 in the following expression:
10439     //   x0 * offset0 + y0 * ptr0 = t0
10440     // knowing that
10441     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10442     //
10443     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10444     // indexed load/store and the expresion that needs to be re-written.
10445     //
10446     // Therefore, we have:
10447     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10448 
10449     ConstantSDNode *CN =
10450       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
10451     int X0, X1, Y0, Y1;
10452     const APInt &Offset0 = CN->getAPIntValue();
10453     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10454 
10455     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10456     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10457     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10458     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10459 
10460     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10461 
10462     APInt CNV = Offset0;
10463     if (X0 < 0) CNV = -CNV;
10464     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10465     else CNV = CNV - Offset1;
10466 
10467     SDLoc DL(OtherUses[i]);
10468 
10469     // We can now generate the new expression.
10470     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10471     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10472 
10473     SDValue NewUse = DAG.getNode(Opcode,
10474                                  DL,
10475                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10476     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10477     deleteAndRecombine(OtherUses[i]);
10478   }
10479 
10480   // Replace the uses of Ptr with uses of the updated base value.
10481   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10482   deleteAndRecombine(Ptr.getNode());
10483 
10484   return true;
10485 }
10486 
10487 /// Try to combine a load/store with a add/sub of the base pointer node into a
10488 /// post-indexed load/store. The transformation folded the add/subtract into the
10489 /// new indexed load/store effectively and all of its uses are redirected to the
10490 /// new load/store.
10491 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10492   if (Level < AfterLegalizeDAG)
10493     return false;
10494 
10495   bool isLoad = true;
10496   SDValue Ptr;
10497   EVT VT;
10498   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10499     if (LD->isIndexed())
10500       return false;
10501     VT = LD->getMemoryVT();
10502     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10503         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10504       return false;
10505     Ptr = LD->getBasePtr();
10506   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10507     if (ST->isIndexed())
10508       return false;
10509     VT = ST->getMemoryVT();
10510     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10511         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10512       return false;
10513     Ptr = ST->getBasePtr();
10514     isLoad = false;
10515   } else {
10516     return false;
10517   }
10518 
10519   if (Ptr.getNode()->hasOneUse())
10520     return false;
10521 
10522   for (SDNode *Op : Ptr.getNode()->uses()) {
10523     if (Op == N ||
10524         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10525       continue;
10526 
10527     SDValue BasePtr;
10528     SDValue Offset;
10529     ISD::MemIndexedMode AM = ISD::UNINDEXED;
10530     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10531       // Don't create a indexed load / store with zero offset.
10532       if (isNullConstant(Offset))
10533         continue;
10534 
10535       // Try turning it into a post-indexed load / store except when
10536       // 1) All uses are load / store ops that use it as base ptr (and
10537       //    it may be folded as addressing mmode).
10538       // 2) Op must be independent of N, i.e. Op is neither a predecessor
10539       //    nor a successor of N. Otherwise, if Op is folded that would
10540       //    create a cycle.
10541 
10542       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10543         continue;
10544 
10545       // Check for #1.
10546       bool TryNext = false;
10547       for (SDNode *Use : BasePtr.getNode()->uses()) {
10548         if (Use == Ptr.getNode())
10549           continue;
10550 
10551         // If all the uses are load / store addresses, then don't do the
10552         // transformation.
10553         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10554           bool RealUse = false;
10555           for (SDNode *UseUse : Use->uses()) {
10556             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10557               RealUse = true;
10558           }
10559 
10560           if (!RealUse) {
10561             TryNext = true;
10562             break;
10563           }
10564         }
10565       }
10566 
10567       if (TryNext)
10568         continue;
10569 
10570       // Check for #2
10571       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10572         SDValue Result = isLoad
10573           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10574                                BasePtr, Offset, AM)
10575           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10576                                 BasePtr, Offset, AM);
10577         ++PostIndexedNodes;
10578         ++NodesCombined;
10579         DEBUG(dbgs() << "\nReplacing.5 ";
10580               N->dump(&DAG);
10581               dbgs() << "\nWith: ";
10582               Result.getNode()->dump(&DAG);
10583               dbgs() << '\n');
10584         WorklistRemover DeadNodes(*this);
10585         if (isLoad) {
10586           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10587           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10588         } else {
10589           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10590         }
10591 
10592         // Finally, since the node is now dead, remove it from the graph.
10593         deleteAndRecombine(N);
10594 
10595         // Replace the uses of Use with uses of the updated base value.
10596         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10597                                       Result.getValue(isLoad ? 1 : 0));
10598         deleteAndRecombine(Op);
10599         return true;
10600       }
10601     }
10602   }
10603 
10604   return false;
10605 }
10606 
10607 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10608 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10609   ISD::MemIndexedMode AM = LD->getAddressingMode();
10610   assert(AM != ISD::UNINDEXED);
10611   SDValue BP = LD->getOperand(1);
10612   SDValue Inc = LD->getOperand(2);
10613 
10614   // Some backends use TargetConstants for load offsets, but don't expect
10615   // TargetConstants in general ADD nodes. We can convert these constants into
10616   // regular Constants (if the constant is not opaque).
10617   assert((Inc.getOpcode() != ISD::TargetConstant ||
10618           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10619          "Cannot split out indexing using opaque target constants");
10620   if (Inc.getOpcode() == ISD::TargetConstant) {
10621     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10622     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10623                           ConstInc->getValueType(0));
10624   }
10625 
10626   unsigned Opc =
10627       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10628   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10629 }
10630 
10631 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10632   LoadSDNode *LD  = cast<LoadSDNode>(N);
10633   SDValue Chain = LD->getChain();
10634   SDValue Ptr   = LD->getBasePtr();
10635 
10636   // If load is not volatile and there are no uses of the loaded value (and
10637   // the updated indexed value in case of indexed loads), change uses of the
10638   // chain value into uses of the chain input (i.e. delete the dead load).
10639   if (!LD->isVolatile()) {
10640     if (N->getValueType(1) == MVT::Other) {
10641       // Unindexed loads.
10642       if (!N->hasAnyUseOfValue(0)) {
10643         // It's not safe to use the two value CombineTo variant here. e.g.
10644         // v1, chain2 = load chain1, loc
10645         // v2, chain3 = load chain2, loc
10646         // v3         = add v2, c
10647         // Now we replace use of chain2 with chain1.  This makes the second load
10648         // isomorphic to the one we are deleting, and thus makes this load live.
10649         DEBUG(dbgs() << "\nReplacing.6 ";
10650               N->dump(&DAG);
10651               dbgs() << "\nWith chain: ";
10652               Chain.getNode()->dump(&DAG);
10653               dbgs() << "\n");
10654         WorklistRemover DeadNodes(*this);
10655         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10656 
10657         if (N->use_empty())
10658           deleteAndRecombine(N);
10659 
10660         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10661       }
10662     } else {
10663       // Indexed loads.
10664       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10665 
10666       // If this load has an opaque TargetConstant offset, then we cannot split
10667       // the indexing into an add/sub directly (that TargetConstant may not be
10668       // valid for a different type of node, and we cannot convert an opaque
10669       // target constant into a regular constant).
10670       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10671                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10672 
10673       if (!N->hasAnyUseOfValue(0) &&
10674           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10675         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10676         SDValue Index;
10677         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10678           Index = SplitIndexingFromLoad(LD);
10679           // Try to fold the base pointer arithmetic into subsequent loads and
10680           // stores.
10681           AddUsersToWorklist(N);
10682         } else
10683           Index = DAG.getUNDEF(N->getValueType(1));
10684         DEBUG(dbgs() << "\nReplacing.7 ";
10685               N->dump(&DAG);
10686               dbgs() << "\nWith: ";
10687               Undef.getNode()->dump(&DAG);
10688               dbgs() << " and 2 other values\n");
10689         WorklistRemover DeadNodes(*this);
10690         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10691         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10692         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10693         deleteAndRecombine(N);
10694         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10695       }
10696     }
10697   }
10698 
10699   // If this load is directly stored, replace the load value with the stored
10700   // value.
10701   // TODO: Handle store large -> read small portion.
10702   // TODO: Handle TRUNCSTORE/LOADEXT
10703   if (OptLevel != CodeGenOpt::None &&
10704       ISD::isNormalLoad(N) && !LD->isVolatile()) {
10705     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10706       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10707       if (PrevST->getBasePtr() == Ptr &&
10708           PrevST->getValue().getValueType() == N->getValueType(0))
10709       return CombineTo(N, Chain.getOperand(1), Chain);
10710     }
10711   }
10712 
10713   // Try to infer better alignment information than the load already has.
10714   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10715     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10716       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10717         SDValue NewLoad = DAG.getExtLoad(
10718             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10719             LD->getPointerInfo(), LD->getMemoryVT(), Align,
10720             LD->getMemOperand()->getFlags(), LD->getAAInfo());
10721         if (NewLoad.getNode() != N)
10722           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10723       }
10724     }
10725   }
10726 
10727   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10728                                                   : DAG.getSubtarget().useAA();
10729 #ifndef NDEBUG
10730   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10731       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10732     UseAA = false;
10733 #endif
10734   if (UseAA && LD->isUnindexed()) {
10735     // Walk up chain skipping non-aliasing memory nodes.
10736     SDValue BetterChain = FindBetterChain(N, Chain);
10737 
10738     // If there is a better chain.
10739     if (Chain != BetterChain) {
10740       SDValue ReplLoad;
10741 
10742       // Replace the chain to void dependency.
10743       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10744         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10745                                BetterChain, Ptr, LD->getMemOperand());
10746       } else {
10747         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10748                                   LD->getValueType(0),
10749                                   BetterChain, Ptr, LD->getMemoryVT(),
10750                                   LD->getMemOperand());
10751       }
10752 
10753       // Create token factor to keep old chain connected.
10754       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10755                                   MVT::Other, Chain, ReplLoad.getValue(1));
10756 
10757       // Make sure the new and old chains are cleaned up.
10758       AddToWorklist(Token.getNode());
10759 
10760       // Replace uses with load result and token factor. Don't add users
10761       // to work list.
10762       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10763     }
10764   }
10765 
10766   // Try transforming N to an indexed load.
10767   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10768     return SDValue(N, 0);
10769 
10770   // Try to slice up N to more direct loads if the slices are mapped to
10771   // different register banks or pairing can take place.
10772   if (SliceUpLoad(N))
10773     return SDValue(N, 0);
10774 
10775   return SDValue();
10776 }
10777 
10778 namespace {
10779 /// \brief Helper structure used to slice a load in smaller loads.
10780 /// Basically a slice is obtained from the following sequence:
10781 /// Origin = load Ty1, Base
10782 /// Shift = srl Ty1 Origin, CstTy Amount
10783 /// Inst = trunc Shift to Ty2
10784 ///
10785 /// Then, it will be rewriten into:
10786 /// Slice = load SliceTy, Base + SliceOffset
10787 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10788 ///
10789 /// SliceTy is deduced from the number of bits that are actually used to
10790 /// build Inst.
10791 struct LoadedSlice {
10792   /// \brief Helper structure used to compute the cost of a slice.
10793   struct Cost {
10794     /// Are we optimizing for code size.
10795     bool ForCodeSize;
10796     /// Various cost.
10797     unsigned Loads;
10798     unsigned Truncates;
10799     unsigned CrossRegisterBanksCopies;
10800     unsigned ZExts;
10801     unsigned Shift;
10802 
10803     Cost(bool ForCodeSize = false)
10804         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10805           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10806 
10807     /// \brief Get the cost of one isolated slice.
10808     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10809         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10810           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10811       EVT TruncType = LS.Inst->getValueType(0);
10812       EVT LoadedType = LS.getLoadedType();
10813       if (TruncType != LoadedType &&
10814           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10815         ZExts = 1;
10816     }
10817 
10818     /// \brief Account for slicing gain in the current cost.
10819     /// Slicing provide a few gains like removing a shift or a
10820     /// truncate. This method allows to grow the cost of the original
10821     /// load with the gain from this slice.
10822     void addSliceGain(const LoadedSlice &LS) {
10823       // Each slice saves a truncate.
10824       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10825       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10826                               LS.Inst->getValueType(0)))
10827         ++Truncates;
10828       // If there is a shift amount, this slice gets rid of it.
10829       if (LS.Shift)
10830         ++Shift;
10831       // If this slice can merge a cross register bank copy, account for it.
10832       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10833         ++CrossRegisterBanksCopies;
10834     }
10835 
10836     Cost &operator+=(const Cost &RHS) {
10837       Loads += RHS.Loads;
10838       Truncates += RHS.Truncates;
10839       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10840       ZExts += RHS.ZExts;
10841       Shift += RHS.Shift;
10842       return *this;
10843     }
10844 
10845     bool operator==(const Cost &RHS) const {
10846       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10847              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10848              ZExts == RHS.ZExts && Shift == RHS.Shift;
10849     }
10850 
10851     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10852 
10853     bool operator<(const Cost &RHS) const {
10854       // Assume cross register banks copies are as expensive as loads.
10855       // FIXME: Do we want some more target hooks?
10856       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10857       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10858       // Unless we are optimizing for code size, consider the
10859       // expensive operation first.
10860       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10861         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10862       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10863              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10864     }
10865 
10866     bool operator>(const Cost &RHS) const { return RHS < *this; }
10867 
10868     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10869 
10870     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10871   };
10872   // The last instruction that represent the slice. This should be a
10873   // truncate instruction.
10874   SDNode *Inst;
10875   // The original load instruction.
10876   LoadSDNode *Origin;
10877   // The right shift amount in bits from the original load.
10878   unsigned Shift;
10879   // The DAG from which Origin came from.
10880   // This is used to get some contextual information about legal types, etc.
10881   SelectionDAG *DAG;
10882 
10883   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10884               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10885       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10886 
10887   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10888   /// \return Result is \p BitWidth and has used bits set to 1 and
10889   ///         not used bits set to 0.
10890   APInt getUsedBits() const {
10891     // Reproduce the trunc(lshr) sequence:
10892     // - Start from the truncated value.
10893     // - Zero extend to the desired bit width.
10894     // - Shift left.
10895     assert(Origin && "No original load to compare against.");
10896     unsigned BitWidth = Origin->getValueSizeInBits(0);
10897     assert(Inst && "This slice is not bound to an instruction");
10898     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10899            "Extracted slice is bigger than the whole type!");
10900     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10901     UsedBits.setAllBits();
10902     UsedBits = UsedBits.zext(BitWidth);
10903     UsedBits <<= Shift;
10904     return UsedBits;
10905   }
10906 
10907   /// \brief Get the size of the slice to be loaded in bytes.
10908   unsigned getLoadedSize() const {
10909     unsigned SliceSize = getUsedBits().countPopulation();
10910     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10911     return SliceSize / 8;
10912   }
10913 
10914   /// \brief Get the type that will be loaded for this slice.
10915   /// Note: This may not be the final type for the slice.
10916   EVT getLoadedType() const {
10917     assert(DAG && "Missing context");
10918     LLVMContext &Ctxt = *DAG->getContext();
10919     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10920   }
10921 
10922   /// \brief Get the alignment of the load used for this slice.
10923   unsigned getAlignment() const {
10924     unsigned Alignment = Origin->getAlignment();
10925     unsigned Offset = getOffsetFromBase();
10926     if (Offset != 0)
10927       Alignment = MinAlign(Alignment, Alignment + Offset);
10928     return Alignment;
10929   }
10930 
10931   /// \brief Check if this slice can be rewritten with legal operations.
10932   bool isLegal() const {
10933     // An invalid slice is not legal.
10934     if (!Origin || !Inst || !DAG)
10935       return false;
10936 
10937     // Offsets are for indexed load only, we do not handle that.
10938     if (!Origin->getOffset().isUndef())
10939       return false;
10940 
10941     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10942 
10943     // Check that the type is legal.
10944     EVT SliceType = getLoadedType();
10945     if (!TLI.isTypeLegal(SliceType))
10946       return false;
10947 
10948     // Check that the load is legal for this type.
10949     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10950       return false;
10951 
10952     // Check that the offset can be computed.
10953     // 1. Check its type.
10954     EVT PtrType = Origin->getBasePtr().getValueType();
10955     if (PtrType == MVT::Untyped || PtrType.isExtended())
10956       return false;
10957 
10958     // 2. Check that it fits in the immediate.
10959     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10960       return false;
10961 
10962     // 3. Check that the computation is legal.
10963     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10964       return false;
10965 
10966     // Check that the zext is legal if it needs one.
10967     EVT TruncateType = Inst->getValueType(0);
10968     if (TruncateType != SliceType &&
10969         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10970       return false;
10971 
10972     return true;
10973   }
10974 
10975   /// \brief Get the offset in bytes of this slice in the original chunk of
10976   /// bits.
10977   /// \pre DAG != nullptr.
10978   uint64_t getOffsetFromBase() const {
10979     assert(DAG && "Missing context.");
10980     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10981     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10982     uint64_t Offset = Shift / 8;
10983     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10984     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10985            "The size of the original loaded type is not a multiple of a"
10986            " byte.");
10987     // If Offset is bigger than TySizeInBytes, it means we are loading all
10988     // zeros. This should have been optimized before in the process.
10989     assert(TySizeInBytes > Offset &&
10990            "Invalid shift amount for given loaded size");
10991     if (IsBigEndian)
10992       Offset = TySizeInBytes - Offset - getLoadedSize();
10993     return Offset;
10994   }
10995 
10996   /// \brief Generate the sequence of instructions to load the slice
10997   /// represented by this object and redirect the uses of this slice to
10998   /// this new sequence of instructions.
10999   /// \pre this->Inst && this->Origin are valid Instructions and this
11000   /// object passed the legal check: LoadedSlice::isLegal returned true.
11001   /// \return The last instruction of the sequence used to load the slice.
11002   SDValue loadSlice() const {
11003     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11004     const SDValue &OldBaseAddr = Origin->getBasePtr();
11005     SDValue BaseAddr = OldBaseAddr;
11006     // Get the offset in that chunk of bytes w.r.t. the endianness.
11007     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11008     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11009     if (Offset) {
11010       // BaseAddr = BaseAddr + Offset.
11011       EVT ArithType = BaseAddr.getValueType();
11012       SDLoc DL(Origin);
11013       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11014                               DAG->getConstant(Offset, DL, ArithType));
11015     }
11016 
11017     // Create the type of the loaded slice according to its size.
11018     EVT SliceType = getLoadedType();
11019 
11020     // Create the load for the slice.
11021     SDValue LastInst =
11022         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11023                      Origin->getPointerInfo().getWithOffset(Offset),
11024                      getAlignment(), Origin->getMemOperand()->getFlags());
11025     // If the final type is not the same as the loaded type, this means that
11026     // we have to pad with zero. Create a zero extend for that.
11027     EVT FinalType = Inst->getValueType(0);
11028     if (SliceType != FinalType)
11029       LastInst =
11030           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11031     return LastInst;
11032   }
11033 
11034   /// \brief Check if this slice can be merged with an expensive cross register
11035   /// bank copy. E.g.,
11036   /// i = load i32
11037   /// f = bitcast i32 i to float
11038   bool canMergeExpensiveCrossRegisterBankCopy() const {
11039     if (!Inst || !Inst->hasOneUse())
11040       return false;
11041     SDNode *Use = *Inst->use_begin();
11042     if (Use->getOpcode() != ISD::BITCAST)
11043       return false;
11044     assert(DAG && "Missing context");
11045     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11046     EVT ResVT = Use->getValueType(0);
11047     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11048     const TargetRegisterClass *ArgRC =
11049         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11050     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11051       return false;
11052 
11053     // At this point, we know that we perform a cross-register-bank copy.
11054     // Check if it is expensive.
11055     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11056     // Assume bitcasts are cheap, unless both register classes do not
11057     // explicitly share a common sub class.
11058     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11059       return false;
11060 
11061     // Check if it will be merged with the load.
11062     // 1. Check the alignment constraint.
11063     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11064         ResVT.getTypeForEVT(*DAG->getContext()));
11065 
11066     if (RequiredAlignment > getAlignment())
11067       return false;
11068 
11069     // 2. Check that the load is a legal operation for that type.
11070     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11071       return false;
11072 
11073     // 3. Check that we do not have a zext in the way.
11074     if (Inst->getValueType(0) != getLoadedType())
11075       return false;
11076 
11077     return true;
11078   }
11079 };
11080 }
11081 
11082 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11083 /// \p UsedBits looks like 0..0 1..1 0..0.
11084 static bool areUsedBitsDense(const APInt &UsedBits) {
11085   // If all the bits are one, this is dense!
11086   if (UsedBits.isAllOnesValue())
11087     return true;
11088 
11089   // Get rid of the unused bits on the right.
11090   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11091   // Get rid of the unused bits on the left.
11092   if (NarrowedUsedBits.countLeadingZeros())
11093     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11094   // Check that the chunk of bits is completely used.
11095   return NarrowedUsedBits.isAllOnesValue();
11096 }
11097 
11098 /// \brief Check whether or not \p First and \p Second are next to each other
11099 /// in memory. This means that there is no hole between the bits loaded
11100 /// by \p First and the bits loaded by \p Second.
11101 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11102                                      const LoadedSlice &Second) {
11103   assert(First.Origin == Second.Origin && First.Origin &&
11104          "Unable to match different memory origins.");
11105   APInt UsedBits = First.getUsedBits();
11106   assert((UsedBits & Second.getUsedBits()) == 0 &&
11107          "Slices are not supposed to overlap.");
11108   UsedBits |= Second.getUsedBits();
11109   return areUsedBitsDense(UsedBits);
11110 }
11111 
11112 /// \brief Adjust the \p GlobalLSCost according to the target
11113 /// paring capabilities and the layout of the slices.
11114 /// \pre \p GlobalLSCost should account for at least as many loads as
11115 /// there is in the slices in \p LoadedSlices.
11116 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11117                                  LoadedSlice::Cost &GlobalLSCost) {
11118   unsigned NumberOfSlices = LoadedSlices.size();
11119   // If there is less than 2 elements, no pairing is possible.
11120   if (NumberOfSlices < 2)
11121     return;
11122 
11123   // Sort the slices so that elements that are likely to be next to each
11124   // other in memory are next to each other in the list.
11125   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11126             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11127     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11128     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11129   });
11130   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11131   // First (resp. Second) is the first (resp. Second) potentially candidate
11132   // to be placed in a paired load.
11133   const LoadedSlice *First = nullptr;
11134   const LoadedSlice *Second = nullptr;
11135   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11136                 // Set the beginning of the pair.
11137                                                            First = Second) {
11138 
11139     Second = &LoadedSlices[CurrSlice];
11140 
11141     // If First is NULL, it means we start a new pair.
11142     // Get to the next slice.
11143     if (!First)
11144       continue;
11145 
11146     EVT LoadedType = First->getLoadedType();
11147 
11148     // If the types of the slices are different, we cannot pair them.
11149     if (LoadedType != Second->getLoadedType())
11150       continue;
11151 
11152     // Check if the target supplies paired loads for this type.
11153     unsigned RequiredAlignment = 0;
11154     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11155       // move to the next pair, this type is hopeless.
11156       Second = nullptr;
11157       continue;
11158     }
11159     // Check if we meet the alignment requirement.
11160     if (RequiredAlignment > First->getAlignment())
11161       continue;
11162 
11163     // Check that both loads are next to each other in memory.
11164     if (!areSlicesNextToEachOther(*First, *Second))
11165       continue;
11166 
11167     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11168     --GlobalLSCost.Loads;
11169     // Move to the next pair.
11170     Second = nullptr;
11171   }
11172 }
11173 
11174 /// \brief Check the profitability of all involved LoadedSlice.
11175 /// Currently, it is considered profitable if there is exactly two
11176 /// involved slices (1) which are (2) next to each other in memory, and
11177 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11178 ///
11179 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11180 /// the elements themselves.
11181 ///
11182 /// FIXME: When the cost model will be mature enough, we can relax
11183 /// constraints (1) and (2).
11184 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11185                                 const APInt &UsedBits, bool ForCodeSize) {
11186   unsigned NumberOfSlices = LoadedSlices.size();
11187   if (StressLoadSlicing)
11188     return NumberOfSlices > 1;
11189 
11190   // Check (1).
11191   if (NumberOfSlices != 2)
11192     return false;
11193 
11194   // Check (2).
11195   if (!areUsedBitsDense(UsedBits))
11196     return false;
11197 
11198   // Check (3).
11199   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11200   // The original code has one big load.
11201   OrigCost.Loads = 1;
11202   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11203     const LoadedSlice &LS = LoadedSlices[CurrSlice];
11204     // Accumulate the cost of all the slices.
11205     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11206     GlobalSlicingCost += SliceCost;
11207 
11208     // Account as cost in the original configuration the gain obtained
11209     // with the current slices.
11210     OrigCost.addSliceGain(LS);
11211   }
11212 
11213   // If the target supports paired load, adjust the cost accordingly.
11214   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11215   return OrigCost > GlobalSlicingCost;
11216 }
11217 
11218 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11219 /// operations, split it in the various pieces being extracted.
11220 ///
11221 /// This sort of thing is introduced by SROA.
11222 /// This slicing takes care not to insert overlapping loads.
11223 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11224 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11225   if (Level < AfterLegalizeDAG)
11226     return false;
11227 
11228   LoadSDNode *LD = cast<LoadSDNode>(N);
11229   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11230       !LD->getValueType(0).isInteger())
11231     return false;
11232 
11233   // Keep track of already used bits to detect overlapping values.
11234   // In that case, we will just abort the transformation.
11235   APInt UsedBits(LD->getValueSizeInBits(0), 0);
11236 
11237   SmallVector<LoadedSlice, 4> LoadedSlices;
11238 
11239   // Check if this load is used as several smaller chunks of bits.
11240   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11241   // of computation for each trunc.
11242   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11243        UI != UIEnd; ++UI) {
11244     // Skip the uses of the chain.
11245     if (UI.getUse().getResNo() != 0)
11246       continue;
11247 
11248     SDNode *User = *UI;
11249     unsigned Shift = 0;
11250 
11251     // Check if this is a trunc(lshr).
11252     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11253         isa<ConstantSDNode>(User->getOperand(1))) {
11254       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
11255       User = *User->use_begin();
11256     }
11257 
11258     // At this point, User is a Truncate, iff we encountered, trunc or
11259     // trunc(lshr).
11260     if (User->getOpcode() != ISD::TRUNCATE)
11261       return false;
11262 
11263     // The width of the type must be a power of 2 and greater than 8-bits.
11264     // Otherwise the load cannot be represented in LLVM IR.
11265     // Moreover, if we shifted with a non-8-bits multiple, the slice
11266     // will be across several bytes. We do not support that.
11267     unsigned Width = User->getValueSizeInBits(0);
11268     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11269       return 0;
11270 
11271     // Build the slice for this chain of computations.
11272     LoadedSlice LS(User, LD, Shift, &DAG);
11273     APInt CurrentUsedBits = LS.getUsedBits();
11274 
11275     // Check if this slice overlaps with another.
11276     if ((CurrentUsedBits & UsedBits) != 0)
11277       return false;
11278     // Update the bits used globally.
11279     UsedBits |= CurrentUsedBits;
11280 
11281     // Check if the new slice would be legal.
11282     if (!LS.isLegal())
11283       return false;
11284 
11285     // Record the slice.
11286     LoadedSlices.push_back(LS);
11287   }
11288 
11289   // Abort slicing if it does not seem to be profitable.
11290   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11291     return false;
11292 
11293   ++SlicedLoads;
11294 
11295   // Rewrite each chain to use an independent load.
11296   // By construction, each chain can be represented by a unique load.
11297 
11298   // Prepare the argument for the new token factor for all the slices.
11299   SmallVector<SDValue, 8> ArgChains;
11300   for (SmallVectorImpl<LoadedSlice>::const_iterator
11301            LSIt = LoadedSlices.begin(),
11302            LSItEnd = LoadedSlices.end();
11303        LSIt != LSItEnd; ++LSIt) {
11304     SDValue SliceInst = LSIt->loadSlice();
11305     CombineTo(LSIt->Inst, SliceInst, true);
11306     if (SliceInst.getOpcode() != ISD::LOAD)
11307       SliceInst = SliceInst.getOperand(0);
11308     assert(SliceInst->getOpcode() == ISD::LOAD &&
11309            "It takes more than a zext to get to the loaded slice!!");
11310     ArgChains.push_back(SliceInst.getValue(1));
11311   }
11312 
11313   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11314                               ArgChains);
11315   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11316   return true;
11317 }
11318 
11319 /// Check to see if V is (and load (ptr), imm), where the load is having
11320 /// specific bytes cleared out.  If so, return the byte size being masked out
11321 /// and the shift amount.
11322 static std::pair<unsigned, unsigned>
11323 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11324   std::pair<unsigned, unsigned> Result(0, 0);
11325 
11326   // Check for the structure we're looking for.
11327   if (V->getOpcode() != ISD::AND ||
11328       !isa<ConstantSDNode>(V->getOperand(1)) ||
11329       !ISD::isNormalLoad(V->getOperand(0).getNode()))
11330     return Result;
11331 
11332   // Check the chain and pointer.
11333   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11334   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
11335 
11336   // The store should be chained directly to the load or be an operand of a
11337   // tokenfactor.
11338   if (LD == Chain.getNode())
11339     ; // ok.
11340   else if (Chain->getOpcode() != ISD::TokenFactor)
11341     return Result; // Fail.
11342   else {
11343     bool isOk = false;
11344     for (const SDValue &ChainOp : Chain->op_values())
11345       if (ChainOp.getNode() == LD) {
11346         isOk = true;
11347         break;
11348       }
11349     if (!isOk) return Result;
11350   }
11351 
11352   // This only handles simple types.
11353   if (V.getValueType() != MVT::i16 &&
11354       V.getValueType() != MVT::i32 &&
11355       V.getValueType() != MVT::i64)
11356     return Result;
11357 
11358   // Check the constant mask.  Invert it so that the bits being masked out are
11359   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
11360   // follow the sign bit for uniformity.
11361   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
11362   unsigned NotMaskLZ = countLeadingZeros(NotMask);
11363   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
11364   unsigned NotMaskTZ = countTrailingZeros(NotMask);
11365   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
11366   if (NotMaskLZ == 64) return Result;  // All zero mask.
11367 
11368   // See if we have a continuous run of bits.  If so, we have 0*1+0*
11369   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
11370     return Result;
11371 
11372   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
11373   if (V.getValueType() != MVT::i64 && NotMaskLZ)
11374     NotMaskLZ -= 64-V.getValueSizeInBits();
11375 
11376   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
11377   switch (MaskedBytes) {
11378   case 1:
11379   case 2:
11380   case 4: break;
11381   default: return Result; // All one mask, or 5-byte mask.
11382   }
11383 
11384   // Verify that the first bit starts at a multiple of mask so that the access
11385   // is aligned the same as the access width.
11386   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
11387 
11388   Result.first = MaskedBytes;
11389   Result.second = NotMaskTZ/8;
11390   return Result;
11391 }
11392 
11393 
11394 /// Check to see if IVal is something that provides a value as specified by
11395 /// MaskInfo. If so, replace the specified store with a narrower store of
11396 /// truncated IVal.
11397 static SDNode *
11398 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
11399                                 SDValue IVal, StoreSDNode *St,
11400                                 DAGCombiner *DC) {
11401   unsigned NumBytes = MaskInfo.first;
11402   unsigned ByteShift = MaskInfo.second;
11403   SelectionDAG &DAG = DC->getDAG();
11404 
11405   // Check to see if IVal is all zeros in the part being masked in by the 'or'
11406   // that uses this.  If not, this is not a replacement.
11407   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
11408                                   ByteShift*8, (ByteShift+NumBytes)*8);
11409   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
11410 
11411   // Check that it is legal on the target to do this.  It is legal if the new
11412   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
11413   // legalization.
11414   MVT VT = MVT::getIntegerVT(NumBytes*8);
11415   if (!DC->isTypeLegal(VT))
11416     return nullptr;
11417 
11418   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
11419   // shifted by ByteShift and truncated down to NumBytes.
11420   if (ByteShift) {
11421     SDLoc DL(IVal);
11422     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
11423                        DAG.getConstant(ByteShift*8, DL,
11424                                     DC->getShiftAmountTy(IVal.getValueType())));
11425   }
11426 
11427   // Figure out the offset for the store and the alignment of the access.
11428   unsigned StOffset;
11429   unsigned NewAlign = St->getAlignment();
11430 
11431   if (DAG.getDataLayout().isLittleEndian())
11432     StOffset = ByteShift;
11433   else
11434     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11435 
11436   SDValue Ptr = St->getBasePtr();
11437   if (StOffset) {
11438     SDLoc DL(IVal);
11439     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11440                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11441     NewAlign = MinAlign(NewAlign, StOffset);
11442   }
11443 
11444   // Truncate down to the new size.
11445   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11446 
11447   ++OpsNarrowed;
11448   return DAG
11449       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11450                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11451       .getNode();
11452 }
11453 
11454 
11455 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11456 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11457 /// narrowing the load and store if it would end up being a win for performance
11458 /// or code size.
11459 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11460   StoreSDNode *ST  = cast<StoreSDNode>(N);
11461   if (ST->isVolatile())
11462     return SDValue();
11463 
11464   SDValue Chain = ST->getChain();
11465   SDValue Value = ST->getValue();
11466   SDValue Ptr   = ST->getBasePtr();
11467   EVT VT = Value.getValueType();
11468 
11469   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11470     return SDValue();
11471 
11472   unsigned Opc = Value.getOpcode();
11473 
11474   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11475   // is a byte mask indicating a consecutive number of bytes, check to see if
11476   // Y is known to provide just those bytes.  If so, we try to replace the
11477   // load + replace + store sequence with a single (narrower) store, which makes
11478   // the load dead.
11479   if (Opc == ISD::OR) {
11480     std::pair<unsigned, unsigned> MaskedLoad;
11481     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11482     if (MaskedLoad.first)
11483       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11484                                                   Value.getOperand(1), ST,this))
11485         return SDValue(NewST, 0);
11486 
11487     // Or is commutative, so try swapping X and Y.
11488     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11489     if (MaskedLoad.first)
11490       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11491                                                   Value.getOperand(0), ST,this))
11492         return SDValue(NewST, 0);
11493   }
11494 
11495   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11496       Value.getOperand(1).getOpcode() != ISD::Constant)
11497     return SDValue();
11498 
11499   SDValue N0 = Value.getOperand(0);
11500   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11501       Chain == SDValue(N0.getNode(), 1)) {
11502     LoadSDNode *LD = cast<LoadSDNode>(N0);
11503     if (LD->getBasePtr() != Ptr ||
11504         LD->getPointerInfo().getAddrSpace() !=
11505         ST->getPointerInfo().getAddrSpace())
11506       return SDValue();
11507 
11508     // Find the type to narrow it the load / op / store to.
11509     SDValue N1 = Value.getOperand(1);
11510     unsigned BitWidth = N1.getValueSizeInBits();
11511     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11512     if (Opc == ISD::AND)
11513       Imm ^= APInt::getAllOnesValue(BitWidth);
11514     if (Imm == 0 || Imm.isAllOnesValue())
11515       return SDValue();
11516     unsigned ShAmt = Imm.countTrailingZeros();
11517     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11518     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11519     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11520     // The narrowing should be profitable, the load/store operation should be
11521     // legal (or custom) and the store size should be equal to the NewVT width.
11522     while (NewBW < BitWidth &&
11523            (NewVT.getStoreSizeInBits() != NewBW ||
11524             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11525             !TLI.isNarrowingProfitable(VT, NewVT))) {
11526       NewBW = NextPowerOf2(NewBW);
11527       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11528     }
11529     if (NewBW >= BitWidth)
11530       return SDValue();
11531 
11532     // If the lsb changed does not start at the type bitwidth boundary,
11533     // start at the previous one.
11534     if (ShAmt % NewBW)
11535       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11536     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11537                                    std::min(BitWidth, ShAmt + NewBW));
11538     if ((Imm & Mask) == Imm) {
11539       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11540       if (Opc == ISD::AND)
11541         NewImm ^= APInt::getAllOnesValue(NewBW);
11542       uint64_t PtrOff = ShAmt / 8;
11543       // For big endian targets, we need to adjust the offset to the pointer to
11544       // load the correct bytes.
11545       if (DAG.getDataLayout().isBigEndian())
11546         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11547 
11548       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11549       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11550       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11551         return SDValue();
11552 
11553       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11554                                    Ptr.getValueType(), Ptr,
11555                                    DAG.getConstant(PtrOff, SDLoc(LD),
11556                                                    Ptr.getValueType()));
11557       SDValue NewLD =
11558           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11559                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11560                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
11561       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11562                                    DAG.getConstant(NewImm, SDLoc(Value),
11563                                                    NewVT));
11564       SDValue NewST =
11565           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11566                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11567 
11568       AddToWorklist(NewPtr.getNode());
11569       AddToWorklist(NewLD.getNode());
11570       AddToWorklist(NewVal.getNode());
11571       WorklistRemover DeadNodes(*this);
11572       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11573       ++OpsNarrowed;
11574       return NewST;
11575     }
11576   }
11577 
11578   return SDValue();
11579 }
11580 
11581 /// For a given floating point load / store pair, if the load value isn't used
11582 /// by any other operations, then consider transforming the pair to integer
11583 /// load / store operations if the target deems the transformation profitable.
11584 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11585   StoreSDNode *ST  = cast<StoreSDNode>(N);
11586   SDValue Chain = ST->getChain();
11587   SDValue Value = ST->getValue();
11588   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11589       Value.hasOneUse() &&
11590       Chain == SDValue(Value.getNode(), 1)) {
11591     LoadSDNode *LD = cast<LoadSDNode>(Value);
11592     EVT VT = LD->getMemoryVT();
11593     if (!VT.isFloatingPoint() ||
11594         VT != ST->getMemoryVT() ||
11595         LD->isNonTemporal() ||
11596         ST->isNonTemporal() ||
11597         LD->getPointerInfo().getAddrSpace() != 0 ||
11598         ST->getPointerInfo().getAddrSpace() != 0)
11599       return SDValue();
11600 
11601     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11602     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11603         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11604         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11605         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11606       return SDValue();
11607 
11608     unsigned LDAlign = LD->getAlignment();
11609     unsigned STAlign = ST->getAlignment();
11610     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11611     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11612     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11613       return SDValue();
11614 
11615     SDValue NewLD =
11616         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11617                     LD->getPointerInfo(), LDAlign);
11618 
11619     SDValue NewST =
11620         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11621                      ST->getPointerInfo(), STAlign);
11622 
11623     AddToWorklist(NewLD.getNode());
11624     AddToWorklist(NewST.getNode());
11625     WorklistRemover DeadNodes(*this);
11626     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11627     ++LdStFP2Int;
11628     return NewST;
11629   }
11630 
11631   return SDValue();
11632 }
11633 
11634 // This is a helper function for visitMUL to check the profitability
11635 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11636 // MulNode is the original multiply, AddNode is (add x, c1),
11637 // and ConstNode is c2.
11638 //
11639 // If the (add x, c1) has multiple uses, we could increase
11640 // the number of adds if we make this transformation.
11641 // It would only be worth doing this if we can remove a
11642 // multiply in the process. Check for that here.
11643 // To illustrate:
11644 //     (A + c1) * c3
11645 //     (A + c2) * c3
11646 // We're checking for cases where we have common "c3 * A" expressions.
11647 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11648                                               SDValue &AddNode,
11649                                               SDValue &ConstNode) {
11650   APInt Val;
11651 
11652   // If the add only has one use, this would be OK to do.
11653   if (AddNode.getNode()->hasOneUse())
11654     return true;
11655 
11656   // Walk all the users of the constant with which we're multiplying.
11657   for (SDNode *Use : ConstNode->uses()) {
11658 
11659     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11660       continue;
11661 
11662     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11663       SDNode *OtherOp;
11664       SDNode *MulVar = AddNode.getOperand(0).getNode();
11665 
11666       // OtherOp is what we're multiplying against the constant.
11667       if (Use->getOperand(0) == ConstNode)
11668         OtherOp = Use->getOperand(1).getNode();
11669       else
11670         OtherOp = Use->getOperand(0).getNode();
11671 
11672       // Check to see if multiply is with the same operand of our "add".
11673       //
11674       //     ConstNode  = CONST
11675       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11676       //     ...
11677       //     AddNode  = (A + c1)  <-- MulVar is A.
11678       //         = AddNode * ConstNode   <-- current visiting instruction.
11679       //
11680       // If we make this transformation, we will have a common
11681       // multiply (ConstNode * A) that we can save.
11682       if (OtherOp == MulVar)
11683         return true;
11684 
11685       // Now check to see if a future expansion will give us a common
11686       // multiply.
11687       //
11688       //     ConstNode  = CONST
11689       //     AddNode    = (A + c1)
11690       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11691       //     ...
11692       //     OtherOp = (A + c2)
11693       //     Use     = OtherOp * ConstNode <-- visiting Use.
11694       //
11695       // If we make this transformation, we will have a common
11696       // multiply (CONST * A) after we also do the same transformation
11697       // to the "t2" instruction.
11698       if (OtherOp->getOpcode() == ISD::ADD &&
11699           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11700           OtherOp->getOperand(0).getNode() == MulVar)
11701         return true;
11702     }
11703   }
11704 
11705   // Didn't find a case where this would be profitable.
11706   return false;
11707 }
11708 
11709 SDValue DAGCombiner::getMergedConstantVectorStore(
11710     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11711     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11712   SmallVector<SDValue, 8> BuildVector;
11713 
11714   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11715     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11716     Chains.push_back(St->getChain());
11717     BuildVector.push_back(St->getValue());
11718   }
11719 
11720   return DAG.getBuildVector(Ty, SL, BuildVector);
11721 }
11722 
11723 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11724                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11725                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11726   // Make sure we have something to merge.
11727   if (NumStores < 2)
11728     return false;
11729 
11730   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11731   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11732   unsigned LatestNodeUsed = 0;
11733 
11734   for (unsigned i=0; i < NumStores; ++i) {
11735     // Find a chain for the new wide-store operand. Notice that some
11736     // of the store nodes that we found may not be selected for inclusion
11737     // in the wide store. The chain we use needs to be the chain of the
11738     // latest store node which is *used* and replaced by the wide store.
11739     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11740       LatestNodeUsed = i;
11741   }
11742 
11743   SmallVector<SDValue, 8> Chains;
11744 
11745   // The latest Node in the DAG.
11746   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11747   SDLoc DL(StoreNodes[0].MemNode);
11748 
11749   SDValue StoredVal;
11750   if (UseVector) {
11751     bool IsVec = MemVT.isVector();
11752     unsigned Elts = NumStores;
11753     if (IsVec) {
11754       // When merging vector stores, get the total number of elements.
11755       Elts *= MemVT.getVectorNumElements();
11756     }
11757     // Get the type for the merged vector store.
11758     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11759     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11760 
11761     if (IsConstantSrc) {
11762       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11763     } else {
11764       SmallVector<SDValue, 8> Ops;
11765       for (unsigned i = 0; i < NumStores; ++i) {
11766         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11767         SDValue Val = St->getValue();
11768         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11769         if (Val.getValueType() != MemVT)
11770           return false;
11771         Ops.push_back(Val);
11772         Chains.push_back(St->getChain());
11773       }
11774 
11775       // Build the extracted vector elements back into a vector.
11776       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11777                               DL, Ty, Ops);    }
11778   } else {
11779     // We should always use a vector store when merging extracted vector
11780     // elements, so this path implies a store of constants.
11781     assert(IsConstantSrc && "Merged vector elements should use vector store");
11782 
11783     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11784     APInt StoreInt(SizeInBits, 0);
11785 
11786     // Construct a single integer constant which is made of the smaller
11787     // constant inputs.
11788     bool IsLE = DAG.getDataLayout().isLittleEndian();
11789     for (unsigned i = 0; i < NumStores; ++i) {
11790       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11791       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11792       Chains.push_back(St->getChain());
11793 
11794       SDValue Val = St->getValue();
11795       StoreInt <<= ElementSizeBytes * 8;
11796       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11797         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11798       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11799         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11800       } else {
11801         llvm_unreachable("Invalid constant element type");
11802       }
11803     }
11804 
11805     // Create the new Load and Store operations.
11806     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11807     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11808   }
11809 
11810   assert(!Chains.empty());
11811 
11812   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11813   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11814                                   FirstInChain->getBasePtr(),
11815                                   FirstInChain->getPointerInfo(),
11816                                   FirstInChain->getAlignment());
11817 
11818   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11819                                                   : DAG.getSubtarget().useAA();
11820   if (UseAA) {
11821     // Replace all merged stores with the new store.
11822     for (unsigned i = 0; i < NumStores; ++i)
11823       CombineTo(StoreNodes[i].MemNode, NewStore);
11824   } else {
11825     // Replace the last store with the new store.
11826     CombineTo(LatestOp, NewStore);
11827     // Erase all other stores.
11828     for (unsigned i = 0; i < NumStores; ++i) {
11829       if (StoreNodes[i].MemNode == LatestOp)
11830         continue;
11831       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11832       // ReplaceAllUsesWith will replace all uses that existed when it was
11833       // called, but graph optimizations may cause new ones to appear. For
11834       // example, the case in pr14333 looks like
11835       //
11836       //  St's chain -> St -> another store -> X
11837       //
11838       // And the only difference from St to the other store is the chain.
11839       // When we change it's chain to be St's chain they become identical,
11840       // get CSEed and the net result is that X is now a use of St.
11841       // Since we know that St is redundant, just iterate.
11842       while (!St->use_empty())
11843         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11844       deleteAndRecombine(St);
11845     }
11846   }
11847 
11848   StoreNodes.erase(StoreNodes.begin() + NumStores, StoreNodes.end());
11849   return true;
11850 }
11851 
11852 void DAGCombiner::getStoreMergeAndAliasCandidates(
11853     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11854     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11855   // This holds the base pointer, index, and the offset in bytes from the base
11856   // pointer.
11857   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11858 
11859   // We must have a base and an offset.
11860   if (!BasePtr.Base.getNode())
11861     return;
11862 
11863   // Do not handle stores to undef base pointers.
11864   if (BasePtr.Base.isUndef())
11865     return;
11866 
11867   // Walk up the chain and look for nodes with offsets from the same
11868   // base pointer. Stop when reaching an instruction with a different kind
11869   // or instruction which has a different base pointer.
11870   EVT MemVT = St->getMemoryVT();
11871   unsigned Seq = 0;
11872   StoreSDNode *Index = St;
11873 
11874 
11875   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11876                                                   : DAG.getSubtarget().useAA();
11877 
11878   if (UseAA) {
11879     // Look at other users of the same chain. Stores on the same chain do not
11880     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11881     // to be on the same chain, so don't bother looking at adjacent chains.
11882 
11883     SDValue Chain = St->getChain();
11884     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11885       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11886         if (I.getOperandNo() != 0)
11887           continue;
11888 
11889         if (OtherST->isVolatile() || OtherST->isIndexed())
11890           continue;
11891 
11892         if (OtherST->getMemoryVT() != MemVT)
11893           continue;
11894 
11895         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11896 
11897         if (Ptr.equalBaseIndex(BasePtr))
11898           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11899       }
11900     }
11901 
11902     return;
11903   }
11904 
11905   while (Index) {
11906     // If the chain has more than one use, then we can't reorder the mem ops.
11907     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11908       break;
11909 
11910     // Find the base pointer and offset for this memory node.
11911     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11912 
11913     // Check that the base pointer is the same as the original one.
11914     if (!Ptr.equalBaseIndex(BasePtr))
11915       break;
11916 
11917     // The memory operands must not be volatile.
11918     if (Index->isVolatile() || Index->isIndexed())
11919       break;
11920 
11921     // No truncation.
11922     if (Index->isTruncatingStore())
11923       break;
11924 
11925     // The stored memory type must be the same.
11926     if (Index->getMemoryVT() != MemVT)
11927       break;
11928 
11929     // We do not allow under-aligned stores in order to prevent
11930     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11931     // be irrelevant here; what MATTERS is that we not move memory
11932     // operations that potentially overlap past each-other.
11933     if (Index->getAlignment() < MemVT.getStoreSize())
11934       break;
11935 
11936     // We found a potential memory operand to merge.
11937     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11938 
11939     // Find the next memory operand in the chain. If the next operand in the
11940     // chain is a store then move up and continue the scan with the next
11941     // memory operand. If the next operand is a load save it and use alias
11942     // information to check if it interferes with anything.
11943     SDNode *NextInChain = Index->getChain().getNode();
11944     while (1) {
11945       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11946         // We found a store node. Use it for the next iteration.
11947         Index = STn;
11948         break;
11949       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11950         if (Ldn->isVolatile()) {
11951           Index = nullptr;
11952           break;
11953         }
11954 
11955         // Save the load node for later. Continue the scan.
11956         AliasLoadNodes.push_back(Ldn);
11957         NextInChain = Ldn->getChain().getNode();
11958         continue;
11959       } else {
11960         Index = nullptr;
11961         break;
11962       }
11963     }
11964   }
11965 }
11966 
11967 // We need to check that merging these stores does not cause a loop
11968 // in the DAG. Any store candidate may depend on another candidate
11969 // indirectly through its operand (we already consider dependencies
11970 // through the chain). Check in parallel by searching up from
11971 // non-chain operands of candidates.
11972 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11973     SmallVectorImpl<MemOpLink> &StoreNodes) {
11974   SmallPtrSet<const SDNode *, 16> Visited;
11975   SmallVector<const SDNode *, 8> Worklist;
11976   // search ops of store candidates
11977   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11978     SDNode *n = StoreNodes[i].MemNode;
11979     // Potential loops may happen only through non-chain operands
11980     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11981       Worklist.push_back(n->getOperand(j).getNode());
11982   }
11983   // search through DAG. We can stop early if we find a storenode
11984   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11985     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11986       return false;
11987   }
11988   return true;
11989 }
11990 
11991 bool DAGCombiner::MergeConsecutiveStores(
11992     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes) {
11993   if (OptLevel == CodeGenOpt::None)
11994     return false;
11995 
11996   EVT MemVT = St->getMemoryVT();
11997   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11998   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11999       Attribute::NoImplicitFloat);
12000 
12001   // This function cannot currently deal with non-byte-sized memory sizes.
12002   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12003     return false;
12004 
12005   if (!MemVT.isSimple())
12006     return false;
12007 
12008   // Perform an early exit check. Do not bother looking at stored values that
12009   // are not constants, loads, or extracted vector elements.
12010   SDValue StoredVal = St->getValue();
12011   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12012   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12013                        isa<ConstantFPSDNode>(StoredVal);
12014   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12015                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12016 
12017   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12018     return false;
12019 
12020   // Don't merge vectors into wider vectors if the source data comes from loads.
12021   // TODO: This restriction can be lifted by using logic similar to the
12022   // ExtractVecSrc case.
12023   if (MemVT.isVector() && IsLoadSrc)
12024     return false;
12025 
12026   // Only look at ends of store sequences.
12027   SDValue Chain = SDValue(St, 0);
12028   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
12029     return false;
12030 
12031   // Save the LoadSDNodes that we find in the chain.
12032   // We need to make sure that these nodes do not interfere with
12033   // any of the store nodes.
12034   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
12035 
12036   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
12037 
12038   // Check if there is anything to merge.
12039   if (StoreNodes.size() < 2)
12040     return false;
12041 
12042   // only do dependence check in AA case
12043   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12044                                                   : DAG.getSubtarget().useAA();
12045   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
12046     return false;
12047 
12048   // Sort the memory operands according to their distance from the
12049   // base pointer.  As a secondary criteria: make sure stores coming
12050   // later in the code come first in the list. This is important for
12051   // the non-UseAA case, because we're merging stores into the FINAL
12052   // store along a chain which potentially contains aliasing stores.
12053   // Thus, if there are multiple stores to the same address, the last
12054   // one can be considered for merging but not the others.
12055   std::sort(StoreNodes.begin(), StoreNodes.end(),
12056             [](MemOpLink LHS, MemOpLink RHS) {
12057     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
12058            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
12059             LHS.SequenceNum < RHS.SequenceNum);
12060   });
12061 
12062   // Scan the memory operations on the chain and find the first non-consecutive
12063   // store memory address.
12064   unsigned LastConsecutiveStore = 0;
12065   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12066   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
12067 
12068     // Check that the addresses are consecutive starting from the second
12069     // element in the list of stores.
12070     if (i > 0) {
12071       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12072       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12073         break;
12074     }
12075 
12076     // Check if this store interferes with any of the loads that we found.
12077     // If we find a load that alias with this store. Stop the sequence.
12078     if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) {
12079           return isAlias(Ldn, StoreNodes[i].MemNode);
12080         }))
12081       break;
12082 
12083     // Mark this node as useful.
12084     LastConsecutiveStore = i;
12085   }
12086 
12087   // The node with the lowest store address.
12088   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12089   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12090   unsigned FirstStoreAlign = FirstInChain->getAlignment();
12091   LLVMContext &Context = *DAG.getContext();
12092   const DataLayout &DL = DAG.getDataLayout();
12093 
12094   // Store the constants into memory as one consecutive store.
12095   if (IsConstantSrc) {
12096     unsigned LastLegalType = 0;
12097     unsigned LastLegalVectorType = 0;
12098     bool NonZero = false;
12099     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
12100       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
12101       SDValue StoredVal = St->getValue();
12102 
12103       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12104         NonZero |= !C->isNullValue();
12105       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
12106         NonZero |= !C->getConstantFPValue()->isNullValue();
12107       } else {
12108         // Non-constant.
12109         break;
12110       }
12111 
12112       // Find a legal type for the constant store.
12113       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
12114       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12115       bool IsFast;
12116       if (TLI.isTypeLegal(StoreTy) &&
12117           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12118                                  FirstStoreAlign, &IsFast) && IsFast) {
12119         LastLegalType = i+1;
12120       // Or check whether a truncstore is legal.
12121       } else if (TLI.getTypeAction(Context, StoreTy) ==
12122                  TargetLowering::TypePromoteInteger) {
12123         EVT LegalizedStoredValueTy =
12124           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12125         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12126             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12127                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
12128             IsFast) {
12129           LastLegalType = i + 1;
12130         }
12131       }
12132 
12133       // We only use vectors if the constant is known to be zero or the target
12134       // allows it and the function is not marked with the noimplicitfloat
12135       // attribute.
12136       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
12137                                                         FirstStoreAS)) &&
12138           !NoVectors) {
12139         // Find a legal type for the vector store.
12140         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
12141         if (TLI.isTypeLegal(Ty) &&
12142             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12143                                    FirstStoreAlign, &IsFast) && IsFast)
12144           LastLegalVectorType = i + 1;
12145       }
12146     }
12147 
12148     // Check if we found a legal integer type to store.
12149     if (LastLegalType == 0 && LastLegalVectorType == 0)
12150       return false;
12151 
12152     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12153     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
12154 
12155     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
12156                                            true, UseVector);
12157   }
12158 
12159   // When extracting multiple vector elements, try to store them
12160   // in one vector store rather than a sequence of scalar stores.
12161   if (IsExtractVecSrc) {
12162     unsigned NumStoresToMerge = 0;
12163     bool IsVec = MemVT.isVector();
12164     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
12165       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
12166       unsigned StoreValOpcode = St->getValue().getOpcode();
12167       // This restriction could be loosened.
12168       // Bail out if any stored values are not elements extracted from a vector.
12169       // It should be possible to handle mixed sources, but load sources need
12170       // more careful handling (see the block of code below that handles
12171       // consecutive loads).
12172       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12173           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12174         return false;
12175 
12176       // Find a legal type for the vector store.
12177       unsigned Elts = i + 1;
12178       if (IsVec) {
12179         // When merging vector stores, get the total number of elements.
12180         Elts *= MemVT.getVectorNumElements();
12181       }
12182       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12183       bool IsFast;
12184       if (TLI.isTypeLegal(Ty) &&
12185           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12186                                  FirstStoreAlign, &IsFast) && IsFast)
12187         NumStoresToMerge = i + 1;
12188     }
12189 
12190     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
12191                                            false, true);
12192   }
12193 
12194   // Below we handle the case of multiple consecutive stores that
12195   // come from multiple consecutive loads. We merge them into a single
12196   // wide load and a single wide store.
12197 
12198   // Look for load nodes which are used by the stored values.
12199   SmallVector<MemOpLink, 8> LoadNodes;
12200 
12201   // Find acceptable loads. Loads need to have the same chain (token factor),
12202   // must not be zext, volatile, indexed, and they must be consecutive.
12203   BaseIndexOffset LdBasePtr;
12204   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
12205     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
12206     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12207     if (!Ld) break;
12208 
12209     // Loads must only have one use.
12210     if (!Ld->hasNUsesOfValue(1, 0))
12211       break;
12212 
12213     // The memory operands must not be volatile.
12214     if (Ld->isVolatile() || Ld->isIndexed())
12215       break;
12216 
12217     // We do not accept ext loads.
12218     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12219       break;
12220 
12221     // The stored memory type must be the same.
12222     if (Ld->getMemoryVT() != MemVT)
12223       break;
12224 
12225     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12226     // If this is not the first ptr that we check.
12227     if (LdBasePtr.Base.getNode()) {
12228       // The base ptr must be the same.
12229       if (!LdPtr.equalBaseIndex(LdBasePtr))
12230         break;
12231     } else {
12232       // Check that all other base pointers are the same as this one.
12233       LdBasePtr = LdPtr;
12234     }
12235 
12236     // We found a potential memory operand to merge.
12237     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
12238   }
12239 
12240   if (LoadNodes.size() < 2)
12241     return false;
12242 
12243   // If we have load/store pair instructions and we only have two values,
12244   // don't bother.
12245   unsigned RequiredAlignment;
12246   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12247       St->getAlignment() >= RequiredAlignment)
12248     return false;
12249 
12250   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12251   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12252   unsigned FirstLoadAlign = FirstLoad->getAlignment();
12253 
12254   // Scan the memory operations on the chain and find the first non-consecutive
12255   // load memory address. These variables hold the index in the store node
12256   // array.
12257   unsigned LastConsecutiveLoad = 0;
12258   // This variable refers to the size and not index in the array.
12259   unsigned LastLegalVectorType = 0;
12260   unsigned LastLegalIntegerType = 0;
12261   StartAddress = LoadNodes[0].OffsetFromBase;
12262   SDValue FirstChain = FirstLoad->getChain();
12263   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12264     // All loads must share the same chain.
12265     if (LoadNodes[i].MemNode->getChain() != FirstChain)
12266       break;
12267 
12268     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12269     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12270       break;
12271     LastConsecutiveLoad = i;
12272     // Find a legal type for the vector store.
12273     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
12274     bool IsFastSt, IsFastLd;
12275     if (TLI.isTypeLegal(StoreTy) &&
12276         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12277                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
12278         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12279                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
12280       LastLegalVectorType = i + 1;
12281     }
12282 
12283     // Find a legal type for the integer store.
12284     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
12285     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12286     if (TLI.isTypeLegal(StoreTy) &&
12287         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12288                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
12289         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12290                                FirstLoadAlign, &IsFastLd) && IsFastLd)
12291       LastLegalIntegerType = i + 1;
12292     // Or check whether a truncstore and extload is legal.
12293     else if (TLI.getTypeAction(Context, StoreTy) ==
12294              TargetLowering::TypePromoteInteger) {
12295       EVT LegalizedStoredValueTy =
12296         TLI.getTypeToTransformTo(Context, StoreTy);
12297       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12298           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12299           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12300           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12301           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12302                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
12303           IsFastSt &&
12304           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12305                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
12306           IsFastLd)
12307         LastLegalIntegerType = i+1;
12308     }
12309   }
12310 
12311   // Only use vector types if the vector type is larger than the integer type.
12312   // If they are the same, use integers.
12313   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
12314   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
12315 
12316   // We add +1 here because the LastXXX variables refer to location while
12317   // the NumElem refers to array/index size.
12318   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
12319   NumElem = std::min(LastLegalType, NumElem);
12320 
12321   if (NumElem < 2)
12322     return false;
12323 
12324   // Collect the chains from all merged stores.
12325   SmallVector<SDValue, 8> MergeStoreChains;
12326   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
12327 
12328   // The latest Node in the DAG.
12329   unsigned LatestNodeUsed = 0;
12330   for (unsigned i=1; i<NumElem; ++i) {
12331     // Find a chain for the new wide-store operand. Notice that some
12332     // of the store nodes that we found may not be selected for inclusion
12333     // in the wide store. The chain we use needs to be the chain of the
12334     // latest store node which is *used* and replaced by the wide store.
12335     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
12336       LatestNodeUsed = i;
12337 
12338     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
12339   }
12340 
12341   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
12342 
12343   // Find if it is better to use vectors or integers to load and store
12344   // to memory.
12345   EVT JointMemOpVT;
12346   if (UseVectorTy) {
12347     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12348   } else {
12349     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12350     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12351   }
12352 
12353   SDLoc LoadDL(LoadNodes[0].MemNode);
12354   SDLoc StoreDL(StoreNodes[0].MemNode);
12355 
12356   // The merged loads are required to have the same incoming chain, so
12357   // using the first's chain is acceptable.
12358   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12359                                 FirstLoad->getBasePtr(),
12360                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
12361 
12362   SDValue NewStoreChain =
12363     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
12364 
12365   SDValue NewStore =
12366       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12367                    FirstInChain->getPointerInfo(), FirstStoreAlign);
12368 
12369   // Transfer chain users from old loads to the new load.
12370   for (unsigned i = 0; i < NumElem; ++i) {
12371     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12372     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12373                                   SDValue(NewLoad.getNode(), 1));
12374   }
12375 
12376   if (UseAA) {
12377     // Replace the all stores with the new store.
12378     for (unsigned i = 0; i < NumElem; ++i)
12379       CombineTo(StoreNodes[i].MemNode, NewStore);
12380   } else {
12381     // Replace the last store with the new store.
12382     CombineTo(LatestOp, NewStore);
12383     // Erase all other stores.
12384     for (unsigned i = 0; i < NumElem; ++i) {
12385       // Remove all Store nodes.
12386       if (StoreNodes[i].MemNode == LatestOp)
12387         continue;
12388       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12389       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
12390       deleteAndRecombine(St);
12391     }
12392   }
12393 
12394   StoreNodes.erase(StoreNodes.begin() + NumElem, StoreNodes.end());
12395   return true;
12396 }
12397 
12398 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12399   SDLoc SL(ST);
12400   SDValue ReplStore;
12401 
12402   // Replace the chain to avoid dependency.
12403   if (ST->isTruncatingStore()) {
12404     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12405                                   ST->getBasePtr(), ST->getMemoryVT(),
12406                                   ST->getMemOperand());
12407   } else {
12408     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12409                              ST->getMemOperand());
12410   }
12411 
12412   // Create token to keep both nodes around.
12413   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12414                               MVT::Other, ST->getChain(), ReplStore);
12415 
12416   // Make sure the new and old chains are cleaned up.
12417   AddToWorklist(Token.getNode());
12418 
12419   // Don't add users to work list.
12420   return CombineTo(ST, Token, false);
12421 }
12422 
12423 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12424   SDValue Value = ST->getValue();
12425   if (Value.getOpcode() == ISD::TargetConstantFP)
12426     return SDValue();
12427 
12428   SDLoc DL(ST);
12429 
12430   SDValue Chain = ST->getChain();
12431   SDValue Ptr = ST->getBasePtr();
12432 
12433   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12434 
12435   // NOTE: If the original store is volatile, this transform must not increase
12436   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12437   // processor operation but an i64 (which is not legal) requires two.  So the
12438   // transform should not be done in this case.
12439 
12440   SDValue Tmp;
12441   switch (CFP->getSimpleValueType(0).SimpleTy) {
12442   default:
12443     llvm_unreachable("Unknown FP type");
12444   case MVT::f16:    // We don't do this for these yet.
12445   case MVT::f80:
12446   case MVT::f128:
12447   case MVT::ppcf128:
12448     return SDValue();
12449   case MVT::f32:
12450     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12451         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12452       ;
12453       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12454                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12455                             MVT::i32);
12456       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12457     }
12458 
12459     return SDValue();
12460   case MVT::f64:
12461     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12462          !ST->isVolatile()) ||
12463         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12464       ;
12465       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12466                             getZExtValue(), SDLoc(CFP), MVT::i64);
12467       return DAG.getStore(Chain, DL, Tmp,
12468                           Ptr, ST->getMemOperand());
12469     }
12470 
12471     if (!ST->isVolatile() &&
12472         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12473       // Many FP stores are not made apparent until after legalize, e.g. for
12474       // argument passing.  Since this is so common, custom legalize the
12475       // 64-bit integer store into two 32-bit stores.
12476       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12477       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12478       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12479       if (DAG.getDataLayout().isBigEndian())
12480         std::swap(Lo, Hi);
12481 
12482       unsigned Alignment = ST->getAlignment();
12483       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12484       AAMDNodes AAInfo = ST->getAAInfo();
12485 
12486       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12487                                  ST->getAlignment(), MMOFlags, AAInfo);
12488       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12489                         DAG.getConstant(4, DL, Ptr.getValueType()));
12490       Alignment = MinAlign(Alignment, 4U);
12491       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12492                                  ST->getPointerInfo().getWithOffset(4),
12493                                  Alignment, MMOFlags, AAInfo);
12494       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12495                          St0, St1);
12496     }
12497 
12498     return SDValue();
12499   }
12500 }
12501 
12502 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12503   StoreSDNode *ST  = cast<StoreSDNode>(N);
12504   SDValue Chain = ST->getChain();
12505   SDValue Value = ST->getValue();
12506   SDValue Ptr   = ST->getBasePtr();
12507 
12508   // If this is a store of a bit convert, store the input value if the
12509   // resultant store does not need a higher alignment than the original.
12510   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12511       ST->isUnindexed()) {
12512     EVT SVT = Value.getOperand(0).getValueType();
12513     if (((!LegalOperations && !ST->isVolatile()) ||
12514          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12515         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12516       unsigned OrigAlign = ST->getAlignment();
12517       bool Fast = false;
12518       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12519                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12520           Fast) {
12521         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12522                             ST->getPointerInfo(), OrigAlign,
12523                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12524       }
12525     }
12526   }
12527 
12528   // Turn 'store undef, Ptr' -> nothing.
12529   if (Value.isUndef() && ST->isUnindexed())
12530     return Chain;
12531 
12532   // Try to infer better alignment information than the store already has.
12533   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12534     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12535       if (Align > ST->getAlignment()) {
12536         SDValue NewStore =
12537             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12538                               ST->getMemoryVT(), Align,
12539                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12540         if (NewStore.getNode() != N)
12541           return CombineTo(ST, NewStore, true);
12542       }
12543     }
12544   }
12545 
12546   // Try transforming a pair floating point load / store ops to integer
12547   // load / store ops.
12548   if (SDValue NewST = TransformFPLoadStorePair(N))
12549     return NewST;
12550 
12551   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12552                                                   : DAG.getSubtarget().useAA();
12553 #ifndef NDEBUG
12554   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12555       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12556     UseAA = false;
12557 #endif
12558   if (UseAA && ST->isUnindexed()) {
12559     // FIXME: We should do this even without AA enabled. AA will just allow
12560     // FindBetterChain to work in more situations. The problem with this is that
12561     // any combine that expects memory operations to be on consecutive chains
12562     // first needs to be updated to look for users of the same chain.
12563 
12564     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12565     // adjacent stores.
12566     if (findBetterNeighborChains(ST)) {
12567       // replaceStoreChain uses CombineTo, which handled all of the worklist
12568       // manipulation. Return the original node to not do anything else.
12569       return SDValue(ST, 0);
12570     }
12571     Chain = ST->getChain();
12572   }
12573 
12574   // Try transforming N to an indexed store.
12575   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12576     return SDValue(N, 0);
12577 
12578   // FIXME: is there such a thing as a truncating indexed store?
12579   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12580       Value.getValueType().isInteger()) {
12581     // See if we can simplify the input to this truncstore with knowledge that
12582     // only the low bits are being used.  For example:
12583     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12584     SDValue Shorter = GetDemandedBits(
12585         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12586                                     ST->getMemoryVT().getScalarSizeInBits()));
12587     AddToWorklist(Value.getNode());
12588     if (Shorter.getNode())
12589       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12590                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12591 
12592     // Otherwise, see if we can simplify the operation with
12593     // SimplifyDemandedBits, which only works if the value has a single use.
12594     if (SimplifyDemandedBits(
12595             Value,
12596             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12597                                  ST->getMemoryVT().getScalarSizeInBits())))
12598       return SDValue(N, 0);
12599   }
12600 
12601   // If this is a load followed by a store to the same location, then the store
12602   // is dead/noop.
12603   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12604     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12605         ST->isUnindexed() && !ST->isVolatile() &&
12606         // There can't be any side effects between the load and store, such as
12607         // a call or store.
12608         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12609       // The store is dead, remove it.
12610       return Chain;
12611     }
12612   }
12613 
12614   // If this is a store followed by a store with the same value to the same
12615   // location, then the store is dead/noop.
12616   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12617     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12618         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12619         ST1->isUnindexed() && !ST1->isVolatile()) {
12620       // The store is dead, remove it.
12621       return Chain;
12622     }
12623   }
12624 
12625   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12626   // truncating store.  We can do this even if this is already a truncstore.
12627   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12628       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12629       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12630                             ST->getMemoryVT())) {
12631     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12632                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12633   }
12634 
12635   // Only perform this optimization before the types are legal, because we
12636   // don't want to perform this optimization on every DAGCombine invocation.
12637   if (!LegalTypes) {
12638     for (;;) {
12639       // There can be multiple store sequences on the same chain.
12640       // Keep trying to merge store sequences until we are unable to do so
12641       // or until we merge the last store on the chain.
12642       SmallVector<MemOpLink, 8> StoreNodes;
12643       bool Changed = MergeConsecutiveStores(ST, StoreNodes);
12644       if (!Changed) break;
12645 
12646       if (any_of(StoreNodes,
12647                  [ST](const MemOpLink &Link) { return Link.MemNode == ST; })) {
12648         // ST has been merged and no longer exists.
12649         return SDValue(N, 0);
12650       }
12651     }
12652   }
12653 
12654   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12655   //
12656   // Make sure to do this only after attempting to merge stores in order to
12657   //  avoid changing the types of some subset of stores due to visit order,
12658   //  preventing their merging.
12659   if (isa<ConstantFPSDNode>(Value)) {
12660     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12661       return NewSt;
12662   }
12663 
12664   if (SDValue NewSt = splitMergedValStore(ST))
12665     return NewSt;
12666 
12667   return ReduceLoadOpStoreWidth(N);
12668 }
12669 
12670 /// For the instruction sequence of store below, F and I values
12671 /// are bundled together as an i64 value before being stored into memory.
12672 /// Sometimes it is more efficent to generate separate stores for F and I,
12673 /// which can remove the bitwise instructions or sink them to colder places.
12674 ///
12675 ///   (store (or (zext (bitcast F to i32) to i64),
12676 ///              (shl (zext I to i64), 32)), addr)  -->
12677 ///   (store F, addr) and (store I, addr+4)
12678 ///
12679 /// Similarly, splitting for other merged store can also be beneficial, like:
12680 /// For pair of {i32, i32}, i64 store --> two i32 stores.
12681 /// For pair of {i32, i16}, i64 store --> two i32 stores.
12682 /// For pair of {i16, i16}, i32 store --> two i16 stores.
12683 /// For pair of {i16, i8},  i32 store --> two i16 stores.
12684 /// For pair of {i8, i8},   i16 store --> two i8 stores.
12685 ///
12686 /// We allow each target to determine specifically which kind of splitting is
12687 /// supported.
12688 ///
12689 /// The store patterns are commonly seen from the simple code snippet below
12690 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
12691 ///   void goo(const std::pair<int, float> &);
12692 ///   hoo() {
12693 ///     ...
12694 ///     goo(std::make_pair(tmp, ftmp));
12695 ///     ...
12696 ///   }
12697 ///
12698 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
12699   if (OptLevel == CodeGenOpt::None)
12700     return SDValue();
12701 
12702   SDValue Val = ST->getValue();
12703   SDLoc DL(ST);
12704 
12705   // Match OR operand.
12706   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
12707     return SDValue();
12708 
12709   // Match SHL operand and get Lower and Higher parts of Val.
12710   SDValue Op1 = Val.getOperand(0);
12711   SDValue Op2 = Val.getOperand(1);
12712   SDValue Lo, Hi;
12713   if (Op1.getOpcode() != ISD::SHL) {
12714     std::swap(Op1, Op2);
12715     if (Op1.getOpcode() != ISD::SHL)
12716       return SDValue();
12717   }
12718   Lo = Op2;
12719   Hi = Op1.getOperand(0);
12720   if (!Op1.hasOneUse())
12721     return SDValue();
12722 
12723   // Match shift amount to HalfValBitSize.
12724   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
12725   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
12726   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
12727     return SDValue();
12728 
12729   // Lo and Hi are zero-extended from int with size less equal than 32
12730   // to i64.
12731   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
12732       !Lo.getOperand(0).getValueType().isScalarInteger() ||
12733       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
12734       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
12735       !Hi.getOperand(0).getValueType().isScalarInteger() ||
12736       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
12737     return SDValue();
12738 
12739   // Use the EVT of low and high parts before bitcast as the input
12740   // of target query.
12741   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
12742                   ? Lo.getOperand(0).getValueType()
12743                   : Lo.getValueType();
12744   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
12745                    ? Hi.getOperand(0).getValueType()
12746                    : Hi.getValueType();
12747   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
12748     return SDValue();
12749 
12750   // Start to split store.
12751   unsigned Alignment = ST->getAlignment();
12752   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12753   AAMDNodes AAInfo = ST->getAAInfo();
12754 
12755   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
12756   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
12757   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
12758   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
12759 
12760   SDValue Chain = ST->getChain();
12761   SDValue Ptr = ST->getBasePtr();
12762   // Lower value store.
12763   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12764                              ST->getAlignment(), MMOFlags, AAInfo);
12765   Ptr =
12766       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12767                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
12768   // Higher value store.
12769   SDValue St1 =
12770       DAG.getStore(St0, DL, Hi, Ptr,
12771                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
12772                    Alignment / 2, MMOFlags, AAInfo);
12773   return St1;
12774 }
12775 
12776 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12777   SDValue InVec = N->getOperand(0);
12778   SDValue InVal = N->getOperand(1);
12779   SDValue EltNo = N->getOperand(2);
12780   SDLoc DL(N);
12781 
12782   // If the inserted element is an UNDEF, just use the input vector.
12783   if (InVal.isUndef())
12784     return InVec;
12785 
12786   EVT VT = InVec.getValueType();
12787 
12788   // Check that we know which element is being inserted
12789   if (!isa<ConstantSDNode>(EltNo))
12790     return SDValue();
12791   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12792 
12793   // Canonicalize insert_vector_elt dag nodes.
12794   // Example:
12795   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12796   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12797   //
12798   // Do this only if the child insert_vector node has one use; also
12799   // do this only if indices are both constants and Idx1 < Idx0.
12800   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12801       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12802     unsigned OtherElt =
12803       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12804     if (Elt < OtherElt) {
12805       // Swap nodes.
12806       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
12807                                   InVec.getOperand(0), InVal, EltNo);
12808       AddToWorklist(NewOp.getNode());
12809       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12810                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12811     }
12812   }
12813 
12814   // If we can't generate a legal BUILD_VECTOR, exit
12815   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12816     return SDValue();
12817 
12818   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12819   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12820   // vector elements.
12821   SmallVector<SDValue, 8> Ops;
12822   // Do not combine these two vectors if the output vector will not replace
12823   // the input vector.
12824   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12825     Ops.append(InVec.getNode()->op_begin(),
12826                InVec.getNode()->op_end());
12827   } else if (InVec.isUndef()) {
12828     unsigned NElts = VT.getVectorNumElements();
12829     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12830   } else {
12831     return SDValue();
12832   }
12833 
12834   // Insert the element
12835   if (Elt < Ops.size()) {
12836     // All the operands of BUILD_VECTOR must have the same type;
12837     // we enforce that here.
12838     EVT OpVT = Ops[0].getValueType();
12839     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
12840   }
12841 
12842   // Return the new vector
12843   return DAG.getBuildVector(VT, DL, Ops);
12844 }
12845 
12846 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12847     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12848   assert(!OriginalLoad->isVolatile());
12849 
12850   EVT ResultVT = EVE->getValueType(0);
12851   EVT VecEltVT = InVecVT.getVectorElementType();
12852   unsigned Align = OriginalLoad->getAlignment();
12853   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12854       VecEltVT.getTypeForEVT(*DAG.getContext()));
12855 
12856   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12857     return SDValue();
12858 
12859   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
12860     ISD::NON_EXTLOAD : ISD::EXTLOAD;
12861   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
12862     return SDValue();
12863 
12864   Align = NewAlign;
12865 
12866   SDValue NewPtr = OriginalLoad->getBasePtr();
12867   SDValue Offset;
12868   EVT PtrType = NewPtr.getValueType();
12869   MachinePointerInfo MPI;
12870   SDLoc DL(EVE);
12871   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12872     int Elt = ConstEltNo->getZExtValue();
12873     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12874     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12875     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12876   } else {
12877     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12878     Offset = DAG.getNode(
12879         ISD::MUL, DL, PtrType, Offset,
12880         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12881     MPI = OriginalLoad->getPointerInfo();
12882   }
12883   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12884 
12885   // The replacement we need to do here is a little tricky: we need to
12886   // replace an extractelement of a load with a load.
12887   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12888   // Note that this replacement assumes that the extractvalue is the only
12889   // use of the load; that's okay because we don't want to perform this
12890   // transformation in other cases anyway.
12891   SDValue Load;
12892   SDValue Chain;
12893   if (ResultVT.bitsGT(VecEltVT)) {
12894     // If the result type of vextract is wider than the load, then issue an
12895     // extending load instead.
12896     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12897                                                   VecEltVT)
12898                                    ? ISD::ZEXTLOAD
12899                                    : ISD::EXTLOAD;
12900     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12901                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12902                           Align, OriginalLoad->getMemOperand()->getFlags(),
12903                           OriginalLoad->getAAInfo());
12904     Chain = Load.getValue(1);
12905   } else {
12906     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12907                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12908                        OriginalLoad->getAAInfo());
12909     Chain = Load.getValue(1);
12910     if (ResultVT.bitsLT(VecEltVT))
12911       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12912     else
12913       Load = DAG.getBitcast(ResultVT, Load);
12914   }
12915   WorklistRemover DeadNodes(*this);
12916   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12917   SDValue To[] = { Load, Chain };
12918   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12919   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12920   // worklist explicitly as well.
12921   AddToWorklist(Load.getNode());
12922   AddUsersToWorklist(Load.getNode()); // Add users too
12923   // Make sure to revisit this node to clean it up; it will usually be dead.
12924   AddToWorklist(EVE);
12925   ++OpsNarrowed;
12926   return SDValue(EVE, 0);
12927 }
12928 
12929 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12930   // (vextract (scalar_to_vector val, 0) -> val
12931   SDValue InVec = N->getOperand(0);
12932   EVT VT = InVec.getValueType();
12933   EVT NVT = N->getValueType(0);
12934 
12935   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12936     // Check if the result type doesn't match the inserted element type. A
12937     // SCALAR_TO_VECTOR may truncate the inserted element and the
12938     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12939     SDValue InOp = InVec.getOperand(0);
12940     if (InOp.getValueType() != NVT) {
12941       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12942       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12943     }
12944     return InOp;
12945   }
12946 
12947   SDValue EltNo = N->getOperand(1);
12948   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12949 
12950   // extract_vector_elt (build_vector x, y), 1 -> y
12951   if (ConstEltNo &&
12952       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12953       TLI.isTypeLegal(VT) &&
12954       (InVec.hasOneUse() ||
12955        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12956     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12957     EVT InEltVT = Elt.getValueType();
12958 
12959     // Sometimes build_vector's scalar input types do not match result type.
12960     if (NVT == InEltVT)
12961       return Elt;
12962 
12963     // TODO: It may be useful to truncate if free if the build_vector implicitly
12964     // converts.
12965   }
12966 
12967   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12968   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12969       ConstEltNo->isNullValue() && VT.isInteger()) {
12970     SDValue BCSrc = InVec.getOperand(0);
12971     if (BCSrc.getValueType().isScalarInteger())
12972       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12973   }
12974 
12975   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12976   //
12977   // This only really matters if the index is non-constant since other combines
12978   // on the constant elements already work.
12979   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12980       EltNo == InVec.getOperand(2)) {
12981     SDValue Elt = InVec.getOperand(1);
12982     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12983   }
12984 
12985   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12986   // We only perform this optimization before the op legalization phase because
12987   // we may introduce new vector instructions which are not backed by TD
12988   // patterns. For example on AVX, extracting elements from a wide vector
12989   // without using extract_subvector. However, if we can find an underlying
12990   // scalar value, then we can always use that.
12991   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12992     int NumElem = VT.getVectorNumElements();
12993     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12994     // Find the new index to extract from.
12995     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12996 
12997     // Extracting an undef index is undef.
12998     if (OrigElt == -1)
12999       return DAG.getUNDEF(NVT);
13000 
13001     // Select the right vector half to extract from.
13002     SDValue SVInVec;
13003     if (OrigElt < NumElem) {
13004       SVInVec = InVec->getOperand(0);
13005     } else {
13006       SVInVec = InVec->getOperand(1);
13007       OrigElt -= NumElem;
13008     }
13009 
13010     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13011       SDValue InOp = SVInVec.getOperand(OrigElt);
13012       if (InOp.getValueType() != NVT) {
13013         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13014         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13015       }
13016 
13017       return InOp;
13018     }
13019 
13020     // FIXME: We should handle recursing on other vector shuffles and
13021     // scalar_to_vector here as well.
13022 
13023     if (!LegalOperations) {
13024       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13025       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13026                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13027     }
13028   }
13029 
13030   bool BCNumEltsChanged = false;
13031   EVT ExtVT = VT.getVectorElementType();
13032   EVT LVT = ExtVT;
13033 
13034   // If the result of load has to be truncated, then it's not necessarily
13035   // profitable.
13036   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13037     return SDValue();
13038 
13039   if (InVec.getOpcode() == ISD::BITCAST) {
13040     // Don't duplicate a load with other uses.
13041     if (!InVec.hasOneUse())
13042       return SDValue();
13043 
13044     EVT BCVT = InVec.getOperand(0).getValueType();
13045     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13046       return SDValue();
13047     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13048       BCNumEltsChanged = true;
13049     InVec = InVec.getOperand(0);
13050     ExtVT = BCVT.getVectorElementType();
13051   }
13052 
13053   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13054   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13055       ISD::isNormalLoad(InVec.getNode()) &&
13056       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13057     SDValue Index = N->getOperand(1);
13058     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13059       if (!OrigLoad->isVolatile()) {
13060         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13061                                                              OrigLoad);
13062       }
13063     }
13064   }
13065 
13066   // Perform only after legalization to ensure build_vector / vector_shuffle
13067   // optimizations have already been done.
13068   if (!LegalOperations) return SDValue();
13069 
13070   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13071   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13072   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13073 
13074   if (ConstEltNo) {
13075     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13076 
13077     LoadSDNode *LN0 = nullptr;
13078     const ShuffleVectorSDNode *SVN = nullptr;
13079     if (ISD::isNormalLoad(InVec.getNode())) {
13080       LN0 = cast<LoadSDNode>(InVec);
13081     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13082                InVec.getOperand(0).getValueType() == ExtVT &&
13083                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13084       // Don't duplicate a load with other uses.
13085       if (!InVec.hasOneUse())
13086         return SDValue();
13087 
13088       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13089     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13090       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13091       // =>
13092       // (load $addr+1*size)
13093 
13094       // Don't duplicate a load with other uses.
13095       if (!InVec.hasOneUse())
13096         return SDValue();
13097 
13098       // If the bit convert changed the number of elements, it is unsafe
13099       // to examine the mask.
13100       if (BCNumEltsChanged)
13101         return SDValue();
13102 
13103       // Select the input vector, guarding against out of range extract vector.
13104       unsigned NumElems = VT.getVectorNumElements();
13105       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13106       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13107 
13108       if (InVec.getOpcode() == ISD::BITCAST) {
13109         // Don't duplicate a load with other uses.
13110         if (!InVec.hasOneUse())
13111           return SDValue();
13112 
13113         InVec = InVec.getOperand(0);
13114       }
13115       if (ISD::isNormalLoad(InVec.getNode())) {
13116         LN0 = cast<LoadSDNode>(InVec);
13117         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13118         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13119       }
13120     }
13121 
13122     // Make sure we found a non-volatile load and the extractelement is
13123     // the only use.
13124     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13125       return SDValue();
13126 
13127     // If Idx was -1 above, Elt is going to be -1, so just return undef.
13128     if (Elt == -1)
13129       return DAG.getUNDEF(LVT);
13130 
13131     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13132   }
13133 
13134   return SDValue();
13135 }
13136 
13137 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13138 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13139   // We perform this optimization post type-legalization because
13140   // the type-legalizer often scalarizes integer-promoted vectors.
13141   // Performing this optimization before may create bit-casts which
13142   // will be type-legalized to complex code sequences.
13143   // We perform this optimization only before the operation legalizer because we
13144   // may introduce illegal operations.
13145   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13146     return SDValue();
13147 
13148   unsigned NumInScalars = N->getNumOperands();
13149   SDLoc DL(N);
13150   EVT VT = N->getValueType(0);
13151 
13152   // Check to see if this is a BUILD_VECTOR of a bunch of values
13153   // which come from any_extend or zero_extend nodes. If so, we can create
13154   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13155   // optimizations. We do not handle sign-extend because we can't fill the sign
13156   // using shuffles.
13157   EVT SourceType = MVT::Other;
13158   bool AllAnyExt = true;
13159 
13160   for (unsigned i = 0; i != NumInScalars; ++i) {
13161     SDValue In = N->getOperand(i);
13162     // Ignore undef inputs.
13163     if (In.isUndef()) continue;
13164 
13165     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
13166     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13167 
13168     // Abort if the element is not an extension.
13169     if (!ZeroExt && !AnyExt) {
13170       SourceType = MVT::Other;
13171       break;
13172     }
13173 
13174     // The input is a ZeroExt or AnyExt. Check the original type.
13175     EVT InTy = In.getOperand(0).getValueType();
13176 
13177     // Check that all of the widened source types are the same.
13178     if (SourceType == MVT::Other)
13179       // First time.
13180       SourceType = InTy;
13181     else if (InTy != SourceType) {
13182       // Multiple income types. Abort.
13183       SourceType = MVT::Other;
13184       break;
13185     }
13186 
13187     // Check if all of the extends are ANY_EXTENDs.
13188     AllAnyExt &= AnyExt;
13189   }
13190 
13191   // In order to have valid types, all of the inputs must be extended from the
13192   // same source type and all of the inputs must be any or zero extend.
13193   // Scalar sizes must be a power of two.
13194   EVT OutScalarTy = VT.getScalarType();
13195   bool ValidTypes = SourceType != MVT::Other &&
13196                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13197                  isPowerOf2_32(SourceType.getSizeInBits());
13198 
13199   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13200   // turn into a single shuffle instruction.
13201   if (!ValidTypes)
13202     return SDValue();
13203 
13204   bool isLE = DAG.getDataLayout().isLittleEndian();
13205   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13206   assert(ElemRatio > 1 && "Invalid element size ratio");
13207   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13208                                DAG.getConstant(0, DL, SourceType);
13209 
13210   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13211   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13212 
13213   // Populate the new build_vector
13214   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13215     SDValue Cast = N->getOperand(i);
13216     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13217             Cast.getOpcode() == ISD::ZERO_EXTEND ||
13218             Cast.isUndef()) && "Invalid cast opcode");
13219     SDValue In;
13220     if (Cast.isUndef())
13221       In = DAG.getUNDEF(SourceType);
13222     else
13223       In = Cast->getOperand(0);
13224     unsigned Index = isLE ? (i * ElemRatio) :
13225                             (i * ElemRatio + (ElemRatio - 1));
13226 
13227     assert(Index < Ops.size() && "Invalid index");
13228     Ops[Index] = In;
13229   }
13230 
13231   // The type of the new BUILD_VECTOR node.
13232   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13233   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13234          "Invalid vector size");
13235   // Check if the new vector type is legal.
13236   if (!isTypeLegal(VecVT)) return SDValue();
13237 
13238   // Make the new BUILD_VECTOR.
13239   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13240 
13241   // The new BUILD_VECTOR node has the potential to be further optimized.
13242   AddToWorklist(BV.getNode());
13243   // Bitcast to the desired type.
13244   return DAG.getBitcast(VT, BV);
13245 }
13246 
13247 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13248   EVT VT = N->getValueType(0);
13249 
13250   unsigned NumInScalars = N->getNumOperands();
13251   SDLoc DL(N);
13252 
13253   EVT SrcVT = MVT::Other;
13254   unsigned Opcode = ISD::DELETED_NODE;
13255   unsigned NumDefs = 0;
13256 
13257   for (unsigned i = 0; i != NumInScalars; ++i) {
13258     SDValue In = N->getOperand(i);
13259     unsigned Opc = In.getOpcode();
13260 
13261     if (Opc == ISD::UNDEF)
13262       continue;
13263 
13264     // If all scalar values are floats and converted from integers.
13265     if (Opcode == ISD::DELETED_NODE &&
13266         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13267       Opcode = Opc;
13268     }
13269 
13270     if (Opc != Opcode)
13271       return SDValue();
13272 
13273     EVT InVT = In.getOperand(0).getValueType();
13274 
13275     // If all scalar values are typed differently, bail out. It's chosen to
13276     // simplify BUILD_VECTOR of integer types.
13277     if (SrcVT == MVT::Other)
13278       SrcVT = InVT;
13279     if (SrcVT != InVT)
13280       return SDValue();
13281     NumDefs++;
13282   }
13283 
13284   // If the vector has just one element defined, it's not worth to fold it into
13285   // a vectorized one.
13286   if (NumDefs < 2)
13287     return SDValue();
13288 
13289   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13290          && "Should only handle conversion from integer to float.");
13291   assert(SrcVT != MVT::Other && "Cannot determine source type!");
13292 
13293   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
13294 
13295   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
13296     return SDValue();
13297 
13298   // Just because the floating-point vector type is legal does not necessarily
13299   // mean that the corresponding integer vector type is.
13300   if (!isTypeLegal(NVT))
13301     return SDValue();
13302 
13303   SmallVector<SDValue, 8> Opnds;
13304   for (unsigned i = 0; i != NumInScalars; ++i) {
13305     SDValue In = N->getOperand(i);
13306 
13307     if (In.isUndef())
13308       Opnds.push_back(DAG.getUNDEF(SrcVT));
13309     else
13310       Opnds.push_back(In.getOperand(0));
13311   }
13312   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
13313   AddToWorklist(BV.getNode());
13314 
13315   return DAG.getNode(Opcode, DL, VT, BV);
13316 }
13317 
13318 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
13319                                            ArrayRef<int> VectorMask,
13320                                            SDValue VecIn1, SDValue VecIn2,
13321                                            unsigned LeftIdx) {
13322   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13323   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
13324 
13325   EVT VT = N->getValueType(0);
13326   EVT InVT1 = VecIn1.getValueType();
13327   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13328 
13329   unsigned Vec2Offset = InVT1.getVectorNumElements();
13330   unsigned NumElems = VT.getVectorNumElements();
13331   unsigned ShuffleNumElems = NumElems;
13332 
13333   // We can't generate a shuffle node with mismatched input and output types.
13334   // Try to make the types match the type of the output.
13335   if (InVT1 != VT || InVT2 != VT) {
13336     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13337       // If the output vector length is a multiple of both input lengths,
13338       // we can concatenate them and pad the rest with undefs.
13339       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13340       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13341       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13342       ConcatOps[0] = VecIn1;
13343       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13344       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13345       VecIn2 = SDValue();
13346     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13347       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13348         return SDValue();
13349 
13350       if (!VecIn2.getNode()) {
13351         // If we only have one input vector, and it's twice the size of the
13352         // output, split it in two.
13353         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13354                              DAG.getConstant(NumElems, DL, IdxTy));
13355         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13356         // Since we now have shorter input vectors, adjust the offset of the
13357         // second vector's start.
13358         Vec2Offset = NumElems;
13359       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13360         // VecIn1 is wider than the output, and we have another, possibly
13361         // smaller input. Pad the smaller input with undefs, shuffle at the
13362         // input vector width, and extract the output.
13363         // The shuffle type is different than VT, so check legality again.
13364         if (LegalOperations &&
13365             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13366           return SDValue();
13367 
13368         if (InVT1 != InVT2)
13369           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13370                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13371         ShuffleNumElems = NumElems * 2;
13372       } else {
13373         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13374         // than VecIn1. We can't handle this for now - this case will disappear
13375         // when we start sorting the vectors by type.
13376         return SDValue();
13377       }
13378     } else {
13379       // TODO: Support cases where the length mismatch isn't exactly by a
13380       // factor of 2.
13381       // TODO: Move this check upwards, so that if we have bad type
13382       // mismatches, we don't create any DAG nodes.
13383       return SDValue();
13384     }
13385   }
13386 
13387   // Initialize mask to undef.
13388   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13389 
13390   // Only need to run up to the number of elements actually used, not the
13391   // total number of elements in the shuffle - if we are shuffling a wider
13392   // vector, the high lanes should be set to undef.
13393   for (unsigned i = 0; i != NumElems; ++i) {
13394     if (VectorMask[i] <= 0)
13395       continue;
13396 
13397     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13398     if (VectorMask[i] == (int)LeftIdx) {
13399       Mask[i] = ExtIndex;
13400     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13401       Mask[i] = Vec2Offset + ExtIndex;
13402     }
13403   }
13404 
13405   // The type the input vectors may have changed above.
13406   InVT1 = VecIn1.getValueType();
13407 
13408   // If we already have a VecIn2, it should have the same type as VecIn1.
13409   // If we don't, get an undef/zero vector of the appropriate type.
13410   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13411   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13412 
13413   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13414   if (ShuffleNumElems > NumElems)
13415     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13416 
13417   return Shuffle;
13418 }
13419 
13420 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13421 // operations. If the types of the vectors we're extracting from allow it,
13422 // turn this into a vector_shuffle node.
13423 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13424   SDLoc DL(N);
13425   EVT VT = N->getValueType(0);
13426 
13427   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13428   if (!isTypeLegal(VT))
13429     return SDValue();
13430 
13431   // May only combine to shuffle after legalize if shuffle is legal.
13432   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13433     return SDValue();
13434 
13435   bool UsesZeroVector = false;
13436   unsigned NumElems = N->getNumOperands();
13437 
13438   // Record, for each element of the newly built vector, which input vector
13439   // that element comes from. -1 stands for undef, 0 for the zero vector,
13440   // and positive values for the input vectors.
13441   // VectorMask maps each element to its vector number, and VecIn maps vector
13442   // numbers to their initial SDValues.
13443 
13444   SmallVector<int, 8> VectorMask(NumElems, -1);
13445   SmallVector<SDValue, 8> VecIn;
13446   VecIn.push_back(SDValue());
13447 
13448   for (unsigned i = 0; i != NumElems; ++i) {
13449     SDValue Op = N->getOperand(i);
13450 
13451     if (Op.isUndef())
13452       continue;
13453 
13454     // See if we can use a blend with a zero vector.
13455     // TODO: Should we generalize this to a blend with an arbitrary constant
13456     // vector?
13457     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13458       UsesZeroVector = true;
13459       VectorMask[i] = 0;
13460       continue;
13461     }
13462 
13463     // Not an undef or zero. If the input is something other than an
13464     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13465     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13466         !isa<ConstantSDNode>(Op.getOperand(1)))
13467       return SDValue();
13468 
13469     SDValue ExtractedFromVec = Op.getOperand(0);
13470 
13471     // All inputs must have the same element type as the output.
13472     if (VT.getVectorElementType() !=
13473         ExtractedFromVec.getValueType().getVectorElementType())
13474       return SDValue();
13475 
13476     // Have we seen this input vector before?
13477     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13478     // a map back from SDValues to numbers isn't worth it.
13479     unsigned Idx = std::distance(
13480         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13481     if (Idx == VecIn.size())
13482       VecIn.push_back(ExtractedFromVec);
13483 
13484     VectorMask[i] = Idx;
13485   }
13486 
13487   // If we didn't find at least one input vector, bail out.
13488   if (VecIn.size() < 2)
13489     return SDValue();
13490 
13491   // TODO: We want to sort the vectors by descending length, so that adjacent
13492   // pairs have similar length, and the longer vector is always first in the
13493   // pair.
13494 
13495   // TODO: Should this fire if some of the input vectors has illegal type (like
13496   // it does now), or should we let legalization run its course first?
13497 
13498   // Shuffle phase:
13499   // Take pairs of vectors, and shuffle them so that the result has elements
13500   // from these vectors in the correct places.
13501   // For example, given:
13502   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13503   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13504   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13505   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13506   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13507   // We will generate:
13508   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13509   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13510   SmallVector<SDValue, 4> Shuffles;
13511   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13512     unsigned LeftIdx = 2 * In + 1;
13513     SDValue VecLeft = VecIn[LeftIdx];
13514     SDValue VecRight =
13515         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13516 
13517     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13518                                                 VecRight, LeftIdx))
13519       Shuffles.push_back(Shuffle);
13520     else
13521       return SDValue();
13522   }
13523 
13524   // If we need the zero vector as an "ingredient" in the blend tree, add it
13525   // to the list of shuffles.
13526   if (UsesZeroVector)
13527     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13528                                       : DAG.getConstantFP(0.0, DL, VT));
13529 
13530   // If we only have one shuffle, we're done.
13531   if (Shuffles.size() == 1)
13532     return Shuffles[0];
13533 
13534   // Update the vector mask to point to the post-shuffle vectors.
13535   for (int &Vec : VectorMask)
13536     if (Vec == 0)
13537       Vec = Shuffles.size() - 1;
13538     else
13539       Vec = (Vec - 1) / 2;
13540 
13541   // More than one shuffle. Generate a binary tree of blends, e.g. if from
13542   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13543   // generate:
13544   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13545   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13546   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13547   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13548   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13549   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13550   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13551 
13552   // Make sure the initial size of the shuffle list is even.
13553   if (Shuffles.size() % 2)
13554     Shuffles.push_back(DAG.getUNDEF(VT));
13555 
13556   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13557     if (CurSize % 2) {
13558       Shuffles[CurSize] = DAG.getUNDEF(VT);
13559       CurSize++;
13560     }
13561     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13562       int Left = 2 * In;
13563       int Right = 2 * In + 1;
13564       SmallVector<int, 8> Mask(NumElems, -1);
13565       for (unsigned i = 0; i != NumElems; ++i) {
13566         if (VectorMask[i] == Left) {
13567           Mask[i] = i;
13568           VectorMask[i] = In;
13569         } else if (VectorMask[i] == Right) {
13570           Mask[i] = i + NumElems;
13571           VectorMask[i] = In;
13572         }
13573       }
13574 
13575       Shuffles[In] =
13576           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13577     }
13578   }
13579 
13580   return Shuffles[0];
13581 }
13582 
13583 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13584   EVT VT = N->getValueType(0);
13585 
13586   // A vector built entirely of undefs is undef.
13587   if (ISD::allOperandsUndef(N))
13588     return DAG.getUNDEF(VT);
13589 
13590   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13591     return V;
13592 
13593   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13594     return V;
13595 
13596   if (SDValue V = reduceBuildVecToShuffle(N))
13597     return V;
13598 
13599   return SDValue();
13600 }
13601 
13602 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13604   EVT OpVT = N->getOperand(0).getValueType();
13605 
13606   // If the operands are legal vectors, leave them alone.
13607   if (TLI.isTypeLegal(OpVT))
13608     return SDValue();
13609 
13610   SDLoc DL(N);
13611   EVT VT = N->getValueType(0);
13612   SmallVector<SDValue, 8> Ops;
13613 
13614   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13615   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13616 
13617   // Keep track of what we encounter.
13618   bool AnyInteger = false;
13619   bool AnyFP = false;
13620   for (const SDValue &Op : N->ops()) {
13621     if (ISD::BITCAST == Op.getOpcode() &&
13622         !Op.getOperand(0).getValueType().isVector())
13623       Ops.push_back(Op.getOperand(0));
13624     else if (ISD::UNDEF == Op.getOpcode())
13625       Ops.push_back(ScalarUndef);
13626     else
13627       return SDValue();
13628 
13629     // Note whether we encounter an integer or floating point scalar.
13630     // If it's neither, bail out, it could be something weird like x86mmx.
13631     EVT LastOpVT = Ops.back().getValueType();
13632     if (LastOpVT.isFloatingPoint())
13633       AnyFP = true;
13634     else if (LastOpVT.isInteger())
13635       AnyInteger = true;
13636     else
13637       return SDValue();
13638   }
13639 
13640   // If any of the operands is a floating point scalar bitcast to a vector,
13641   // use floating point types throughout, and bitcast everything.
13642   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
13643   if (AnyFP) {
13644     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
13645     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13646     if (AnyInteger) {
13647       for (SDValue &Op : Ops) {
13648         if (Op.getValueType() == SVT)
13649           continue;
13650         if (Op.isUndef())
13651           Op = ScalarUndef;
13652         else
13653           Op = DAG.getBitcast(SVT, Op);
13654       }
13655     }
13656   }
13657 
13658   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
13659                                VT.getSizeInBits() / SVT.getSizeInBits());
13660   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
13661 }
13662 
13663 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
13664 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
13665 // most two distinct vectors the same size as the result, attempt to turn this
13666 // into a legal shuffle.
13667 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
13668   EVT VT = N->getValueType(0);
13669   EVT OpVT = N->getOperand(0).getValueType();
13670   int NumElts = VT.getVectorNumElements();
13671   int NumOpElts = OpVT.getVectorNumElements();
13672 
13673   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
13674   SmallVector<int, 8> Mask;
13675 
13676   for (SDValue Op : N->ops()) {
13677     // Peek through any bitcast.
13678     while (Op.getOpcode() == ISD::BITCAST)
13679       Op = Op.getOperand(0);
13680 
13681     // UNDEF nodes convert to UNDEF shuffle mask values.
13682     if (Op.isUndef()) {
13683       Mask.append((unsigned)NumOpElts, -1);
13684       continue;
13685     }
13686 
13687     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13688       return SDValue();
13689 
13690     // What vector are we extracting the subvector from and at what index?
13691     SDValue ExtVec = Op.getOperand(0);
13692 
13693     // We want the EVT of the original extraction to correctly scale the
13694     // extraction index.
13695     EVT ExtVT = ExtVec.getValueType();
13696 
13697     // Peek through any bitcast.
13698     while (ExtVec.getOpcode() == ISD::BITCAST)
13699       ExtVec = ExtVec.getOperand(0);
13700 
13701     // UNDEF nodes convert to UNDEF shuffle mask values.
13702     if (ExtVec.isUndef()) {
13703       Mask.append((unsigned)NumOpElts, -1);
13704       continue;
13705     }
13706 
13707     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13708       return SDValue();
13709     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13710 
13711     // Ensure that we are extracting a subvector from a vector the same
13712     // size as the result.
13713     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13714       return SDValue();
13715 
13716     // Scale the subvector index to account for any bitcast.
13717     int NumExtElts = ExtVT.getVectorNumElements();
13718     if (0 == (NumExtElts % NumElts))
13719       ExtIdx /= (NumExtElts / NumElts);
13720     else if (0 == (NumElts % NumExtElts))
13721       ExtIdx *= (NumElts / NumExtElts);
13722     else
13723       return SDValue();
13724 
13725     // At most we can reference 2 inputs in the final shuffle.
13726     if (SV0.isUndef() || SV0 == ExtVec) {
13727       SV0 = ExtVec;
13728       for (int i = 0; i != NumOpElts; ++i)
13729         Mask.push_back(i + ExtIdx);
13730     } else if (SV1.isUndef() || SV1 == ExtVec) {
13731       SV1 = ExtVec;
13732       for (int i = 0; i != NumOpElts; ++i)
13733         Mask.push_back(i + ExtIdx + NumElts);
13734     } else {
13735       return SDValue();
13736     }
13737   }
13738 
13739   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13740     return SDValue();
13741 
13742   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13743                               DAG.getBitcast(VT, SV1), Mask);
13744 }
13745 
13746 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13747   // If we only have one input vector, we don't need to do any concatenation.
13748   if (N->getNumOperands() == 1)
13749     return N->getOperand(0);
13750 
13751   // Check if all of the operands are undefs.
13752   EVT VT = N->getValueType(0);
13753   if (ISD::allOperandsUndef(N))
13754     return DAG.getUNDEF(VT);
13755 
13756   // Optimize concat_vectors where all but the first of the vectors are undef.
13757   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13758         return Op.isUndef();
13759       })) {
13760     SDValue In = N->getOperand(0);
13761     assert(In.getValueType().isVector() && "Must concat vectors");
13762 
13763     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13764     if (In->getOpcode() == ISD::BITCAST &&
13765         !In->getOperand(0)->getValueType(0).isVector()) {
13766       SDValue Scalar = In->getOperand(0);
13767 
13768       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13769       // look through the trunc so we can still do the transform:
13770       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13771       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13772           !TLI.isTypeLegal(Scalar.getValueType()) &&
13773           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13774         Scalar = Scalar->getOperand(0);
13775 
13776       EVT SclTy = Scalar->getValueType(0);
13777 
13778       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13779         return SDValue();
13780 
13781       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13782                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13783       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13784         return SDValue();
13785 
13786       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
13787       return DAG.getBitcast(VT, Res);
13788     }
13789   }
13790 
13791   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13792   // We have already tested above for an UNDEF only concatenation.
13793   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13794   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13795   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13796     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13797   };
13798   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13799     SmallVector<SDValue, 8> Opnds;
13800     EVT SVT = VT.getScalarType();
13801 
13802     EVT MinVT = SVT;
13803     if (!SVT.isFloatingPoint()) {
13804       // If BUILD_VECTOR are from built from integer, they may have different
13805       // operand types. Get the smallest type and truncate all operands to it.
13806       bool FoundMinVT = false;
13807       for (const SDValue &Op : N->ops())
13808         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13809           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13810           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13811           FoundMinVT = true;
13812         }
13813       assert(FoundMinVT && "Concat vector type mismatch");
13814     }
13815 
13816     for (const SDValue &Op : N->ops()) {
13817       EVT OpVT = Op.getValueType();
13818       unsigned NumElts = OpVT.getVectorNumElements();
13819 
13820       if (ISD::UNDEF == Op.getOpcode())
13821         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13822 
13823       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13824         if (SVT.isFloatingPoint()) {
13825           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13826           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13827         } else {
13828           for (unsigned i = 0; i != NumElts; ++i)
13829             Opnds.push_back(
13830                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13831         }
13832       }
13833     }
13834 
13835     assert(VT.getVectorNumElements() == Opnds.size() &&
13836            "Concat vector type mismatch");
13837     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13838   }
13839 
13840   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13841   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13842     return V;
13843 
13844   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13845   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13846     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13847       return V;
13848 
13849   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13850   // nodes often generate nop CONCAT_VECTOR nodes.
13851   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13852   // place the incoming vectors at the exact same location.
13853   SDValue SingleSource = SDValue();
13854   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13855 
13856   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13857     SDValue Op = N->getOperand(i);
13858 
13859     if (Op.isUndef())
13860       continue;
13861 
13862     // Check if this is the identity extract:
13863     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13864       return SDValue();
13865 
13866     // Find the single incoming vector for the extract_subvector.
13867     if (SingleSource.getNode()) {
13868       if (Op.getOperand(0) != SingleSource)
13869         return SDValue();
13870     } else {
13871       SingleSource = Op.getOperand(0);
13872 
13873       // Check the source type is the same as the type of the result.
13874       // If not, this concat may extend the vector, so we can not
13875       // optimize it away.
13876       if (SingleSource.getValueType() != N->getValueType(0))
13877         return SDValue();
13878     }
13879 
13880     unsigned IdentityIndex = i * PartNumElem;
13881     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13882     // The extract index must be constant.
13883     if (!CS)
13884       return SDValue();
13885 
13886     // Check that we are reading from the identity index.
13887     if (CS->getZExtValue() != IdentityIndex)
13888       return SDValue();
13889   }
13890 
13891   if (SingleSource.getNode())
13892     return SingleSource;
13893 
13894   return SDValue();
13895 }
13896 
13897 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13898   EVT NVT = N->getValueType(0);
13899   SDValue V = N->getOperand(0);
13900 
13901   // Extract from UNDEF is UNDEF.
13902   if (V.isUndef())
13903     return DAG.getUNDEF(NVT);
13904 
13905   // Combine:
13906   //    (extract_subvec (concat V1, V2, ...), i)
13907   // Into:
13908   //    Vi if possible
13909   // Only operand 0 is checked as 'concat' assumes all inputs of the same
13910   // type.
13911   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
13912       isa<ConstantSDNode>(N->getOperand(1)) &&
13913       V->getOperand(0).getValueType() == NVT) {
13914     unsigned Idx = N->getConstantOperandVal(1);
13915     unsigned NumElems = NVT.getVectorNumElements();
13916     assert((Idx % NumElems) == 0 &&
13917            "IDX in concat is not a multiple of the result vector length.");
13918     return V->getOperand(Idx / NumElems);
13919   }
13920 
13921   // Skip bitcasting
13922   if (V->getOpcode() == ISD::BITCAST)
13923     V = V.getOperand(0);
13924 
13925   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13926     // Handle only simple case where vector being inserted and vector
13927     // being extracted are of same type, and are half size of larger vectors.
13928     EVT BigVT = V->getOperand(0).getValueType();
13929     EVT SmallVT = V->getOperand(1).getValueType();
13930     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13931       return SDValue();
13932 
13933     // Only handle cases where both indexes are constants with the same type.
13934     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13935     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13936 
13937     if (InsIdx && ExtIdx) {
13938       // Combine:
13939       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13940       // Into:
13941       //    indices are equal or bit offsets are equal => V1
13942       //    otherwise => (extract_subvec V1, ExtIdx)
13943       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
13944           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
13945         return DAG.getBitcast(NVT, V->getOperand(1));
13946       return DAG.getNode(
13947           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
13948           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13949           N->getOperand(1));
13950     }
13951   }
13952 
13953   return SDValue();
13954 }
13955 
13956 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13957                                                  SDValue V, SelectionDAG &DAG) {
13958   SDLoc DL(V);
13959   EVT VT = V.getValueType();
13960 
13961   switch (V.getOpcode()) {
13962   default:
13963     return V;
13964 
13965   case ISD::CONCAT_VECTORS: {
13966     EVT OpVT = V->getOperand(0).getValueType();
13967     int OpSize = OpVT.getVectorNumElements();
13968     SmallBitVector OpUsedElements(OpSize, false);
13969     bool FoundSimplification = false;
13970     SmallVector<SDValue, 4> NewOps;
13971     NewOps.reserve(V->getNumOperands());
13972     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13973       SDValue Op = V->getOperand(i);
13974       bool OpUsed = false;
13975       for (int j = 0; j < OpSize; ++j)
13976         if (UsedElements[i * OpSize + j]) {
13977           OpUsedElements[j] = true;
13978           OpUsed = true;
13979         }
13980       NewOps.push_back(
13981           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13982                  : DAG.getUNDEF(OpVT));
13983       FoundSimplification |= Op == NewOps.back();
13984       OpUsedElements.reset();
13985     }
13986     if (FoundSimplification)
13987       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13988     return V;
13989   }
13990 
13991   case ISD::INSERT_SUBVECTOR: {
13992     SDValue BaseV = V->getOperand(0);
13993     SDValue SubV = V->getOperand(1);
13994     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13995     if (!IdxN)
13996       return V;
13997 
13998     int SubSize = SubV.getValueType().getVectorNumElements();
13999     int Idx = IdxN->getZExtValue();
14000     bool SubVectorUsed = false;
14001     SmallBitVector SubUsedElements(SubSize, false);
14002     for (int i = 0; i < SubSize; ++i)
14003       if (UsedElements[i + Idx]) {
14004         SubVectorUsed = true;
14005         SubUsedElements[i] = true;
14006         UsedElements[i + Idx] = false;
14007       }
14008 
14009     // Now recurse on both the base and sub vectors.
14010     SDValue SimplifiedSubV =
14011         SubVectorUsed
14012             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14013             : DAG.getUNDEF(SubV.getValueType());
14014     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14015     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14016       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14017                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14018     return V;
14019   }
14020   }
14021 }
14022 
14023 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14024                                        SDValue N1, SelectionDAG &DAG) {
14025   EVT VT = SVN->getValueType(0);
14026   int NumElts = VT.getVectorNumElements();
14027   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14028   for (int M : SVN->getMask())
14029     if (M >= 0 && M < NumElts)
14030       N0UsedElements[M] = true;
14031     else if (M >= NumElts)
14032       N1UsedElements[M - NumElts] = true;
14033 
14034   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14035   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14036   if (S0 == N0 && S1 == N1)
14037     return SDValue();
14038 
14039   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14040 }
14041 
14042 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14043 // or turn a shuffle of a single concat into simpler shuffle then concat.
14044 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14045   EVT VT = N->getValueType(0);
14046   unsigned NumElts = VT.getVectorNumElements();
14047 
14048   SDValue N0 = N->getOperand(0);
14049   SDValue N1 = N->getOperand(1);
14050   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14051 
14052   SmallVector<SDValue, 4> Ops;
14053   EVT ConcatVT = N0.getOperand(0).getValueType();
14054   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
14055   unsigned NumConcats = NumElts / NumElemsPerConcat;
14056 
14057   // Special case: shuffle(concat(A,B)) can be more efficiently represented
14058   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
14059   // half vector elements.
14060   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
14061       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
14062                   SVN->getMask().end(), [](int i) { return i == -1; })) {
14063     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
14064                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
14065     N1 = DAG.getUNDEF(ConcatVT);
14066     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
14067   }
14068 
14069   // Look at every vector that's inserted. We're looking for exact
14070   // subvector-sized copies from a concatenated vector
14071   for (unsigned I = 0; I != NumConcats; ++I) {
14072     // Make sure we're dealing with a copy.
14073     unsigned Begin = I * NumElemsPerConcat;
14074     bool AllUndef = true, NoUndef = true;
14075     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
14076       if (SVN->getMaskElt(J) >= 0)
14077         AllUndef = false;
14078       else
14079         NoUndef = false;
14080     }
14081 
14082     if (NoUndef) {
14083       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
14084         return SDValue();
14085 
14086       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
14087         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
14088           return SDValue();
14089 
14090       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
14091       if (FirstElt < N0.getNumOperands())
14092         Ops.push_back(N0.getOperand(FirstElt));
14093       else
14094         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
14095 
14096     } else if (AllUndef) {
14097       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
14098     } else { // Mixed with general masks and undefs, can't do optimization.
14099       return SDValue();
14100     }
14101   }
14102 
14103   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
14104 }
14105 
14106 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14107 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14108 //
14109 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
14110 // a simplification in some sense, but it isn't appropriate in general: some
14111 // BUILD_VECTORs are substantially cheaper than others. The general case
14112 // of a BUILD_VECTOR requires inserting each element individually (or
14113 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
14114 // all constants is a single constant pool load.  A BUILD_VECTOR where each
14115 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
14116 // are undef lowers to a small number of element insertions.
14117 //
14118 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
14119 // We don't fold shuffles where one side is a non-zero constant, and we don't
14120 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
14121 // non-constant operands. This seems to work out reasonably well in practice.
14122 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
14123                                        SelectionDAG &DAG,
14124                                        const TargetLowering &TLI) {
14125   EVT VT = SVN->getValueType(0);
14126   unsigned NumElts = VT.getVectorNumElements();
14127   SDValue N0 = SVN->getOperand(0);
14128   SDValue N1 = SVN->getOperand(1);
14129 
14130   if (!N0->hasOneUse() || !N1->hasOneUse())
14131     return SDValue();
14132   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
14133   // discussed above.
14134   if (!N1.isUndef()) {
14135     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
14136     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
14137     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
14138       return SDValue();
14139     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
14140       return SDValue();
14141   }
14142 
14143   SmallVector<SDValue, 8> Ops;
14144   SmallSet<SDValue, 16> DuplicateOps;
14145   for (int M : SVN->getMask()) {
14146     SDValue Op = DAG.getUNDEF(VT.getScalarType());
14147     if (M >= 0) {
14148       int Idx = M < (int)NumElts ? M : M - NumElts;
14149       SDValue &S = (M < (int)NumElts ? N0 : N1);
14150       if (S.getOpcode() == ISD::BUILD_VECTOR) {
14151         Op = S.getOperand(Idx);
14152       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14153         if (Idx == 0)
14154           Op = S.getOperand(0);
14155       } else {
14156         // Operand can't be combined - bail out.
14157         return SDValue();
14158       }
14159     }
14160 
14161     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
14162     // fine, but it's likely to generate low-quality code if the target can't
14163     // reconstruct an appropriate shuffle.
14164     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
14165       if (!DuplicateOps.insert(Op).second)
14166         return SDValue();
14167 
14168     Ops.push_back(Op);
14169   }
14170   // BUILD_VECTOR requires all inputs to be of the same type, find the
14171   // maximum type and extend them all.
14172   EVT SVT = VT.getScalarType();
14173   if (SVT.isInteger())
14174     for (SDValue &Op : Ops)
14175       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
14176   if (SVT != VT.getScalarType())
14177     for (SDValue &Op : Ops)
14178       Op = TLI.isZExtFree(Op.getValueType(), SVT)
14179                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
14180                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
14181   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
14182 }
14183 
14184 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
14185   EVT VT = N->getValueType(0);
14186   unsigned NumElts = VT.getVectorNumElements();
14187 
14188   SDValue N0 = N->getOperand(0);
14189   SDValue N1 = N->getOperand(1);
14190 
14191   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
14192 
14193   // Canonicalize shuffle undef, undef -> undef
14194   if (N0.isUndef() && N1.isUndef())
14195     return DAG.getUNDEF(VT);
14196 
14197   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14198 
14199   // Canonicalize shuffle v, v -> v, undef
14200   if (N0 == N1) {
14201     SmallVector<int, 8> NewMask;
14202     for (unsigned i = 0; i != NumElts; ++i) {
14203       int Idx = SVN->getMaskElt(i);
14204       if (Idx >= (int)NumElts) Idx -= NumElts;
14205       NewMask.push_back(Idx);
14206     }
14207     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
14208   }
14209 
14210   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
14211   if (N0.isUndef())
14212     return DAG.getCommutedVectorShuffle(*SVN);
14213 
14214   // Remove references to rhs if it is undef
14215   if (N1.isUndef()) {
14216     bool Changed = false;
14217     SmallVector<int, 8> NewMask;
14218     for (unsigned i = 0; i != NumElts; ++i) {
14219       int Idx = SVN->getMaskElt(i);
14220       if (Idx >= (int)NumElts) {
14221         Idx = -1;
14222         Changed = true;
14223       }
14224       NewMask.push_back(Idx);
14225     }
14226     if (Changed)
14227       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
14228   }
14229 
14230   // If it is a splat, check if the argument vector is another splat or a
14231   // build_vector.
14232   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
14233     SDNode *V = N0.getNode();
14234 
14235     // If this is a bit convert that changes the element type of the vector but
14236     // not the number of vector elements, look through it.  Be careful not to
14237     // look though conversions that change things like v4f32 to v2f64.
14238     if (V->getOpcode() == ISD::BITCAST) {
14239       SDValue ConvInput = V->getOperand(0);
14240       if (ConvInput.getValueType().isVector() &&
14241           ConvInput.getValueType().getVectorNumElements() == NumElts)
14242         V = ConvInput.getNode();
14243     }
14244 
14245     if (V->getOpcode() == ISD::BUILD_VECTOR) {
14246       assert(V->getNumOperands() == NumElts &&
14247              "BUILD_VECTOR has wrong number of operands");
14248       SDValue Base;
14249       bool AllSame = true;
14250       for (unsigned i = 0; i != NumElts; ++i) {
14251         if (!V->getOperand(i).isUndef()) {
14252           Base = V->getOperand(i);
14253           break;
14254         }
14255       }
14256       // Splat of <u, u, u, u>, return <u, u, u, u>
14257       if (!Base.getNode())
14258         return N0;
14259       for (unsigned i = 0; i != NumElts; ++i) {
14260         if (V->getOperand(i) != Base) {
14261           AllSame = false;
14262           break;
14263         }
14264       }
14265       // Splat of <x, x, x, x>, return <x, x, x, x>
14266       if (AllSame)
14267         return N0;
14268 
14269       // Canonicalize any other splat as a build_vector.
14270       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
14271       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
14272       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
14273 
14274       // We may have jumped through bitcasts, so the type of the
14275       // BUILD_VECTOR may not match the type of the shuffle.
14276       if (V->getValueType(0) != VT)
14277         NewBV = DAG.getBitcast(VT, NewBV);
14278       return NewBV;
14279     }
14280   }
14281 
14282   // There are various patterns used to build up a vector from smaller vectors,
14283   // subvectors, or elements. Scan chains of these and replace unused insertions
14284   // or components with undef.
14285   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
14286     return S;
14287 
14288   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
14289       Level < AfterLegalizeVectorOps &&
14290       (N1.isUndef() ||
14291       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
14292        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
14293     if (SDValue V = partitionShuffleOfConcats(N, DAG))
14294       return V;
14295   }
14296 
14297   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14298   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14299   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14300     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
14301       return Res;
14302 
14303   // If this shuffle only has a single input that is a bitcasted shuffle,
14304   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
14305   // back to their original types.
14306   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
14307       N1.isUndef() && Level < AfterLegalizeVectorOps &&
14308       TLI.isTypeLegal(VT)) {
14309 
14310     // Peek through the bitcast only if there is one user.
14311     SDValue BC0 = N0;
14312     while (BC0.getOpcode() == ISD::BITCAST) {
14313       if (!BC0.hasOneUse())
14314         break;
14315       BC0 = BC0.getOperand(0);
14316     }
14317 
14318     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
14319       if (Scale == 1)
14320         return SmallVector<int, 8>(Mask.begin(), Mask.end());
14321 
14322       SmallVector<int, 8> NewMask;
14323       for (int M : Mask)
14324         for (int s = 0; s != Scale; ++s)
14325           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
14326       return NewMask;
14327     };
14328 
14329     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
14330       EVT SVT = VT.getScalarType();
14331       EVT InnerVT = BC0->getValueType(0);
14332       EVT InnerSVT = InnerVT.getScalarType();
14333 
14334       // Determine which shuffle works with the smaller scalar type.
14335       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
14336       EVT ScaleSVT = ScaleVT.getScalarType();
14337 
14338       if (TLI.isTypeLegal(ScaleVT) &&
14339           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
14340           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
14341 
14342         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14343         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14344 
14345         // Scale the shuffle masks to the smaller scalar type.
14346         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
14347         SmallVector<int, 8> InnerMask =
14348             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
14349         SmallVector<int, 8> OuterMask =
14350             ScaleShuffleMask(SVN->getMask(), OuterScale);
14351 
14352         // Merge the shuffle masks.
14353         SmallVector<int, 8> NewMask;
14354         for (int M : OuterMask)
14355           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
14356 
14357         // Test for shuffle mask legality over both commutations.
14358         SDValue SV0 = BC0->getOperand(0);
14359         SDValue SV1 = BC0->getOperand(1);
14360         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14361         if (!LegalMask) {
14362           std::swap(SV0, SV1);
14363           ShuffleVectorSDNode::commuteMask(NewMask);
14364           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14365         }
14366 
14367         if (LegalMask) {
14368           SV0 = DAG.getBitcast(ScaleVT, SV0);
14369           SV1 = DAG.getBitcast(ScaleVT, SV1);
14370           return DAG.getBitcast(
14371               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
14372         }
14373       }
14374     }
14375   }
14376 
14377   // Canonicalize shuffles according to rules:
14378   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
14379   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
14380   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
14381   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
14382       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
14383       TLI.isTypeLegal(VT)) {
14384     // The incoming shuffle must be of the same type as the result of the
14385     // current shuffle.
14386     assert(N1->getOperand(0).getValueType() == VT &&
14387            "Shuffle types don't match");
14388 
14389     SDValue SV0 = N1->getOperand(0);
14390     SDValue SV1 = N1->getOperand(1);
14391     bool HasSameOp0 = N0 == SV0;
14392     bool IsSV1Undef = SV1.isUndef();
14393     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
14394       // Commute the operands of this shuffle so that next rule
14395       // will trigger.
14396       return DAG.getCommutedVectorShuffle(*SVN);
14397   }
14398 
14399   // Try to fold according to rules:
14400   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14401   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14402   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14403   // Don't try to fold shuffles with illegal type.
14404   // Only fold if this shuffle is the only user of the other shuffle.
14405   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14406       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14407     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14408 
14409     // Don't try to fold splats; they're likely to simplify somehow, or they
14410     // might be free.
14411     if (OtherSV->isSplat())
14412       return SDValue();
14413 
14414     // The incoming shuffle must be of the same type as the result of the
14415     // current shuffle.
14416     assert(OtherSV->getOperand(0).getValueType() == VT &&
14417            "Shuffle types don't match");
14418 
14419     SDValue SV0, SV1;
14420     SmallVector<int, 4> Mask;
14421     // Compute the combined shuffle mask for a shuffle with SV0 as the first
14422     // operand, and SV1 as the second operand.
14423     for (unsigned i = 0; i != NumElts; ++i) {
14424       int Idx = SVN->getMaskElt(i);
14425       if (Idx < 0) {
14426         // Propagate Undef.
14427         Mask.push_back(Idx);
14428         continue;
14429       }
14430 
14431       SDValue CurrentVec;
14432       if (Idx < (int)NumElts) {
14433         // This shuffle index refers to the inner shuffle N0. Lookup the inner
14434         // shuffle mask to identify which vector is actually referenced.
14435         Idx = OtherSV->getMaskElt(Idx);
14436         if (Idx < 0) {
14437           // Propagate Undef.
14438           Mask.push_back(Idx);
14439           continue;
14440         }
14441 
14442         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14443                                            : OtherSV->getOperand(1);
14444       } else {
14445         // This shuffle index references an element within N1.
14446         CurrentVec = N1;
14447       }
14448 
14449       // Simple case where 'CurrentVec' is UNDEF.
14450       if (CurrentVec.isUndef()) {
14451         Mask.push_back(-1);
14452         continue;
14453       }
14454 
14455       // Canonicalize the shuffle index. We don't know yet if CurrentVec
14456       // will be the first or second operand of the combined shuffle.
14457       Idx = Idx % NumElts;
14458       if (!SV0.getNode() || SV0 == CurrentVec) {
14459         // Ok. CurrentVec is the left hand side.
14460         // Update the mask accordingly.
14461         SV0 = CurrentVec;
14462         Mask.push_back(Idx);
14463         continue;
14464       }
14465 
14466       // Bail out if we cannot convert the shuffle pair into a single shuffle.
14467       if (SV1.getNode() && SV1 != CurrentVec)
14468         return SDValue();
14469 
14470       // Ok. CurrentVec is the right hand side.
14471       // Update the mask accordingly.
14472       SV1 = CurrentVec;
14473       Mask.push_back(Idx + NumElts);
14474     }
14475 
14476     // Check if all indices in Mask are Undef. In case, propagate Undef.
14477     bool isUndefMask = true;
14478     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14479       isUndefMask &= Mask[i] < 0;
14480 
14481     if (isUndefMask)
14482       return DAG.getUNDEF(VT);
14483 
14484     if (!SV0.getNode())
14485       SV0 = DAG.getUNDEF(VT);
14486     if (!SV1.getNode())
14487       SV1 = DAG.getUNDEF(VT);
14488 
14489     // Avoid introducing shuffles with illegal mask.
14490     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14491       ShuffleVectorSDNode::commuteMask(Mask);
14492 
14493       if (!TLI.isShuffleMaskLegal(Mask, VT))
14494         return SDValue();
14495 
14496       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14497       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14498       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14499       std::swap(SV0, SV1);
14500     }
14501 
14502     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14503     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14504     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14505     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14506   }
14507 
14508   return SDValue();
14509 }
14510 
14511 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14512   SDValue InVal = N->getOperand(0);
14513   EVT VT = N->getValueType(0);
14514 
14515   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14516   // with a VECTOR_SHUFFLE.
14517   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14518     SDValue InVec = InVal->getOperand(0);
14519     SDValue EltNo = InVal->getOperand(1);
14520 
14521     // FIXME: We could support implicit truncation if the shuffle can be
14522     // scaled to a smaller vector scalar type.
14523     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
14524     if (C0 && VT == InVec.getValueType() &&
14525         VT.getScalarType() == InVal.getValueType()) {
14526       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
14527       int Elt = C0->getZExtValue();
14528       NewMask[0] = Elt;
14529 
14530       if (TLI.isShuffleMaskLegal(NewMask, VT))
14531         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
14532                                     NewMask);
14533     }
14534   }
14535 
14536   return SDValue();
14537 }
14538 
14539 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
14540   EVT VT = N->getValueType(0);
14541   SDValue N0 = N->getOperand(0);
14542   SDValue N1 = N->getOperand(1);
14543   SDValue N2 = N->getOperand(2);
14544 
14545   // If inserting an UNDEF, just return the original vector.
14546   if (N1.isUndef())
14547     return N0;
14548 
14549   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
14550   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
14551   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
14552   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
14553       N0.getOperand(1).getValueType() == N1.getValueType() &&
14554       N0.getOperand(2) == N2)
14555     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
14556                        N1, N2);
14557 
14558   if (!isa<ConstantSDNode>(N2))
14559     return SDValue();
14560 
14561   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
14562 
14563   // Canonicalize insert_subvector dag nodes.
14564   // Example:
14565   // (insert_subvector (insert_subvector A, Idx0), Idx1)
14566   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
14567   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
14568       N1.getValueType() == N0.getOperand(1).getValueType() &&
14569       isa<ConstantSDNode>(N0.getOperand(2))) {
14570     unsigned OtherIdx = cast<ConstantSDNode>(N0.getOperand(2))->getZExtValue();
14571     if (InsIdx < OtherIdx) {
14572       // Swap nodes.
14573       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
14574                                   N0.getOperand(0), N1, N2);
14575       AddToWorklist(NewOp.getNode());
14576       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
14577                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
14578     }
14579   }
14580 
14581   if (N0.getValueType() != N1.getValueType())
14582     return SDValue();
14583 
14584   // If the input vector is a concatenation, and the insert replaces
14585   // one of the halves, we can optimize into a single concat_vectors.
14586   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2) {
14587     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14588     // (concat_vectors Z, Y)
14589     if (InsIdx == 0)
14590       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
14591                          N0.getOperand(1));
14592 
14593     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14594     // (concat_vectors X, Z)
14595     if (InsIdx == VT.getVectorNumElements() / 2)
14596       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
14597                          N1);
14598   }
14599 
14600   return SDValue();
14601 }
14602 
14603 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
14604   SDValue N0 = N->getOperand(0);
14605 
14606   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
14607   if (N0->getOpcode() == ISD::FP16_TO_FP)
14608     return N0->getOperand(0);
14609 
14610   return SDValue();
14611 }
14612 
14613 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
14614   SDValue N0 = N->getOperand(0);
14615 
14616   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
14617   if (N0->getOpcode() == ISD::AND) {
14618     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
14619     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
14620       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
14621                          N0.getOperand(0));
14622     }
14623   }
14624 
14625   return SDValue();
14626 }
14627 
14628 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
14629 /// with the destination vector and a zero vector.
14630 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
14631 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
14632 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
14633   EVT VT = N->getValueType(0);
14634   SDValue LHS = N->getOperand(0);
14635   SDValue RHS = N->getOperand(1);
14636   SDLoc DL(N);
14637 
14638   // Make sure we're not running after operation legalization where it
14639   // may have custom lowered the vector shuffles.
14640   if (LegalOperations)
14641     return SDValue();
14642 
14643   if (N->getOpcode() != ISD::AND)
14644     return SDValue();
14645 
14646   if (RHS.getOpcode() == ISD::BITCAST)
14647     RHS = RHS.getOperand(0);
14648 
14649   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
14650     return SDValue();
14651 
14652   EVT RVT = RHS.getValueType();
14653   unsigned NumElts = RHS.getNumOperands();
14654 
14655   // Attempt to create a valid clear mask, splitting the mask into
14656   // sub elements and checking to see if each is
14657   // all zeros or all ones - suitable for shuffle masking.
14658   auto BuildClearMask = [&](int Split) {
14659     int NumSubElts = NumElts * Split;
14660     int NumSubBits = RVT.getScalarSizeInBits() / Split;
14661 
14662     SmallVector<int, 8> Indices;
14663     for (int i = 0; i != NumSubElts; ++i) {
14664       int EltIdx = i / Split;
14665       int SubIdx = i % Split;
14666       SDValue Elt = RHS.getOperand(EltIdx);
14667       if (Elt.isUndef()) {
14668         Indices.push_back(-1);
14669         continue;
14670       }
14671 
14672       APInt Bits;
14673       if (isa<ConstantSDNode>(Elt))
14674         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
14675       else if (isa<ConstantFPSDNode>(Elt))
14676         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
14677       else
14678         return SDValue();
14679 
14680       // Extract the sub element from the constant bit mask.
14681       if (DAG.getDataLayout().isBigEndian()) {
14682         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
14683       } else {
14684         Bits = Bits.lshr(SubIdx * NumSubBits);
14685       }
14686 
14687       if (Split > 1)
14688         Bits = Bits.trunc(NumSubBits);
14689 
14690       if (Bits.isAllOnesValue())
14691         Indices.push_back(i);
14692       else if (Bits == 0)
14693         Indices.push_back(i + NumSubElts);
14694       else
14695         return SDValue();
14696     }
14697 
14698     // Let's see if the target supports this vector_shuffle.
14699     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
14700     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
14701     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
14702       return SDValue();
14703 
14704     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
14705     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
14706                                                    DAG.getBitcast(ClearVT, LHS),
14707                                                    Zero, Indices));
14708   };
14709 
14710   // Determine maximum split level (byte level masking).
14711   int MaxSplit = 1;
14712   if (RVT.getScalarSizeInBits() % 8 == 0)
14713     MaxSplit = RVT.getScalarSizeInBits() / 8;
14714 
14715   for (int Split = 1; Split <= MaxSplit; ++Split)
14716     if (RVT.getScalarSizeInBits() % Split == 0)
14717       if (SDValue S = BuildClearMask(Split))
14718         return S;
14719 
14720   return SDValue();
14721 }
14722 
14723 /// Visit a binary vector operation, like ADD.
14724 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
14725   assert(N->getValueType(0).isVector() &&
14726          "SimplifyVBinOp only works on vectors!");
14727 
14728   SDValue LHS = N->getOperand(0);
14729   SDValue RHS = N->getOperand(1);
14730   SDValue Ops[] = {LHS, RHS};
14731 
14732   // See if we can constant fold the vector operation.
14733   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
14734           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
14735     return Fold;
14736 
14737   // Try to convert a constant mask AND into a shuffle clear mask.
14738   if (SDValue Shuffle = XformToShuffleWithZero(N))
14739     return Shuffle;
14740 
14741   // Type legalization might introduce new shuffles in the DAG.
14742   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
14743   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
14744   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
14745       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
14746       LHS.getOperand(1).isUndef() &&
14747       RHS.getOperand(1).isUndef()) {
14748     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
14749     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
14750 
14751     if (SVN0->getMask().equals(SVN1->getMask())) {
14752       EVT VT = N->getValueType(0);
14753       SDValue UndefVector = LHS.getOperand(1);
14754       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
14755                                      LHS.getOperand(0), RHS.getOperand(0),
14756                                      N->getFlags());
14757       AddUsersToWorklist(N);
14758       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
14759                                   SVN0->getMask());
14760     }
14761   }
14762 
14763   return SDValue();
14764 }
14765 
14766 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
14767                                     SDValue N2) {
14768   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14769 
14770   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14771                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
14772 
14773   // If we got a simplified select_cc node back from SimplifySelectCC, then
14774   // break it down into a new SETCC node, and a new SELECT node, and then return
14775   // the SELECT node, since we were called with a SELECT node.
14776   if (SCC.getNode()) {
14777     // Check to see if we got a select_cc back (to turn into setcc/select).
14778     // Otherwise, just return whatever node we got back, like fabs.
14779     if (SCC.getOpcode() == ISD::SELECT_CC) {
14780       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14781                                   N0.getValueType(),
14782                                   SCC.getOperand(0), SCC.getOperand(1),
14783                                   SCC.getOperand(4));
14784       AddToWorklist(SETCC.getNode());
14785       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14786                            SCC.getOperand(2), SCC.getOperand(3));
14787     }
14788 
14789     return SCC;
14790   }
14791   return SDValue();
14792 }
14793 
14794 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14795 /// being selected between, see if we can simplify the select.  Callers of this
14796 /// should assume that TheSelect is deleted if this returns true.  As such, they
14797 /// should return the appropriate thing (e.g. the node) back to the top-level of
14798 /// the DAG combiner loop to avoid it being looked at.
14799 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14800                                     SDValue RHS) {
14801 
14802   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14803   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14804   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14805     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14806       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14807       SDValue Sqrt = RHS;
14808       ISD::CondCode CC;
14809       SDValue CmpLHS;
14810       const ConstantFPSDNode *Zero = nullptr;
14811 
14812       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14813         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14814         CmpLHS = TheSelect->getOperand(0);
14815         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14816       } else {
14817         // SELECT or VSELECT
14818         SDValue Cmp = TheSelect->getOperand(0);
14819         if (Cmp.getOpcode() == ISD::SETCC) {
14820           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14821           CmpLHS = Cmp.getOperand(0);
14822           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14823         }
14824       }
14825       if (Zero && Zero->isZero() &&
14826           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14827           CC == ISD::SETULT || CC == ISD::SETLT)) {
14828         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14829         CombineTo(TheSelect, Sqrt);
14830         return true;
14831       }
14832     }
14833   }
14834   // Cannot simplify select with vector condition
14835   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14836 
14837   // If this is a select from two identical things, try to pull the operation
14838   // through the select.
14839   if (LHS.getOpcode() != RHS.getOpcode() ||
14840       !LHS.hasOneUse() || !RHS.hasOneUse())
14841     return false;
14842 
14843   // If this is a load and the token chain is identical, replace the select
14844   // of two loads with a load through a select of the address to load from.
14845   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14846   // constants have been dropped into the constant pool.
14847   if (LHS.getOpcode() == ISD::LOAD) {
14848     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14849     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14850 
14851     // Token chains must be identical.
14852     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14853         // Do not let this transformation reduce the number of volatile loads.
14854         LLD->isVolatile() || RLD->isVolatile() ||
14855         // FIXME: If either is a pre/post inc/dec load,
14856         // we'd need to split out the address adjustment.
14857         LLD->isIndexed() || RLD->isIndexed() ||
14858         // If this is an EXTLOAD, the VT's must match.
14859         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14860         // If this is an EXTLOAD, the kind of extension must match.
14861         (LLD->getExtensionType() != RLD->getExtensionType() &&
14862          // The only exception is if one of the extensions is anyext.
14863          LLD->getExtensionType() != ISD::EXTLOAD &&
14864          RLD->getExtensionType() != ISD::EXTLOAD) ||
14865         // FIXME: this discards src value information.  This is
14866         // over-conservative. It would be beneficial to be able to remember
14867         // both potential memory locations.  Since we are discarding
14868         // src value info, don't do the transformation if the memory
14869         // locations are not in the default address space.
14870         LLD->getPointerInfo().getAddrSpace() != 0 ||
14871         RLD->getPointerInfo().getAddrSpace() != 0 ||
14872         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14873                                       LLD->getBasePtr().getValueType()))
14874       return false;
14875 
14876     // Check that the select condition doesn't reach either load.  If so,
14877     // folding this will induce a cycle into the DAG.  If not, this is safe to
14878     // xform, so create a select of the addresses.
14879     SDValue Addr;
14880     if (TheSelect->getOpcode() == ISD::SELECT) {
14881       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14882       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14883           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14884         return false;
14885       // The loads must not depend on one another.
14886       if (LLD->isPredecessorOf(RLD) ||
14887           RLD->isPredecessorOf(LLD))
14888         return false;
14889       Addr = DAG.getSelect(SDLoc(TheSelect),
14890                            LLD->getBasePtr().getValueType(),
14891                            TheSelect->getOperand(0), LLD->getBasePtr(),
14892                            RLD->getBasePtr());
14893     } else {  // Otherwise SELECT_CC
14894       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14895       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14896 
14897       if ((LLD->hasAnyUseOfValue(1) &&
14898            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14899           (RLD->hasAnyUseOfValue(1) &&
14900            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14901         return false;
14902 
14903       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14904                          LLD->getBasePtr().getValueType(),
14905                          TheSelect->getOperand(0),
14906                          TheSelect->getOperand(1),
14907                          LLD->getBasePtr(), RLD->getBasePtr(),
14908                          TheSelect->getOperand(4));
14909     }
14910 
14911     SDValue Load;
14912     // It is safe to replace the two loads if they have different alignments,
14913     // but the new load must be the minimum (most restrictive) alignment of the
14914     // inputs.
14915     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14916     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14917     if (!RLD->isInvariant())
14918       MMOFlags &= ~MachineMemOperand::MOInvariant;
14919     if (!RLD->isDereferenceable())
14920       MMOFlags &= ~MachineMemOperand::MODereferenceable;
14921     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14922       // FIXME: Discards pointer and AA info.
14923       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14924                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14925                          MMOFlags);
14926     } else {
14927       // FIXME: Discards pointer and AA info.
14928       Load = DAG.getExtLoad(
14929           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14930                                                   : LLD->getExtensionType(),
14931           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14932           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14933     }
14934 
14935     // Users of the select now use the result of the load.
14936     CombineTo(TheSelect, Load);
14937 
14938     // Users of the old loads now use the new load's chain.  We know the
14939     // old-load value is dead now.
14940     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14941     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14942     return true;
14943   }
14944 
14945   return false;
14946 }
14947 
14948 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
14949 /// bitwise 'and'.
14950 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
14951                                             SDValue N1, SDValue N2, SDValue N3,
14952                                             ISD::CondCode CC) {
14953   // If this is a select where the false operand is zero and the compare is a
14954   // check of the sign bit, see if we can perform the "gzip trick":
14955   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
14956   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
14957   EVT XType = N0.getValueType();
14958   EVT AType = N2.getValueType();
14959   if (!isNullConstant(N3) || !XType.bitsGE(AType))
14960     return SDValue();
14961 
14962   // If the comparison is testing for a positive value, we have to invert
14963   // the sign bit mask, so only do that transform if the target has a bitwise
14964   // 'and not' instruction (the invert is free).
14965   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
14966     // (X > -1) ? A : 0
14967     // (X >  0) ? X : 0 <-- This is canonical signed max.
14968     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
14969       return SDValue();
14970   } else if (CC == ISD::SETLT) {
14971     // (X <  0) ? A : 0
14972     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
14973     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
14974       return SDValue();
14975   } else {
14976     return SDValue();
14977   }
14978 
14979   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
14980   // constant.
14981   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
14982   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14983   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14984     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
14985     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
14986     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
14987     AddToWorklist(Shift.getNode());
14988 
14989     if (XType.bitsGT(AType)) {
14990       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14991       AddToWorklist(Shift.getNode());
14992     }
14993 
14994     if (CC == ISD::SETGT)
14995       Shift = DAG.getNOT(DL, Shift, AType);
14996 
14997     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14998   }
14999 
15000   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
15001   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
15002   AddToWorklist(Shift.getNode());
15003 
15004   if (XType.bitsGT(AType)) {
15005     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15006     AddToWorklist(Shift.getNode());
15007   }
15008 
15009   if (CC == ISD::SETGT)
15010     Shift = DAG.getNOT(DL, Shift, AType);
15011 
15012   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15013 }
15014 
15015 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
15016 /// where 'cond' is the comparison specified by CC.
15017 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
15018                                       SDValue N2, SDValue N3, ISD::CondCode CC,
15019                                       bool NotExtCompare) {
15020   // (x ? y : y) -> y.
15021   if (N2 == N3) return N2;
15022 
15023   EVT VT = N2.getValueType();
15024   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
15025   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15026 
15027   // Determine if the condition we're dealing with is constant
15028   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
15029                               N0, N1, CC, DL, false);
15030   if (SCC.getNode()) AddToWorklist(SCC.getNode());
15031 
15032   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
15033     // fold select_cc true, x, y -> x
15034     // fold select_cc false, x, y -> y
15035     return !SCCC->isNullValue() ? N2 : N3;
15036   }
15037 
15038   // Check to see if we can simplify the select into an fabs node
15039   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
15040     // Allow either -0.0 or 0.0
15041     if (CFP->isZero()) {
15042       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
15043       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
15044           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
15045           N2 == N3.getOperand(0))
15046         return DAG.getNode(ISD::FABS, DL, VT, N0);
15047 
15048       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
15049       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
15050           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
15051           N2.getOperand(0) == N3)
15052         return DAG.getNode(ISD::FABS, DL, VT, N3);
15053     }
15054   }
15055 
15056   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
15057   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
15058   // in it.  This is a win when the constant is not otherwise available because
15059   // it replaces two constant pool loads with one.  We only do this if the FP
15060   // type is known to be legal, because if it isn't, then we are before legalize
15061   // types an we want the other legalization to happen first (e.g. to avoid
15062   // messing with soft float) and if the ConstantFP is not legal, because if
15063   // it is legal, we may not need to store the FP constant in a constant pool.
15064   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
15065     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
15066       if (TLI.isTypeLegal(N2.getValueType()) &&
15067           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
15068                TargetLowering::Legal &&
15069            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
15070            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
15071           // If both constants have multiple uses, then we won't need to do an
15072           // extra load, they are likely around in registers for other users.
15073           (TV->hasOneUse() || FV->hasOneUse())) {
15074         Constant *Elts[] = {
15075           const_cast<ConstantFP*>(FV->getConstantFPValue()),
15076           const_cast<ConstantFP*>(TV->getConstantFPValue())
15077         };
15078         Type *FPTy = Elts[0]->getType();
15079         const DataLayout &TD = DAG.getDataLayout();
15080 
15081         // Create a ConstantArray of the two constants.
15082         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
15083         SDValue CPIdx =
15084             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
15085                                 TD.getPrefTypeAlignment(FPTy));
15086         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
15087 
15088         // Get the offsets to the 0 and 1 element of the array so that we can
15089         // select between them.
15090         SDValue Zero = DAG.getIntPtrConstant(0, DL);
15091         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
15092         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
15093 
15094         SDValue Cond = DAG.getSetCC(DL,
15095                                     getSetCCResultType(N0.getValueType()),
15096                                     N0, N1, CC);
15097         AddToWorklist(Cond.getNode());
15098         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
15099                                           Cond, One, Zero);
15100         AddToWorklist(CstOffset.getNode());
15101         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
15102                             CstOffset);
15103         AddToWorklist(CPIdx.getNode());
15104         return DAG.getLoad(
15105             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
15106             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
15107             Alignment);
15108       }
15109     }
15110 
15111   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
15112     return V;
15113 
15114   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
15115   // where y is has a single bit set.
15116   // A plaintext description would be, we can turn the SELECT_CC into an AND
15117   // when the condition can be materialized as an all-ones register.  Any
15118   // single bit-test can be materialized as an all-ones register with
15119   // shift-left and shift-right-arith.
15120   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
15121       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
15122     SDValue AndLHS = N0->getOperand(0);
15123     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
15124     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
15125       // Shift the tested bit over the sign bit.
15126       const APInt &AndMask = ConstAndRHS->getAPIntValue();
15127       SDValue ShlAmt =
15128         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
15129                         getShiftAmountTy(AndLHS.getValueType()));
15130       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
15131 
15132       // Now arithmetic right shift it all the way over, so the result is either
15133       // all-ones, or zero.
15134       SDValue ShrAmt =
15135         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
15136                         getShiftAmountTy(Shl.getValueType()));
15137       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
15138 
15139       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
15140     }
15141   }
15142 
15143   // fold select C, 16, 0 -> shl C, 4
15144   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
15145       TLI.getBooleanContents(N0.getValueType()) ==
15146           TargetLowering::ZeroOrOneBooleanContent) {
15147 
15148     // If the caller doesn't want us to simplify this into a zext of a compare,
15149     // don't do it.
15150     if (NotExtCompare && N2C->isOne())
15151       return SDValue();
15152 
15153     // Get a SetCC of the condition
15154     // NOTE: Don't create a SETCC if it's not legal on this target.
15155     if (!LegalOperations ||
15156         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
15157       SDValue Temp, SCC;
15158       // cast from setcc result type to select result type
15159       if (LegalTypes) {
15160         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
15161                             N0, N1, CC);
15162         if (N2.getValueType().bitsLT(SCC.getValueType()))
15163           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
15164                                         N2.getValueType());
15165         else
15166           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15167                              N2.getValueType(), SCC);
15168       } else {
15169         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
15170         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15171                            N2.getValueType(), SCC);
15172       }
15173 
15174       AddToWorklist(SCC.getNode());
15175       AddToWorklist(Temp.getNode());
15176 
15177       if (N2C->isOne())
15178         return Temp;
15179 
15180       // shl setcc result by log2 n2c
15181       return DAG.getNode(
15182           ISD::SHL, DL, N2.getValueType(), Temp,
15183           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
15184                           getShiftAmountTy(Temp.getValueType())));
15185     }
15186   }
15187 
15188   // Check to see if this is an integer abs.
15189   // select_cc setg[te] X,  0,  X, -X ->
15190   // select_cc setgt    X, -1,  X, -X ->
15191   // select_cc setl[te] X,  0, -X,  X ->
15192   // select_cc setlt    X,  1, -X,  X ->
15193   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
15194   if (N1C) {
15195     ConstantSDNode *SubC = nullptr;
15196     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
15197          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
15198         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
15199       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
15200     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
15201               (N1C->isOne() && CC == ISD::SETLT)) &&
15202              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
15203       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
15204 
15205     EVT XType = N0.getValueType();
15206     if (SubC && SubC->isNullValue() && XType.isInteger()) {
15207       SDLoc DL(N0);
15208       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
15209                                   N0,
15210                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
15211                                          getShiftAmountTy(N0.getValueType())));
15212       SDValue Add = DAG.getNode(ISD::ADD, DL,
15213                                 XType, N0, Shift);
15214       AddToWorklist(Shift.getNode());
15215       AddToWorklist(Add.getNode());
15216       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
15217     }
15218   }
15219 
15220   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
15221   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
15222   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
15223   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
15224   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
15225   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
15226   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
15227   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
15228   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15229     SDValue ValueOnZero = N2;
15230     SDValue Count = N3;
15231     // If the condition is NE instead of E, swap the operands.
15232     if (CC == ISD::SETNE)
15233       std::swap(ValueOnZero, Count);
15234     // Check if the value on zero is a constant equal to the bits in the type.
15235     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
15236       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
15237         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
15238         // legal, combine to just cttz.
15239         if ((Count.getOpcode() == ISD::CTTZ ||
15240              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
15241             N0 == Count.getOperand(0) &&
15242             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
15243           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
15244         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
15245         // legal, combine to just ctlz.
15246         if ((Count.getOpcode() == ISD::CTLZ ||
15247              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
15248             N0 == Count.getOperand(0) &&
15249             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
15250           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
15251       }
15252     }
15253   }
15254 
15255   return SDValue();
15256 }
15257 
15258 /// This is a stub for TargetLowering::SimplifySetCC.
15259 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
15260                                    ISD::CondCode Cond, const SDLoc &DL,
15261                                    bool foldBooleans) {
15262   TargetLowering::DAGCombinerInfo
15263     DagCombineInfo(DAG, Level, false, this);
15264   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
15265 }
15266 
15267 /// Given an ISD::SDIV node expressing a divide by constant, return
15268 /// a DAG expression to select that will generate the same value by multiplying
15269 /// by a magic number.
15270 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15271 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
15272   // when optimising for minimum size, we don't want to expand a div to a mul
15273   // and a shift.
15274   if (DAG.getMachineFunction().getFunction()->optForMinSize())
15275     return SDValue();
15276 
15277   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15278   if (!C)
15279     return SDValue();
15280 
15281   // Avoid division by zero.
15282   if (C->isNullValue())
15283     return SDValue();
15284 
15285   std::vector<SDNode*> Built;
15286   SDValue S =
15287       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15288 
15289   for (SDNode *N : Built)
15290     AddToWorklist(N);
15291   return S;
15292 }
15293 
15294 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
15295 /// DAG expression that will generate the same value by right shifting.
15296 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
15297   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15298   if (!C)
15299     return SDValue();
15300 
15301   // Avoid division by zero.
15302   if (C->isNullValue())
15303     return SDValue();
15304 
15305   std::vector<SDNode *> Built;
15306   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
15307 
15308   for (SDNode *N : Built)
15309     AddToWorklist(N);
15310   return S;
15311 }
15312 
15313 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
15314 /// expression that will generate the same value by multiplying by a magic
15315 /// number.
15316 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15317 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
15318   // when optimising for minimum size, we don't want to expand a div to a mul
15319   // and a shift.
15320   if (DAG.getMachineFunction().getFunction()->optForMinSize())
15321     return SDValue();
15322 
15323   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15324   if (!C)
15325     return SDValue();
15326 
15327   // Avoid division by zero.
15328   if (C->isNullValue())
15329     return SDValue();
15330 
15331   std::vector<SDNode*> Built;
15332   SDValue S =
15333       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15334 
15335   for (SDNode *N : Built)
15336     AddToWorklist(N);
15337   return S;
15338 }
15339 
15340 /// Determines the LogBase2 value for a non-null input value using the
15341 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
15342 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
15343   EVT VT = V.getValueType();
15344   unsigned EltBits = VT.getScalarSizeInBits();
15345   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
15346   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
15347   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
15348   return LogBase2;
15349 }
15350 
15351 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15352 /// For the reciprocal, we need to find the zero of the function:
15353 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
15354 ///     =>
15355 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
15356 ///     does not require additional intermediate precision]
15357 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
15358   if (Level >= AfterLegalizeDAG)
15359     return SDValue();
15360 
15361   // TODO: Handle half and/or extended types?
15362   EVT VT = Op.getValueType();
15363   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15364     return SDValue();
15365 
15366   // If estimates are explicitly disabled for this function, we're done.
15367   MachineFunction &MF = DAG.getMachineFunction();
15368   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
15369   if (Enabled == TLI.ReciprocalEstimate::Disabled)
15370     return SDValue();
15371 
15372   // Estimates may be explicitly enabled for this type with a custom number of
15373   // refinement steps.
15374   int Iterations = TLI.getDivRefinementSteps(VT, MF);
15375   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
15376     AddToWorklist(Est.getNode());
15377 
15378     if (Iterations) {
15379       EVT VT = Op.getValueType();
15380       SDLoc DL(Op);
15381       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
15382 
15383       // Newton iterations: Est = Est + Est (1 - Arg * Est)
15384       for (int i = 0; i < Iterations; ++i) {
15385         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
15386         AddToWorklist(NewEst.getNode());
15387 
15388         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
15389         AddToWorklist(NewEst.getNode());
15390 
15391         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15392         AddToWorklist(NewEst.getNode());
15393 
15394         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
15395         AddToWorklist(Est.getNode());
15396       }
15397     }
15398     return Est;
15399   }
15400 
15401   return SDValue();
15402 }
15403 
15404 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15405 /// For the reciprocal sqrt, we need to find the zero of the function:
15406 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15407 ///     =>
15408 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
15409 /// As a result, we precompute A/2 prior to the iteration loop.
15410 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
15411                                          unsigned Iterations,
15412                                          SDNodeFlags *Flags, bool Reciprocal) {
15413   EVT VT = Arg.getValueType();
15414   SDLoc DL(Arg);
15415   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
15416 
15417   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
15418   // this entire sequence requires only one FP constant.
15419   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
15420   AddToWorklist(HalfArg.getNode());
15421 
15422   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
15423   AddToWorklist(HalfArg.getNode());
15424 
15425   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
15426   for (unsigned i = 0; i < Iterations; ++i) {
15427     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
15428     AddToWorklist(NewEst.getNode());
15429 
15430     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
15431     AddToWorklist(NewEst.getNode());
15432 
15433     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
15434     AddToWorklist(NewEst.getNode());
15435 
15436     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15437     AddToWorklist(Est.getNode());
15438   }
15439 
15440   // If non-reciprocal square root is requested, multiply the result by Arg.
15441   if (!Reciprocal) {
15442     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
15443     AddToWorklist(Est.getNode());
15444   }
15445 
15446   return Est;
15447 }
15448 
15449 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15450 /// For the reciprocal sqrt, we need to find the zero of the function:
15451 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15452 ///     =>
15453 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
15454 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
15455                                          unsigned Iterations,
15456                                          SDNodeFlags *Flags, bool Reciprocal) {
15457   EVT VT = Arg.getValueType();
15458   SDLoc DL(Arg);
15459   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
15460   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
15461 
15462   // This routine must enter the loop below to work correctly
15463   // when (Reciprocal == false).
15464   assert(Iterations > 0);
15465 
15466   // Newton iterations for reciprocal square root:
15467   // E = (E * -0.5) * ((A * E) * E + -3.0)
15468   for (unsigned i = 0; i < Iterations; ++i) {
15469     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15470     AddToWorklist(AE.getNode());
15471 
15472     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15473     AddToWorklist(AEE.getNode());
15474 
15475     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15476     AddToWorklist(RHS.getNode());
15477 
15478     // When calculating a square root at the last iteration build:
15479     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15480     // (notice a common subexpression)
15481     SDValue LHS;
15482     if (Reciprocal || (i + 1) < Iterations) {
15483       // RSQRT: LHS = (E * -0.5)
15484       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15485     } else {
15486       // SQRT: LHS = (A * E) * -0.5
15487       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15488     }
15489     AddToWorklist(LHS.getNode());
15490 
15491     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15492     AddToWorklist(Est.getNode());
15493   }
15494 
15495   return Est;
15496 }
15497 
15498 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15499 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15500 /// Op can be zero.
15501 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15502                                            bool Reciprocal) {
15503   if (Level >= AfterLegalizeDAG)
15504     return SDValue();
15505 
15506   // TODO: Handle half and/or extended types?
15507   EVT VT = Op.getValueType();
15508   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15509     return SDValue();
15510 
15511   // If estimates are explicitly disabled for this function, we're done.
15512   MachineFunction &MF = DAG.getMachineFunction();
15513   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
15514   if (Enabled == TLI.ReciprocalEstimate::Disabled)
15515     return SDValue();
15516 
15517   // Estimates may be explicitly enabled for this type with a custom number of
15518   // refinement steps.
15519   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
15520 
15521   bool UseOneConstNR = false;
15522   if (SDValue Est =
15523       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
15524                           Reciprocal)) {
15525     AddToWorklist(Est.getNode());
15526 
15527     if (Iterations) {
15528       Est = UseOneConstNR
15529             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
15530             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
15531 
15532       if (!Reciprocal) {
15533         // Unfortunately, Est is now NaN if the input was exactly 0.0.
15534         // Select out this case and force the answer to 0.0.
15535         EVT VT = Op.getValueType();
15536         SDLoc DL(Op);
15537 
15538         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
15539         EVT CCVT = getSetCCResultType(VT);
15540         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
15541         AddToWorklist(ZeroCmp.getNode());
15542 
15543         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
15544                           ZeroCmp, FPZero, Est);
15545         AddToWorklist(Est.getNode());
15546       }
15547     }
15548     return Est;
15549   }
15550 
15551   return SDValue();
15552 }
15553 
15554 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15555   return buildSqrtEstimateImpl(Op, Flags, true);
15556 }
15557 
15558 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15559   return buildSqrtEstimateImpl(Op, Flags, false);
15560 }
15561 
15562 /// Return true if base is a frame index, which is known not to alias with
15563 /// anything but itself.  Provides base object and offset as results.
15564 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
15565                            const GlobalValue *&GV, const void *&CV) {
15566   // Assume it is a primitive operation.
15567   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
15568 
15569   // If it's an adding a simple constant then integrate the offset.
15570   if (Base.getOpcode() == ISD::ADD) {
15571     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
15572       Base = Base.getOperand(0);
15573       Offset += C->getZExtValue();
15574     }
15575   }
15576 
15577   // Return the underlying GlobalValue, and update the Offset.  Return false
15578   // for GlobalAddressSDNode since the same GlobalAddress may be represented
15579   // by multiple nodes with different offsets.
15580   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
15581     GV = G->getGlobal();
15582     Offset += G->getOffset();
15583     return false;
15584   }
15585 
15586   // Return the underlying Constant value, and update the Offset.  Return false
15587   // for ConstantSDNodes since the same constant pool entry may be represented
15588   // by multiple nodes with different offsets.
15589   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
15590     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
15591                                          : (const void *)C->getConstVal();
15592     Offset += C->getOffset();
15593     return false;
15594   }
15595   // If it's any of the following then it can't alias with anything but itself.
15596   return isa<FrameIndexSDNode>(Base);
15597 }
15598 
15599 /// Return true if there is any possibility that the two addresses overlap.
15600 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
15601   // If they are the same then they must be aliases.
15602   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
15603 
15604   // If they are both volatile then they cannot be reordered.
15605   if (Op0->isVolatile() && Op1->isVolatile()) return true;
15606 
15607   // If one operation reads from invariant memory, and the other may store, they
15608   // cannot alias. These should really be checking the equivalent of mayWrite,
15609   // but it only matters for memory nodes other than load /store.
15610   if (Op0->isInvariant() && Op1->writeMem())
15611     return false;
15612 
15613   if (Op1->isInvariant() && Op0->writeMem())
15614     return false;
15615 
15616   // Gather base node and offset information.
15617   SDValue Base1, Base2;
15618   int64_t Offset1, Offset2;
15619   const GlobalValue *GV1, *GV2;
15620   const void *CV1, *CV2;
15621   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
15622                                       Base1, Offset1, GV1, CV1);
15623   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
15624                                       Base2, Offset2, GV2, CV2);
15625 
15626   // If they have a same base address then check to see if they overlap.
15627   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
15628     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15629              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15630 
15631   // It is possible for different frame indices to alias each other, mostly
15632   // when tail call optimization reuses return address slots for arguments.
15633   // To catch this case, look up the actual index of frame indices to compute
15634   // the real alias relationship.
15635   if (isFrameIndex1 && isFrameIndex2) {
15636     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
15637     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
15638     Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
15639     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15640              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15641   }
15642 
15643   // Otherwise, if we know what the bases are, and they aren't identical, then
15644   // we know they cannot alias.
15645   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
15646     return false;
15647 
15648   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
15649   // compared to the size and offset of the access, we may be able to prove they
15650   // do not alias.  This check is conservative for now to catch cases created by
15651   // splitting vector types.
15652   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
15653       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
15654       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
15655        Op1->getMemoryVT().getSizeInBits() >> 3) &&
15656       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
15657     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
15658     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
15659 
15660     // There is no overlap between these relatively aligned accesses of similar
15661     // size, return no alias.
15662     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
15663         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
15664       return false;
15665   }
15666 
15667   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
15668                    ? CombinerGlobalAA
15669                    : DAG.getSubtarget().useAA();
15670 #ifndef NDEBUG
15671   if (CombinerAAOnlyFunc.getNumOccurrences() &&
15672       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
15673     UseAA = false;
15674 #endif
15675   if (UseAA &&
15676       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
15677     // Use alias analysis information.
15678     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
15679                                  Op1->getSrcValueOffset());
15680     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
15681         Op0->getSrcValueOffset() - MinOffset;
15682     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
15683         Op1->getSrcValueOffset() - MinOffset;
15684     AliasResult AAResult =
15685         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
15686                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
15687                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
15688                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
15689     if (AAResult == NoAlias)
15690       return false;
15691   }
15692 
15693   // Otherwise we have to assume they alias.
15694   return true;
15695 }
15696 
15697 /// Walk up chain skipping non-aliasing memory nodes,
15698 /// looking for aliasing nodes and adding them to the Aliases vector.
15699 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
15700                                    SmallVectorImpl<SDValue> &Aliases) {
15701   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
15702   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
15703 
15704   // Get alias information for node.
15705   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
15706 
15707   // Starting off.
15708   Chains.push_back(OriginalChain);
15709   unsigned Depth = 0;
15710 
15711   // Look at each chain and determine if it is an alias.  If so, add it to the
15712   // aliases list.  If not, then continue up the chain looking for the next
15713   // candidate.
15714   while (!Chains.empty()) {
15715     SDValue Chain = Chains.pop_back_val();
15716 
15717     // For TokenFactor nodes, look at each operand and only continue up the
15718     // chain until we reach the depth limit.
15719     //
15720     // FIXME: The depth check could be made to return the last non-aliasing
15721     // chain we found before we hit a tokenfactor rather than the original
15722     // chain.
15723     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
15724       Aliases.clear();
15725       Aliases.push_back(OriginalChain);
15726       return;
15727     }
15728 
15729     // Don't bother if we've been before.
15730     if (!Visited.insert(Chain.getNode()).second)
15731       continue;
15732 
15733     switch (Chain.getOpcode()) {
15734     case ISD::EntryToken:
15735       // Entry token is ideal chain operand, but handled in FindBetterChain.
15736       break;
15737 
15738     case ISD::LOAD:
15739     case ISD::STORE: {
15740       // Get alias information for Chain.
15741       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
15742           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
15743 
15744       // If chain is alias then stop here.
15745       if (!(IsLoad && IsOpLoad) &&
15746           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
15747         Aliases.push_back(Chain);
15748       } else {
15749         // Look further up the chain.
15750         Chains.push_back(Chain.getOperand(0));
15751         ++Depth;
15752       }
15753       break;
15754     }
15755 
15756     case ISD::TokenFactor:
15757       // We have to check each of the operands of the token factor for "small"
15758       // token factors, so we queue them up.  Adding the operands to the queue
15759       // (stack) in reverse order maintains the original order and increases the
15760       // likelihood that getNode will find a matching token factor (CSE.)
15761       if (Chain.getNumOperands() > 16) {
15762         Aliases.push_back(Chain);
15763         break;
15764       }
15765       for (unsigned n = Chain.getNumOperands(); n;)
15766         Chains.push_back(Chain.getOperand(--n));
15767       ++Depth;
15768       break;
15769 
15770     default:
15771       // For all other instructions we will just have to take what we can get.
15772       Aliases.push_back(Chain);
15773       break;
15774     }
15775   }
15776 }
15777 
15778 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
15779 /// (aliasing node.)
15780 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
15781   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
15782 
15783   // Accumulate all the aliases to this node.
15784   GatherAllAliases(N, OldChain, Aliases);
15785 
15786   // If no operands then chain to entry token.
15787   if (Aliases.size() == 0)
15788     return DAG.getEntryNode();
15789 
15790   // If a single operand then chain to it.  We don't need to revisit it.
15791   if (Aliases.size() == 1)
15792     return Aliases[0];
15793 
15794   // Construct a custom tailored token factor.
15795   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
15796 }
15797 
15798 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
15799   // This holds the base pointer, index, and the offset in bytes from the base
15800   // pointer.
15801   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
15802 
15803   // We must have a base and an offset.
15804   if (!BasePtr.Base.getNode())
15805     return false;
15806 
15807   // Do not handle stores to undef base pointers.
15808   if (BasePtr.Base.isUndef())
15809     return false;
15810 
15811   SmallVector<StoreSDNode *, 8> ChainedStores;
15812   ChainedStores.push_back(St);
15813 
15814   // Walk up the chain and look for nodes with offsets from the same
15815   // base pointer. Stop when reaching an instruction with a different kind
15816   // or instruction which has a different base pointer.
15817   StoreSDNode *Index = St;
15818   while (Index) {
15819     // If the chain has more than one use, then we can't reorder the mem ops.
15820     if (Index != St && !SDValue(Index, 0)->hasOneUse())
15821       break;
15822 
15823     if (Index->isVolatile() || Index->isIndexed())
15824       break;
15825 
15826     // Find the base pointer and offset for this memory node.
15827     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
15828 
15829     // Check that the base pointer is the same as the original one.
15830     if (!Ptr.equalBaseIndex(BasePtr))
15831       break;
15832 
15833     // Find the next memory operand in the chain. If the next operand in the
15834     // chain is a store then move up and continue the scan with the next
15835     // memory operand. If the next operand is a load save it and use alias
15836     // information to check if it interferes with anything.
15837     SDNode *NextInChain = Index->getChain().getNode();
15838     while (true) {
15839       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
15840         // We found a store node. Use it for the next iteration.
15841         if (STn->isVolatile() || STn->isIndexed()) {
15842           Index = nullptr;
15843           break;
15844         }
15845         ChainedStores.push_back(STn);
15846         Index = STn;
15847         break;
15848       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
15849         NextInChain = Ldn->getChain().getNode();
15850         continue;
15851       } else {
15852         Index = nullptr;
15853         break;
15854       }
15855     }
15856   }
15857 
15858   bool MadeChangeToSt = false;
15859   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15860 
15861   for (StoreSDNode *ChainedStore : ChainedStores) {
15862     SDValue Chain = ChainedStore->getChain();
15863     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15864 
15865     if (Chain != BetterChain) {
15866       if (ChainedStore == St)
15867         MadeChangeToSt = true;
15868       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15869     }
15870   }
15871 
15872   // Do all replacements after finding the replacements to make to avoid making
15873   // the chains more complicated by introducing new TokenFactors.
15874   for (auto Replacement : BetterChains)
15875     replaceStoreChain(Replacement.first, Replacement.second);
15876 
15877   return MadeChangeToSt;
15878 }
15879 
15880 /// This is the entry point for the file.
15881 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15882                            CodeGenOpt::Level OptLevel) {
15883   /// This is the main entry point to this class.
15884   DAGCombiner(*this, AA, OptLevel).Run(Level);
15885 }
15886