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/SelectionDAGAddressAnalysis.h"
29 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44 #include <algorithm>
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "dagcombine"
48 
49 STATISTIC(NodesCombined   , "Number of dag nodes combined");
50 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
51 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
52 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
53 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
54 STATISTIC(SlicedLoads, "Number of load sliced");
55 
56 namespace {
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60 
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64 
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71 
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79 
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83 
84 //------------------------------ DAGCombiner ---------------------------------//
85 
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94 
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103 
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110 
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 32> CombinedNodes;
116 
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis *AA;
119 
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126 
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129 
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       assert(N->getOpcode() != ISD::DELETED_NODE &&
135              "Deleted Node added to Worklist");
136 
137       // Skip handle nodes as they can't usefully be combined and confuse the
138       // zero-use deletion strategy.
139       if (N->getOpcode() == ISD::HANDLENODE)
140         return;
141 
142       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
143         Worklist.push_back(N);
144     }
145 
146     /// Remove all instances of N from the worklist.
147     void removeFromWorklist(SDNode *N) {
148       CombinedNodes.erase(N);
149 
150       auto It = WorklistMap.find(N);
151       if (It == WorklistMap.end())
152         return; // Not in the worklist.
153 
154       // Null out the entry rather than erasing it to avoid a linear operation.
155       Worklist[It->second] = nullptr;
156       WorklistMap.erase(It);
157     }
158 
159     void deleteAndRecombine(SDNode *N);
160     bool recursivelyDeleteUnusedNodes(SDNode *N);
161 
162     /// Replaces all uses of the results of one DAG node with new values.
163     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
164                       bool AddTo = true);
165 
166     /// Replaces all uses of the results of one DAG node with new values.
167     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
168       return CombineTo(N, &Res, 1, AddTo);
169     }
170 
171     /// Replaces all uses of the results of one DAG node with new values.
172     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
173                       bool AddTo = true) {
174       SDValue To[] = { Res0, Res1 };
175       return CombineTo(N, To, 2, AddTo);
176     }
177 
178     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
179 
180   private:
181     unsigned MaximumLegalStoreInBits;
182 
183     /// Check the specified integer node value to see if it can be simplified or
184     /// if things it uses can be simplified by bit propagation.
185     /// If so, return true.
186     bool SimplifyDemandedBits(SDValue Op) {
187       unsigned BitWidth = Op.getScalarValueSizeInBits();
188       APInt Demanded = APInt::getAllOnesValue(BitWidth);
189       return SimplifyDemandedBits(Op, Demanded);
190     }
191 
192     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
193 
194     bool CombineToPreIndexedLoadStore(SDNode *N);
195     bool CombineToPostIndexedLoadStore(SDNode *N);
196     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
197     bool SliceUpLoad(SDNode *N);
198 
199     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
200     ///   load.
201     ///
202     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
203     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
204     /// \param EltNo index of the vector element to load.
205     /// \param OriginalLoad load that EVE came from to be replaced.
206     /// \returns EVE on success SDValue() on failure.
207     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
208         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
209     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
210     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
211     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
212     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
213     SDValue PromoteIntBinOp(SDValue Op);
214     SDValue PromoteIntShiftOp(SDValue Op);
215     SDValue PromoteExtend(SDValue Op);
216     bool PromoteLoad(SDValue Op);
217 
218     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
219                          SDValue ExtLoad, const SDLoc &DL,
220                          ISD::NodeType ExtType);
221 
222     /// Call the node-specific routine that knows how to fold each
223     /// particular type of node. If that doesn't do anything, try the
224     /// target-specific DAG combines.
225     SDValue combine(SDNode *N);
226 
227     // Visitation implementation - Implement dag node combining for different
228     // node types.  The semantics are as follows:
229     // Return Value:
230     //   SDValue.getNode() == 0 - No change was made
231     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
232     //   otherwise              - N should be replaced by the returned Operand.
233     //
234     SDValue visitTokenFactor(SDNode *N);
235     SDValue visitMERGE_VALUES(SDNode *N);
236     SDValue visitADD(SDNode *N);
237     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
238     SDValue visitSUB(SDNode *N);
239     SDValue visitADDC(SDNode *N);
240     SDValue visitUADDO(SDNode *N);
241     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
242     SDValue visitSUBC(SDNode *N);
243     SDValue visitUSUBO(SDNode *N);
244     SDValue visitADDE(SDNode *N);
245     SDValue visitADDCARRY(SDNode *N);
246     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
247     SDValue visitSUBE(SDNode *N);
248     SDValue visitSUBCARRY(SDNode *N);
249     SDValue visitMUL(SDNode *N);
250     SDValue useDivRem(SDNode *N);
251     SDValue visitSDIV(SDNode *N);
252     SDValue visitUDIV(SDNode *N);
253     SDValue visitREM(SDNode *N);
254     SDValue visitMULHU(SDNode *N);
255     SDValue visitMULHS(SDNode *N);
256     SDValue visitSMUL_LOHI(SDNode *N);
257     SDValue visitUMUL_LOHI(SDNode *N);
258     SDValue visitSMULO(SDNode *N);
259     SDValue visitUMULO(SDNode *N);
260     SDValue visitIMINMAX(SDNode *N);
261     SDValue visitAND(SDNode *N);
262     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
263     SDValue visitOR(SDNode *N);
264     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
265     SDValue visitXOR(SDNode *N);
266     SDValue SimplifyVBinOp(SDNode *N);
267     SDValue visitSHL(SDNode *N);
268     SDValue visitSRA(SDNode *N);
269     SDValue visitSRL(SDNode *N);
270     SDValue visitRotate(SDNode *N);
271     SDValue visitABS(SDNode *N);
272     SDValue visitBSWAP(SDNode *N);
273     SDValue visitBITREVERSE(SDNode *N);
274     SDValue visitCTLZ(SDNode *N);
275     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
276     SDValue visitCTTZ(SDNode *N);
277     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
278     SDValue visitCTPOP(SDNode *N);
279     SDValue visitSELECT(SDNode *N);
280     SDValue visitVSELECT(SDNode *N);
281     SDValue visitSELECT_CC(SDNode *N);
282     SDValue visitSETCC(SDNode *N);
283     SDValue visitSETCCE(SDNode *N);
284     SDValue visitSETCCCARRY(SDNode *N);
285     SDValue visitSIGN_EXTEND(SDNode *N);
286     SDValue visitZERO_EXTEND(SDNode *N);
287     SDValue visitANY_EXTEND(SDNode *N);
288     SDValue visitAssertZext(SDNode *N);
289     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
290     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
291     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
292     SDValue visitTRUNCATE(SDNode *N);
293     SDValue visitBITCAST(SDNode *N);
294     SDValue visitBUILD_PAIR(SDNode *N);
295     SDValue visitFADD(SDNode *N);
296     SDValue visitFSUB(SDNode *N);
297     SDValue visitFMUL(SDNode *N);
298     SDValue visitFMA(SDNode *N);
299     SDValue visitFDIV(SDNode *N);
300     SDValue visitFREM(SDNode *N);
301     SDValue visitFSQRT(SDNode *N);
302     SDValue visitFCOPYSIGN(SDNode *N);
303     SDValue visitSINT_TO_FP(SDNode *N);
304     SDValue visitUINT_TO_FP(SDNode *N);
305     SDValue visitFP_TO_SINT(SDNode *N);
306     SDValue visitFP_TO_UINT(SDNode *N);
307     SDValue visitFP_ROUND(SDNode *N);
308     SDValue visitFP_ROUND_INREG(SDNode *N);
309     SDValue visitFP_EXTEND(SDNode *N);
310     SDValue visitFNEG(SDNode *N);
311     SDValue visitFABS(SDNode *N);
312     SDValue visitFCEIL(SDNode *N);
313     SDValue visitFTRUNC(SDNode *N);
314     SDValue visitFFLOOR(SDNode *N);
315     SDValue visitFMINNUM(SDNode *N);
316     SDValue visitFMAXNUM(SDNode *N);
317     SDValue visitBRCOND(SDNode *N);
318     SDValue visitBR_CC(SDNode *N);
319     SDValue visitLOAD(SDNode *N);
320 
321     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
322     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
323 
324     SDValue visitSTORE(SDNode *N);
325     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
326     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
327     SDValue visitBUILD_VECTOR(SDNode *N);
328     SDValue visitCONCAT_VECTORS(SDNode *N);
329     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
330     SDValue visitVECTOR_SHUFFLE(SDNode *N);
331     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
332     SDValue visitINSERT_SUBVECTOR(SDNode *N);
333     SDValue visitMLOAD(SDNode *N);
334     SDValue visitMSTORE(SDNode *N);
335     SDValue visitMGATHER(SDNode *N);
336     SDValue visitMSCATTER(SDNode *N);
337     SDValue visitFP_TO_FP16(SDNode *N);
338     SDValue visitFP16_TO_FP(SDNode *N);
339 
340     SDValue visitFADDForFMACombine(SDNode *N);
341     SDValue visitFSUBForFMACombine(SDNode *N);
342     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
343 
344     SDValue XformToShuffleWithZero(SDNode *N);
345     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
346                            SDValue RHS);
347 
348     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
349 
350     SDValue foldSelectOfConstants(SDNode *N);
351     SDValue foldBinOpIntoSelect(SDNode *BO);
352     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
353     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
354     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
355     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
356                              SDValue N2, SDValue N3, ISD::CondCode CC,
357                              bool NotExtCompare = false);
358     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
359                                    SDValue N2, SDValue N3, ISD::CondCode CC);
360     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
361                               const SDLoc &DL);
362     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
363                           const SDLoc &DL, bool foldBooleans = true);
364 
365     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
366                            SDValue &CC) const;
367     bool isOneUseSetCC(SDValue N) const;
368 
369     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
370                                          unsigned HiOp);
371     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
372     SDValue CombineExtLoad(SDNode *N);
373     SDValue combineRepeatedFPDivisors(SDNode *N);
374     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
375     SDValue BuildSDIV(SDNode *N);
376     SDValue BuildSDIVPow2(SDNode *N);
377     SDValue BuildUDIV(SDNode *N);
378     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
379     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
380     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
381     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
382     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
383     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
384                                 SDNodeFlags Flags, bool Reciprocal);
385     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
386                                 SDNodeFlags Flags, bool Reciprocal);
387     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
388                                bool DemandHighBits = true);
389     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
390     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
391                               SDValue InnerPos, SDValue InnerNeg,
392                               unsigned PosOpcode, unsigned NegOpcode,
393                               const SDLoc &DL);
394     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
395     SDValue MatchLoadCombine(SDNode *N);
396     SDValue ReduceLoadWidth(SDNode *N);
397     SDValue ReduceLoadOpStoreWidth(SDNode *N);
398     SDValue splitMergedValStore(StoreSDNode *ST);
399     SDValue TransformFPLoadStorePair(SDNode *N);
400     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
401     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
402     SDValue reduceBuildVecToShuffle(SDNode *N);
403     SDValue reduceBuildVecToTrunc(SDNode *N);
404     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
405                                   ArrayRef<int> VectorMask, SDValue VecIn1,
406                                   SDValue VecIn2, unsigned LeftIdx);
407     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
408 
409     /// Walk up chain skipping non-aliasing memory nodes,
410     /// looking for aliasing nodes and adding them to the Aliases vector.
411     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
412                           SmallVectorImpl<SDValue> &Aliases);
413 
414     /// Return true if there is any possibility that the two addresses overlap.
415     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
416 
417     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
418     /// chain (aliasing node.)
419     SDValue FindBetterChain(SDNode *N, SDValue Chain);
420 
421     /// Try to replace a store and any possibly adjacent stores on
422     /// consecutive chains with better chains. Return true only if St is
423     /// replaced.
424     ///
425     /// Notice that other chains may still be replaced even if the function
426     /// returns false.
427     bool findBetterNeighborChains(StoreSDNode *St);
428 
429     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
430     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
431 
432     /// Holds a pointer to an LSBaseSDNode as well as information on where it
433     /// is located in a sequence of memory operations connected by a chain.
434     struct MemOpLink {
435       MemOpLink(LSBaseSDNode *N, int64_t Offset)
436           : MemNode(N), OffsetFromBase(Offset) {}
437       // Ptr to the mem node.
438       LSBaseSDNode *MemNode;
439       // Offset from the base ptr.
440       int64_t OffsetFromBase;
441     };
442 
443     /// This is a helper function for visitMUL to check the profitability
444     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
445     /// MulNode is the original multiply, AddNode is (add x, c1),
446     /// and ConstNode is c2.
447     bool isMulAddWithConstProfitable(SDNode *MulNode,
448                                      SDValue &AddNode,
449                                      SDValue &ConstNode);
450 
451 
452     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
453     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
454     /// the type of the loaded value to be extended.  LoadedVT returns the type
455     /// of the original loaded value.  NarrowLoad returns whether the load would
456     /// need to be narrowed in order to match.
457     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
458                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
459                           bool &NarrowLoad);
460 
461     /// Helper function for MergeConsecutiveStores which merges the
462     /// component store chains.
463     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
464                                 unsigned NumStores);
465 
466     /// This is a helper function for MergeConsecutiveStores. When the
467     /// source elements of the consecutive stores are all constants or
468     /// all extracted vector elements, try to merge them into one
469     /// larger store introducing bitcasts if necessary.  \return True
470     /// if a merged store was created.
471     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
472                                          EVT MemVT, unsigned NumStores,
473                                          bool IsConstantSrc, bool UseVector,
474                                          bool UseTrunc);
475 
476     /// This is a helper function for MergeConsecutiveStores. Stores
477     /// that potentially may be merged with St are placed in
478     /// StoreNodes.
479     void getStoreMergeCandidates(StoreSDNode *St,
480                                  SmallVectorImpl<MemOpLink> &StoreNodes);
481 
482     /// Helper function for MergeConsecutiveStores. Checks if
483     /// candidate stores have indirect dependency through their
484     /// operands. \return True if safe to merge.
485     bool checkMergeStoreCandidatesForDependencies(
486         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
487 
488     /// Merge consecutive store operations into a wide store.
489     /// This optimization uses wide integers or vectors when possible.
490     /// \return number of stores that were merged into a merged store (the
491     /// affected nodes are stored as a prefix in \p StoreNodes).
492     bool MergeConsecutiveStores(StoreSDNode *N);
493 
494     /// \brief Try to transform a truncation where C is a constant:
495     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
496     ///
497     /// \p N needs to be a truncation and its first operand an AND. Other
498     /// requirements are checked by the function (e.g. that trunc is
499     /// single-use) and if missed an empty SDValue is returned.
500     SDValue distributeTruncateThroughAnd(SDNode *N);
501 
502   public:
503     DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
504         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
505           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) {
506       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
507 
508       MaximumLegalStoreInBits = 0;
509       for (MVT VT : MVT::all_valuetypes())
510         if (EVT(VT).isSimple() && VT != MVT::Other &&
511             TLI.isTypeLegal(EVT(VT)) &&
512             VT.getSizeInBits() >= MaximumLegalStoreInBits)
513           MaximumLegalStoreInBits = VT.getSizeInBits();
514     }
515 
516     /// Runs the dag combiner on all nodes in the work list
517     void Run(CombineLevel AtLevel);
518 
519     SelectionDAG &getDAG() const { return DAG; }
520 
521     /// Returns a type large enough to hold any valid shift amount - before type
522     /// legalization these can be huge.
523     EVT getShiftAmountTy(EVT LHSTy) {
524       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
525       if (LHSTy.isVector())
526         return LHSTy;
527       auto &DL = DAG.getDataLayout();
528       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
529                         : TLI.getPointerTy(DL);
530     }
531 
532     /// This method returns true if we are running before type legalization or
533     /// if the specified VT is legal.
534     bool isTypeLegal(const EVT &VT) {
535       if (!LegalTypes) return true;
536       return TLI.isTypeLegal(VT);
537     }
538 
539     /// Convenience wrapper around TargetLowering::getSetCCResultType
540     EVT getSetCCResultType(EVT VT) const {
541       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
542     }
543   };
544 }
545 
546 
547 namespace {
548 /// This class is a DAGUpdateListener that removes any deleted
549 /// nodes from the worklist.
550 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
551   DAGCombiner &DC;
552 public:
553   explicit WorklistRemover(DAGCombiner &dc)
554     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
555 
556   void NodeDeleted(SDNode *N, SDNode *E) override {
557     DC.removeFromWorklist(N);
558   }
559 };
560 }
561 
562 //===----------------------------------------------------------------------===//
563 //  TargetLowering::DAGCombinerInfo implementation
564 //===----------------------------------------------------------------------===//
565 
566 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
567   ((DAGCombiner*)DC)->AddToWorklist(N);
568 }
569 
570 SDValue TargetLowering::DAGCombinerInfo::
571 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
572   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
573 }
574 
575 SDValue TargetLowering::DAGCombinerInfo::
576 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
577   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
578 }
579 
580 
581 SDValue TargetLowering::DAGCombinerInfo::
582 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
583   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
584 }
585 
586 void TargetLowering::DAGCombinerInfo::
587 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
588   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
589 }
590 
591 //===----------------------------------------------------------------------===//
592 // Helper Functions
593 //===----------------------------------------------------------------------===//
594 
595 void DAGCombiner::deleteAndRecombine(SDNode *N) {
596   removeFromWorklist(N);
597 
598   // If the operands of this node are only used by the node, they will now be
599   // dead. Make sure to re-visit them and recursively delete dead nodes.
600   for (const SDValue &Op : N->ops())
601     // For an operand generating multiple values, one of the values may
602     // become dead allowing further simplification (e.g. split index
603     // arithmetic from an indexed load).
604     if (Op->hasOneUse() || Op->getNumValues() > 1)
605       AddToWorklist(Op.getNode());
606 
607   DAG.DeleteNode(N);
608 }
609 
610 /// Return 1 if we can compute the negated form of the specified expression for
611 /// the same cost as the expression itself, or 2 if we can compute the negated
612 /// form more cheaply than the expression itself.
613 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
614                                const TargetLowering &TLI,
615                                const TargetOptions *Options,
616                                unsigned Depth = 0) {
617   // fneg is removable even if it has multiple uses.
618   if (Op.getOpcode() == ISD::FNEG) return 2;
619 
620   // Don't allow anything with multiple uses.
621   if (!Op.hasOneUse()) return 0;
622 
623   // Don't recurse exponentially.
624   if (Depth > 6) return 0;
625 
626   switch (Op.getOpcode()) {
627   default: return false;
628   case ISD::ConstantFP: {
629     if (!LegalOperations)
630       return 1;
631 
632     // Don't invert constant FP values after legalization unless the target says
633     // the negated constant is legal.
634     EVT VT = Op.getValueType();
635     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
636       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
637   }
638   case ISD::FADD:
639     // FIXME: determine better conditions for this xform.
640     if (!Options->UnsafeFPMath) return 0;
641 
642     // After operation legalization, it might not be legal to create new FSUBs.
643     if (LegalOperations &&
644         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
645       return 0;
646 
647     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
648     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
649                                     Options, Depth + 1))
650       return V;
651     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
652     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
653                               Depth + 1);
654   case ISD::FSUB:
655     // We can't turn -(A-B) into B-A when we honor signed zeros.
656     if (!Options->NoSignedZerosFPMath &&
657         !Op.getNode()->getFlags().hasNoSignedZeros())
658       return 0;
659 
660     // fold (fneg (fsub A, B)) -> (fsub B, A)
661     return 1;
662 
663   case ISD::FMUL:
664   case ISD::FDIV:
665     if (Options->HonorSignDependentRoundingFPMath()) return 0;
666 
667     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
668     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
669                                     Options, Depth + 1))
670       return V;
671 
672     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
673                               Depth + 1);
674 
675   case ISD::FP_EXTEND:
676   case ISD::FP_ROUND:
677   case ISD::FSIN:
678     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
679                               Depth + 1);
680   }
681 }
682 
683 /// If isNegatibleForFree returns true, return the newly negated expression.
684 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
685                                     bool LegalOperations, unsigned Depth = 0) {
686   const TargetOptions &Options = DAG.getTarget().Options;
687   // fneg is removable even if it has multiple uses.
688   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
689 
690   // Don't allow anything with multiple uses.
691   assert(Op.hasOneUse() && "Unknown reuse!");
692 
693   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
694 
695   const SDNodeFlags Flags = Op.getNode()->getFlags();
696 
697   switch (Op.getOpcode()) {
698   default: llvm_unreachable("Unknown code");
699   case ISD::ConstantFP: {
700     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
701     V.changeSign();
702     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
703   }
704   case ISD::FADD:
705     // FIXME: determine better conditions for this xform.
706     assert(Options.UnsafeFPMath);
707 
708     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
709     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
710                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
711       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
712                          GetNegatedExpression(Op.getOperand(0), DAG,
713                                               LegalOperations, Depth+1),
714                          Op.getOperand(1), Flags);
715     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
716     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
717                        GetNegatedExpression(Op.getOperand(1), DAG,
718                                             LegalOperations, Depth+1),
719                        Op.getOperand(0), Flags);
720   case ISD::FSUB:
721     // fold (fneg (fsub 0, B)) -> B
722     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
723       if (N0CFP->isZero())
724         return Op.getOperand(1);
725 
726     // fold (fneg (fsub A, B)) -> (fsub B, A)
727     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
728                        Op.getOperand(1), Op.getOperand(0), Flags);
729 
730   case ISD::FMUL:
731   case ISD::FDIV:
732     assert(!Options.HonorSignDependentRoundingFPMath());
733 
734     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
735     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
736                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
737       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
738                          GetNegatedExpression(Op.getOperand(0), DAG,
739                                               LegalOperations, Depth+1),
740                          Op.getOperand(1), Flags);
741 
742     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
743     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
744                        Op.getOperand(0),
745                        GetNegatedExpression(Op.getOperand(1), DAG,
746                                             LegalOperations, Depth+1), Flags);
747 
748   case ISD::FP_EXTEND:
749   case ISD::FSIN:
750     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
751                        GetNegatedExpression(Op.getOperand(0), DAG,
752                                             LegalOperations, Depth+1));
753   case ISD::FP_ROUND:
754       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
755                          GetNegatedExpression(Op.getOperand(0), DAG,
756                                               LegalOperations, Depth+1),
757                          Op.getOperand(1));
758   }
759 }
760 
761 // APInts must be the same size for most operations, this helper
762 // function zero extends the shorter of the pair so that they match.
763 // We provide an Offset so that we can create bitwidths that won't overflow.
764 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
765   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
766   LHS = LHS.zextOrSelf(Bits);
767   RHS = RHS.zextOrSelf(Bits);
768 }
769 
770 // Return true if this node is a setcc, or is a select_cc
771 // that selects between the target values used for true and false, making it
772 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
773 // the appropriate nodes based on the type of node we are checking. This
774 // simplifies life a bit for the callers.
775 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
776                                     SDValue &CC) const {
777   if (N.getOpcode() == ISD::SETCC) {
778     LHS = N.getOperand(0);
779     RHS = N.getOperand(1);
780     CC  = N.getOperand(2);
781     return true;
782   }
783 
784   if (N.getOpcode() != ISD::SELECT_CC ||
785       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
786       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
787     return false;
788 
789   if (TLI.getBooleanContents(N.getValueType()) ==
790       TargetLowering::UndefinedBooleanContent)
791     return false;
792 
793   LHS = N.getOperand(0);
794   RHS = N.getOperand(1);
795   CC  = N.getOperand(4);
796   return true;
797 }
798 
799 /// Return true if this is a SetCC-equivalent operation with only one use.
800 /// If this is true, it allows the users to invert the operation for free when
801 /// it is profitable to do so.
802 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
803   SDValue N0, N1, N2;
804   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
805     return true;
806   return false;
807 }
808 
809 // \brief Returns the SDNode if it is a constant float BuildVector
810 // or constant float.
811 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
812   if (isa<ConstantFPSDNode>(N))
813     return N.getNode();
814   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
815     return N.getNode();
816   return nullptr;
817 }
818 
819 // Determines if it is a constant integer or a build vector of constant
820 // integers (and undefs).
821 // Do not permit build vector implicit truncation.
822 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
823   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
824     return !(Const->isOpaque() && NoOpaques);
825   if (N.getOpcode() != ISD::BUILD_VECTOR)
826     return false;
827   unsigned BitWidth = N.getScalarValueSizeInBits();
828   for (const SDValue &Op : N->op_values()) {
829     if (Op.isUndef())
830       continue;
831     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
832     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
833         (Const->isOpaque() && NoOpaques))
834       return false;
835   }
836   return true;
837 }
838 
839 // Determines if it is a constant null integer or a splatted vector of a
840 // constant null integer (with no undefs).
841 // Build vector implicit truncation is not an issue for null values.
842 static bool isNullConstantOrNullSplatConstant(SDValue N) {
843   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
844     return Splat->isNullValue();
845   return false;
846 }
847 
848 // Determines if it is a constant integer of one or a splatted vector of a
849 // constant integer of one (with no undefs).
850 // Do not permit build vector implicit truncation.
851 static bool isOneConstantOrOneSplatConstant(SDValue N) {
852   unsigned BitWidth = N.getScalarValueSizeInBits();
853   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
854     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
855   return false;
856 }
857 
858 // Determines if it is a constant integer of all ones or a splatted vector of a
859 // constant integer of all ones (with no undefs).
860 // Do not permit build vector implicit truncation.
861 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
862   unsigned BitWidth = N.getScalarValueSizeInBits();
863   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
864     return Splat->isAllOnesValue() &&
865            Splat->getAPIntValue().getBitWidth() == BitWidth;
866   return false;
867 }
868 
869 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
870 // undef's.
871 static bool isAnyConstantBuildVector(const SDNode *N) {
872   return ISD::isBuildVectorOfConstantSDNodes(N) ||
873          ISD::isBuildVectorOfConstantFPSDNodes(N);
874 }
875 
876 // Attempt to match a unary predicate against a scalar/splat constant or
877 // every element of a constant BUILD_VECTOR.
878 static bool matchUnaryPredicate(SDValue Op,
879                                 std::function<bool(ConstantSDNode *)> Match) {
880   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
881     return Match(Cst);
882 
883   if (ISD::BUILD_VECTOR != Op.getOpcode())
884     return false;
885 
886   EVT SVT = Op.getValueType().getScalarType();
887   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
888     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
889     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
890       return false;
891   }
892   return true;
893 }
894 
895 // Attempt to match a binary predicate against a pair of scalar/splat constants
896 // or every element of a pair of constant BUILD_VECTORs.
897 static bool matchBinaryPredicate(
898     SDValue LHS, SDValue RHS,
899     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match) {
900   if (LHS.getValueType() != RHS.getValueType())
901     return false;
902 
903   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
904     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
905       return Match(LHSCst, RHSCst);
906 
907   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
908       ISD::BUILD_VECTOR != RHS.getOpcode())
909     return false;
910 
911   EVT SVT = LHS.getValueType().getScalarType();
912   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
913     auto *LHSCst = dyn_cast<ConstantSDNode>(LHS.getOperand(i));
914     auto *RHSCst = dyn_cast<ConstantSDNode>(RHS.getOperand(i));
915     if (!LHSCst || !RHSCst)
916       return false;
917     if (LHSCst->getValueType(0) != SVT ||
918         LHSCst->getValueType(0) != RHSCst->getValueType(0))
919       return false;
920     if (!Match(LHSCst, RHSCst))
921       return false;
922   }
923   return true;
924 }
925 
926 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
927                                     SDValue N1) {
928   EVT VT = N0.getValueType();
929   if (N0.getOpcode() == Opc) {
930     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
931       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
932         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
933         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
934           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
935         return SDValue();
936       }
937       if (N0.hasOneUse()) {
938         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
939         // use
940         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
941         if (!OpNode.getNode())
942           return SDValue();
943         AddToWorklist(OpNode.getNode());
944         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
945       }
946     }
947   }
948 
949   if (N1.getOpcode() == Opc) {
950     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
951       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
952         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
953         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
954           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
955         return SDValue();
956       }
957       if (N1.hasOneUse()) {
958         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
959         // use
960         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
961         if (!OpNode.getNode())
962           return SDValue();
963         AddToWorklist(OpNode.getNode());
964         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
965       }
966     }
967   }
968 
969   return SDValue();
970 }
971 
972 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
973                                bool AddTo) {
974   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
975   ++NodesCombined;
976   DEBUG(dbgs() << "\nReplacing.1 ";
977         N->dump(&DAG);
978         dbgs() << "\nWith: ";
979         To[0].getNode()->dump(&DAG);
980         dbgs() << " and " << NumTo-1 << " other values\n");
981   for (unsigned i = 0, e = NumTo; i != e; ++i)
982     assert((!To[i].getNode() ||
983             N->getValueType(i) == To[i].getValueType()) &&
984            "Cannot combine value to value of different type!");
985 
986   WorklistRemover DeadNodes(*this);
987   DAG.ReplaceAllUsesWith(N, To);
988   if (AddTo) {
989     // Push the new nodes and any users onto the worklist
990     for (unsigned i = 0, e = NumTo; i != e; ++i) {
991       if (To[i].getNode()) {
992         AddToWorklist(To[i].getNode());
993         AddUsersToWorklist(To[i].getNode());
994       }
995     }
996   }
997 
998   // Finally, if the node is now dead, remove it from the graph.  The node
999   // may not be dead if the replacement process recursively simplified to
1000   // something else needing this node.
1001   if (N->use_empty())
1002     deleteAndRecombine(N);
1003   return SDValue(N, 0);
1004 }
1005 
1006 void DAGCombiner::
1007 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1008   // Replace all uses.  If any nodes become isomorphic to other nodes and
1009   // are deleted, make sure to remove them from our worklist.
1010   WorklistRemover DeadNodes(*this);
1011   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1012 
1013   // Push the new node and any (possibly new) users onto the worklist.
1014   AddToWorklist(TLO.New.getNode());
1015   AddUsersToWorklist(TLO.New.getNode());
1016 
1017   // Finally, if the node is now dead, remove it from the graph.  The node
1018   // may not be dead if the replacement process recursively simplified to
1019   // something else needing this node.
1020   if (TLO.Old.getNode()->use_empty())
1021     deleteAndRecombine(TLO.Old.getNode());
1022 }
1023 
1024 /// Check the specified integer node value to see if it can be simplified or if
1025 /// things it uses can be simplified by bit propagation. If so, return true.
1026 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
1027   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1028   KnownBits Known;
1029   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
1030     return false;
1031 
1032   // Revisit the node.
1033   AddToWorklist(Op.getNode());
1034 
1035   // Replace the old value with the new one.
1036   ++NodesCombined;
1037   DEBUG(dbgs() << "\nReplacing.2 ";
1038         TLO.Old.getNode()->dump(&DAG);
1039         dbgs() << "\nWith: ";
1040         TLO.New.getNode()->dump(&DAG);
1041         dbgs() << '\n');
1042 
1043   CommitTargetLoweringOpt(TLO);
1044   return true;
1045 }
1046 
1047 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1048   SDLoc DL(Load);
1049   EVT VT = Load->getValueType(0);
1050   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1051 
1052   DEBUG(dbgs() << "\nReplacing.9 ";
1053         Load->dump(&DAG);
1054         dbgs() << "\nWith: ";
1055         Trunc.getNode()->dump(&DAG);
1056         dbgs() << '\n');
1057   WorklistRemover DeadNodes(*this);
1058   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1059   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1060   deleteAndRecombine(Load);
1061   AddToWorklist(Trunc.getNode());
1062 }
1063 
1064 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1065   Replace = false;
1066   SDLoc DL(Op);
1067   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1068     LoadSDNode *LD = cast<LoadSDNode>(Op);
1069     EVT MemVT = LD->getMemoryVT();
1070     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1071       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1072                                                        : ISD::EXTLOAD)
1073       : LD->getExtensionType();
1074     Replace = true;
1075     return DAG.getExtLoad(ExtType, DL, PVT,
1076                           LD->getChain(), LD->getBasePtr(),
1077                           MemVT, LD->getMemOperand());
1078   }
1079 
1080   unsigned Opc = Op.getOpcode();
1081   switch (Opc) {
1082   default: break;
1083   case ISD::AssertSext:
1084     if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1085       return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1086     break;
1087   case ISD::AssertZext:
1088     if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1089       return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1090     break;
1091   case ISD::Constant: {
1092     unsigned ExtOpc =
1093       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1094     return DAG.getNode(ExtOpc, DL, PVT, Op);
1095   }
1096   }
1097 
1098   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1099     return SDValue();
1100   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1101 }
1102 
1103 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1104   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1105     return SDValue();
1106   EVT OldVT = Op.getValueType();
1107   SDLoc DL(Op);
1108   bool Replace = false;
1109   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1110   if (!NewOp.getNode())
1111     return SDValue();
1112   AddToWorklist(NewOp.getNode());
1113 
1114   if (Replace)
1115     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1116   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1117                      DAG.getValueType(OldVT));
1118 }
1119 
1120 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1121   EVT OldVT = Op.getValueType();
1122   SDLoc DL(Op);
1123   bool Replace = false;
1124   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1125   if (!NewOp.getNode())
1126     return SDValue();
1127   AddToWorklist(NewOp.getNode());
1128 
1129   if (Replace)
1130     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1131   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1132 }
1133 
1134 /// Promote the specified integer binary operation if the target indicates it is
1135 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1136 /// i32 since i16 instructions are longer.
1137 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1138   if (!LegalOperations)
1139     return SDValue();
1140 
1141   EVT VT = Op.getValueType();
1142   if (VT.isVector() || !VT.isInteger())
1143     return SDValue();
1144 
1145   // If operation type is 'undesirable', e.g. i16 on x86, consider
1146   // promoting it.
1147   unsigned Opc = Op.getOpcode();
1148   if (TLI.isTypeDesirableForOp(Opc, VT))
1149     return SDValue();
1150 
1151   EVT PVT = VT;
1152   // Consult target whether it is a good idea to promote this operation and
1153   // what's the right type to promote it to.
1154   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1155     assert(PVT != VT && "Don't know what type to promote to!");
1156 
1157     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1158 
1159     bool Replace0 = false;
1160     SDValue N0 = Op.getOperand(0);
1161     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1162 
1163     bool Replace1 = false;
1164     SDValue N1 = Op.getOperand(1);
1165     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1166     SDLoc DL(Op);
1167 
1168     SDValue RV =
1169         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1170 
1171     // New replace instances of N0 and N1
1172     if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
1173         NN0.getOpcode() != ISD::DELETED_NODE) {
1174       AddToWorklist(NN0.getNode());
1175       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1176     }
1177 
1178     if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
1179         NN1.getOpcode() != ISD::DELETED_NODE) {
1180       AddToWorklist(NN1.getNode());
1181       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1182     }
1183 
1184     // Deal with Op being deleted.
1185     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1186       return RV;
1187   }
1188   return SDValue();
1189 }
1190 
1191 /// Promote the specified integer shift operation if the target indicates it is
1192 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1193 /// i32 since i16 instructions are longer.
1194 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1195   if (!LegalOperations)
1196     return SDValue();
1197 
1198   EVT VT = Op.getValueType();
1199   if (VT.isVector() || !VT.isInteger())
1200     return SDValue();
1201 
1202   // If operation type is 'undesirable', e.g. i16 on x86, consider
1203   // promoting it.
1204   unsigned Opc = Op.getOpcode();
1205   if (TLI.isTypeDesirableForOp(Opc, VT))
1206     return SDValue();
1207 
1208   EVT PVT = VT;
1209   // Consult target whether it is a good idea to promote this operation and
1210   // what's the right type to promote it to.
1211   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1212     assert(PVT != VT && "Don't know what type to promote to!");
1213 
1214     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1215 
1216     bool Replace = false;
1217     SDValue N0 = Op.getOperand(0);
1218     SDValue N1 = Op.getOperand(1);
1219     if (Opc == ISD::SRA)
1220       N0 = SExtPromoteOperand(N0, PVT);
1221     else if (Opc == ISD::SRL)
1222       N0 = ZExtPromoteOperand(N0, PVT);
1223     else
1224       N0 = PromoteOperand(N0, PVT, Replace);
1225 
1226     if (!N0.getNode())
1227       return SDValue();
1228 
1229     SDLoc DL(Op);
1230     SDValue RV =
1231         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1232 
1233     AddToWorklist(N0.getNode());
1234     if (Replace)
1235       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1236 
1237     // Deal with Op being deleted.
1238     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1239       return RV;
1240   }
1241   return SDValue();
1242 }
1243 
1244 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1245   if (!LegalOperations)
1246     return SDValue();
1247 
1248   EVT VT = Op.getValueType();
1249   if (VT.isVector() || !VT.isInteger())
1250     return SDValue();
1251 
1252   // If operation type is 'undesirable', e.g. i16 on x86, consider
1253   // promoting it.
1254   unsigned Opc = Op.getOpcode();
1255   if (TLI.isTypeDesirableForOp(Opc, VT))
1256     return SDValue();
1257 
1258   EVT PVT = VT;
1259   // Consult target whether it is a good idea to promote this operation and
1260   // what's the right type to promote it to.
1261   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1262     assert(PVT != VT && "Don't know what type to promote to!");
1263     // fold (aext (aext x)) -> (aext x)
1264     // fold (aext (zext x)) -> (zext x)
1265     // fold (aext (sext x)) -> (sext x)
1266     DEBUG(dbgs() << "\nPromoting ";
1267           Op.getNode()->dump(&DAG));
1268     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1269   }
1270   return SDValue();
1271 }
1272 
1273 bool DAGCombiner::PromoteLoad(SDValue Op) {
1274   if (!LegalOperations)
1275     return false;
1276 
1277   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1278     return false;
1279 
1280   EVT VT = Op.getValueType();
1281   if (VT.isVector() || !VT.isInteger())
1282     return false;
1283 
1284   // If operation type is 'undesirable', e.g. i16 on x86, consider
1285   // promoting it.
1286   unsigned Opc = Op.getOpcode();
1287   if (TLI.isTypeDesirableForOp(Opc, VT))
1288     return false;
1289 
1290   EVT PVT = VT;
1291   // Consult target whether it is a good idea to promote this operation and
1292   // what's the right type to promote it to.
1293   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1294     assert(PVT != VT && "Don't know what type to promote to!");
1295 
1296     SDLoc DL(Op);
1297     SDNode *N = Op.getNode();
1298     LoadSDNode *LD = cast<LoadSDNode>(N);
1299     EVT MemVT = LD->getMemoryVT();
1300     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1301       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1302                                                        : ISD::EXTLOAD)
1303       : LD->getExtensionType();
1304     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1305                                    LD->getChain(), LD->getBasePtr(),
1306                                    MemVT, LD->getMemOperand());
1307     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1308 
1309     DEBUG(dbgs() << "\nPromoting ";
1310           N->dump(&DAG);
1311           dbgs() << "\nTo: ";
1312           Result.getNode()->dump(&DAG);
1313           dbgs() << '\n');
1314     WorklistRemover DeadNodes(*this);
1315     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1316     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1317     deleteAndRecombine(N);
1318     AddToWorklist(Result.getNode());
1319     return true;
1320   }
1321   return false;
1322 }
1323 
1324 /// \brief Recursively delete a node which has no uses and any operands for
1325 /// which it is the only use.
1326 ///
1327 /// Note that this both deletes the nodes and removes them from the worklist.
1328 /// It also adds any nodes who have had a user deleted to the worklist as they
1329 /// may now have only one use and subject to other combines.
1330 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1331   if (!N->use_empty())
1332     return false;
1333 
1334   SmallSetVector<SDNode *, 16> Nodes;
1335   Nodes.insert(N);
1336   do {
1337     N = Nodes.pop_back_val();
1338     if (!N)
1339       continue;
1340 
1341     if (N->use_empty()) {
1342       for (const SDValue &ChildN : N->op_values())
1343         Nodes.insert(ChildN.getNode());
1344 
1345       removeFromWorklist(N);
1346       DAG.DeleteNode(N);
1347     } else {
1348       AddToWorklist(N);
1349     }
1350   } while (!Nodes.empty());
1351   return true;
1352 }
1353 
1354 //===----------------------------------------------------------------------===//
1355 //  Main DAG Combiner implementation
1356 //===----------------------------------------------------------------------===//
1357 
1358 void DAGCombiner::Run(CombineLevel AtLevel) {
1359   // set the instance variables, so that the various visit routines may use it.
1360   Level = AtLevel;
1361   LegalOperations = Level >= AfterLegalizeVectorOps;
1362   LegalTypes = Level >= AfterLegalizeTypes;
1363 
1364   // Add all the dag nodes to the worklist.
1365   for (SDNode &Node : DAG.allnodes())
1366     AddToWorklist(&Node);
1367 
1368   // Create a dummy node (which is not added to allnodes), that adds a reference
1369   // to the root node, preventing it from being deleted, and tracking any
1370   // changes of the root.
1371   HandleSDNode Dummy(DAG.getRoot());
1372 
1373   // While the worklist isn't empty, find a node and try to combine it.
1374   while (!WorklistMap.empty()) {
1375     SDNode *N;
1376     // The Worklist holds the SDNodes in order, but it may contain null entries.
1377     do {
1378       N = Worklist.pop_back_val();
1379     } while (!N);
1380 
1381     bool GoodWorklistEntry = WorklistMap.erase(N);
1382     (void)GoodWorklistEntry;
1383     assert(GoodWorklistEntry &&
1384            "Found a worklist entry without a corresponding map entry!");
1385 
1386     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1387     // N is deleted from the DAG, since they too may now be dead or may have a
1388     // reduced number of uses, allowing other xforms.
1389     if (recursivelyDeleteUnusedNodes(N))
1390       continue;
1391 
1392     WorklistRemover DeadNodes(*this);
1393 
1394     // If this combine is running after legalizing the DAG, re-legalize any
1395     // nodes pulled off the worklist.
1396     if (Level == AfterLegalizeDAG) {
1397       SmallSetVector<SDNode *, 16> UpdatedNodes;
1398       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1399 
1400       for (SDNode *LN : UpdatedNodes) {
1401         AddToWorklist(LN);
1402         AddUsersToWorklist(LN);
1403       }
1404       if (!NIsValid)
1405         continue;
1406     }
1407 
1408     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1409 
1410     // Add any operands of the new node which have not yet been combined to the
1411     // worklist as well. Because the worklist uniques things already, this
1412     // won't repeatedly process the same operand.
1413     CombinedNodes.insert(N);
1414     for (const SDValue &ChildN : N->op_values())
1415       if (!CombinedNodes.count(ChildN.getNode()))
1416         AddToWorklist(ChildN.getNode());
1417 
1418     SDValue RV = combine(N);
1419 
1420     if (!RV.getNode())
1421       continue;
1422 
1423     ++NodesCombined;
1424 
1425     // If we get back the same node we passed in, rather than a new node or
1426     // zero, we know that the node must have defined multiple values and
1427     // CombineTo was used.  Since CombineTo takes care of the worklist
1428     // mechanics for us, we have no work to do in this case.
1429     if (RV.getNode() == N)
1430       continue;
1431 
1432     assert(N->getOpcode() != ISD::DELETED_NODE &&
1433            RV.getOpcode() != ISD::DELETED_NODE &&
1434            "Node was deleted but visit returned new node!");
1435 
1436     DEBUG(dbgs() << " ... into: ";
1437           RV.getNode()->dump(&DAG));
1438 
1439     if (N->getNumValues() == RV.getNode()->getNumValues())
1440       DAG.ReplaceAllUsesWith(N, RV.getNode());
1441     else {
1442       assert(N->getValueType(0) == RV.getValueType() &&
1443              N->getNumValues() == 1 && "Type mismatch");
1444       DAG.ReplaceAllUsesWith(N, &RV);
1445     }
1446 
1447     // Push the new node and any users onto the worklist
1448     AddToWorklist(RV.getNode());
1449     AddUsersToWorklist(RV.getNode());
1450 
1451     // Finally, if the node is now dead, remove it from the graph.  The node
1452     // may not be dead if the replacement process recursively simplified to
1453     // something else needing this node. This will also take care of adding any
1454     // operands which have lost a user to the worklist.
1455     recursivelyDeleteUnusedNodes(N);
1456   }
1457 
1458   // If the root changed (e.g. it was a dead load, update the root).
1459   DAG.setRoot(Dummy.getValue());
1460   DAG.RemoveDeadNodes();
1461 }
1462 
1463 SDValue DAGCombiner::visit(SDNode *N) {
1464   switch (N->getOpcode()) {
1465   default: break;
1466   case ISD::TokenFactor:        return visitTokenFactor(N);
1467   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1468   case ISD::ADD:                return visitADD(N);
1469   case ISD::SUB:                return visitSUB(N);
1470   case ISD::ADDC:               return visitADDC(N);
1471   case ISD::UADDO:              return visitUADDO(N);
1472   case ISD::SUBC:               return visitSUBC(N);
1473   case ISD::USUBO:              return visitUSUBO(N);
1474   case ISD::ADDE:               return visitADDE(N);
1475   case ISD::ADDCARRY:           return visitADDCARRY(N);
1476   case ISD::SUBE:               return visitSUBE(N);
1477   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1478   case ISD::MUL:                return visitMUL(N);
1479   case ISD::SDIV:               return visitSDIV(N);
1480   case ISD::UDIV:               return visitUDIV(N);
1481   case ISD::SREM:
1482   case ISD::UREM:               return visitREM(N);
1483   case ISD::MULHU:              return visitMULHU(N);
1484   case ISD::MULHS:              return visitMULHS(N);
1485   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1486   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1487   case ISD::SMULO:              return visitSMULO(N);
1488   case ISD::UMULO:              return visitUMULO(N);
1489   case ISD::SMIN:
1490   case ISD::SMAX:
1491   case ISD::UMIN:
1492   case ISD::UMAX:               return visitIMINMAX(N);
1493   case ISD::AND:                return visitAND(N);
1494   case ISD::OR:                 return visitOR(N);
1495   case ISD::XOR:                return visitXOR(N);
1496   case ISD::SHL:                return visitSHL(N);
1497   case ISD::SRA:                return visitSRA(N);
1498   case ISD::SRL:                return visitSRL(N);
1499   case ISD::ROTR:
1500   case ISD::ROTL:               return visitRotate(N);
1501   case ISD::ABS:                return visitABS(N);
1502   case ISD::BSWAP:              return visitBSWAP(N);
1503   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1504   case ISD::CTLZ:               return visitCTLZ(N);
1505   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1506   case ISD::CTTZ:               return visitCTTZ(N);
1507   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1508   case ISD::CTPOP:              return visitCTPOP(N);
1509   case ISD::SELECT:             return visitSELECT(N);
1510   case ISD::VSELECT:            return visitVSELECT(N);
1511   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1512   case ISD::SETCC:              return visitSETCC(N);
1513   case ISD::SETCCE:             return visitSETCCE(N);
1514   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1515   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1516   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1517   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1518   case ISD::AssertZext:         return visitAssertZext(N);
1519   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1520   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1521   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1522   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1523   case ISD::BITCAST:            return visitBITCAST(N);
1524   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1525   case ISD::FADD:               return visitFADD(N);
1526   case ISD::FSUB:               return visitFSUB(N);
1527   case ISD::FMUL:               return visitFMUL(N);
1528   case ISD::FMA:                return visitFMA(N);
1529   case ISD::FDIV:               return visitFDIV(N);
1530   case ISD::FREM:               return visitFREM(N);
1531   case ISD::FSQRT:              return visitFSQRT(N);
1532   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1533   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1534   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1535   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1536   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1537   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1538   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1539   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1540   case ISD::FNEG:               return visitFNEG(N);
1541   case ISD::FABS:               return visitFABS(N);
1542   case ISD::FFLOOR:             return visitFFLOOR(N);
1543   case ISD::FMINNUM:            return visitFMINNUM(N);
1544   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1545   case ISD::FCEIL:              return visitFCEIL(N);
1546   case ISD::FTRUNC:             return visitFTRUNC(N);
1547   case ISD::BRCOND:             return visitBRCOND(N);
1548   case ISD::BR_CC:              return visitBR_CC(N);
1549   case ISD::LOAD:               return visitLOAD(N);
1550   case ISD::STORE:              return visitSTORE(N);
1551   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1552   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1553   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1554   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1555   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1556   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1557   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1558   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1559   case ISD::MGATHER:            return visitMGATHER(N);
1560   case ISD::MLOAD:              return visitMLOAD(N);
1561   case ISD::MSCATTER:           return visitMSCATTER(N);
1562   case ISD::MSTORE:             return visitMSTORE(N);
1563   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1564   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1565   }
1566   return SDValue();
1567 }
1568 
1569 SDValue DAGCombiner::combine(SDNode *N) {
1570   SDValue RV = visit(N);
1571 
1572   // If nothing happened, try a target-specific DAG combine.
1573   if (!RV.getNode()) {
1574     assert(N->getOpcode() != ISD::DELETED_NODE &&
1575            "Node was deleted but visit returned NULL!");
1576 
1577     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1578         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1579 
1580       // Expose the DAG combiner to the target combiner impls.
1581       TargetLowering::DAGCombinerInfo
1582         DagCombineInfo(DAG, Level, false, this);
1583 
1584       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1585     }
1586   }
1587 
1588   // If nothing happened still, try promoting the operation.
1589   if (!RV.getNode()) {
1590     switch (N->getOpcode()) {
1591     default: break;
1592     case ISD::ADD:
1593     case ISD::SUB:
1594     case ISD::MUL:
1595     case ISD::AND:
1596     case ISD::OR:
1597     case ISD::XOR:
1598       RV = PromoteIntBinOp(SDValue(N, 0));
1599       break;
1600     case ISD::SHL:
1601     case ISD::SRA:
1602     case ISD::SRL:
1603       RV = PromoteIntShiftOp(SDValue(N, 0));
1604       break;
1605     case ISD::SIGN_EXTEND:
1606     case ISD::ZERO_EXTEND:
1607     case ISD::ANY_EXTEND:
1608       RV = PromoteExtend(SDValue(N, 0));
1609       break;
1610     case ISD::LOAD:
1611       if (PromoteLoad(SDValue(N, 0)))
1612         RV = SDValue(N, 0);
1613       break;
1614     }
1615   }
1616 
1617   // If N is a commutative binary node, try commuting it to enable more
1618   // sdisel CSE.
1619   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1620       N->getNumValues() == 1) {
1621     SDValue N0 = N->getOperand(0);
1622     SDValue N1 = N->getOperand(1);
1623 
1624     // Constant operands are canonicalized to RHS.
1625     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1626       SDValue Ops[] = {N1, N0};
1627       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1628                                             N->getFlags());
1629       if (CSENode)
1630         return SDValue(CSENode, 0);
1631     }
1632   }
1633 
1634   return RV;
1635 }
1636 
1637 /// Given a node, return its input chain if it has one, otherwise return a null
1638 /// sd operand.
1639 static SDValue getInputChainForNode(SDNode *N) {
1640   if (unsigned NumOps = N->getNumOperands()) {
1641     if (N->getOperand(0).getValueType() == MVT::Other)
1642       return N->getOperand(0);
1643     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1644       return N->getOperand(NumOps-1);
1645     for (unsigned i = 1; i < NumOps-1; ++i)
1646       if (N->getOperand(i).getValueType() == MVT::Other)
1647         return N->getOperand(i);
1648   }
1649   return SDValue();
1650 }
1651 
1652 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1653   // If N has two operands, where one has an input chain equal to the other,
1654   // the 'other' chain is redundant.
1655   if (N->getNumOperands() == 2) {
1656     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1657       return N->getOperand(0);
1658     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1659       return N->getOperand(1);
1660   }
1661 
1662   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1663   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1664   SmallPtrSet<SDNode*, 16> SeenOps;
1665   bool Changed = false;             // If we should replace this token factor.
1666 
1667   // Start out with this token factor.
1668   TFs.push_back(N);
1669 
1670   // Iterate through token factors.  The TFs grows when new token factors are
1671   // encountered.
1672   for (unsigned i = 0; i < TFs.size(); ++i) {
1673     SDNode *TF = TFs[i];
1674 
1675     // Check each of the operands.
1676     for (const SDValue &Op : TF->op_values()) {
1677 
1678       switch (Op.getOpcode()) {
1679       case ISD::EntryToken:
1680         // Entry tokens don't need to be added to the list. They are
1681         // redundant.
1682         Changed = true;
1683         break;
1684 
1685       case ISD::TokenFactor:
1686         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1687           // Queue up for processing.
1688           TFs.push_back(Op.getNode());
1689           // Clean up in case the token factor is removed.
1690           AddToWorklist(Op.getNode());
1691           Changed = true;
1692           break;
1693         }
1694         LLVM_FALLTHROUGH;
1695 
1696       default:
1697         // Only add if it isn't already in the list.
1698         if (SeenOps.insert(Op.getNode()).second)
1699           Ops.push_back(Op);
1700         else
1701           Changed = true;
1702         break;
1703       }
1704     }
1705   }
1706 
1707   // Remove Nodes that are chained to another node in the list. Do so
1708   // by walking up chains breath-first stopping when we've seen
1709   // another operand. In general we must climb to the EntryNode, but we can exit
1710   // early if we find all remaining work is associated with just one operand as
1711   // no further pruning is possible.
1712 
1713   // List of nodes to search through and original Ops from which they originate.
1714   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1715   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1716   SmallPtrSet<SDNode *, 16> SeenChains;
1717   bool DidPruneOps = false;
1718 
1719   unsigned NumLeftToConsider = 0;
1720   for (const SDValue &Op : Ops) {
1721     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1722     OpWorkCount.push_back(1);
1723   }
1724 
1725   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1726     // If this is an Op, we can remove the op from the list. Remark any
1727     // search associated with it as from the current OpNumber.
1728     if (SeenOps.count(Op) != 0) {
1729       Changed = true;
1730       DidPruneOps = true;
1731       unsigned OrigOpNumber = 0;
1732       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1733         OrigOpNumber++;
1734       assert((OrigOpNumber != Ops.size()) &&
1735              "expected to find TokenFactor Operand");
1736       // Re-mark worklist from OrigOpNumber to OpNumber
1737       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1738         if (Worklist[i].second == OrigOpNumber) {
1739           Worklist[i].second = OpNumber;
1740         }
1741       }
1742       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1743       OpWorkCount[OrigOpNumber] = 0;
1744       NumLeftToConsider--;
1745     }
1746     // Add if it's a new chain
1747     if (SeenChains.insert(Op).second) {
1748       OpWorkCount[OpNumber]++;
1749       Worklist.push_back(std::make_pair(Op, OpNumber));
1750     }
1751   };
1752 
1753   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1754     // We need at least be consider at least 2 Ops to prune.
1755     if (NumLeftToConsider <= 1)
1756       break;
1757     auto CurNode = Worklist[i].first;
1758     auto CurOpNumber = Worklist[i].second;
1759     assert((OpWorkCount[CurOpNumber] > 0) &&
1760            "Node should not appear in worklist");
1761     switch (CurNode->getOpcode()) {
1762     case ISD::EntryToken:
1763       // Hitting EntryToken is the only way for the search to terminate without
1764       // hitting
1765       // another operand's search. Prevent us from marking this operand
1766       // considered.
1767       NumLeftToConsider++;
1768       break;
1769     case ISD::TokenFactor:
1770       for (const SDValue &Op : CurNode->op_values())
1771         AddToWorklist(i, Op.getNode(), CurOpNumber);
1772       break;
1773     case ISD::CopyFromReg:
1774     case ISD::CopyToReg:
1775       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1776       break;
1777     default:
1778       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1779         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1780       break;
1781     }
1782     OpWorkCount[CurOpNumber]--;
1783     if (OpWorkCount[CurOpNumber] == 0)
1784       NumLeftToConsider--;
1785   }
1786 
1787   // If we've changed things around then replace token factor.
1788   if (Changed) {
1789     SDValue Result;
1790     if (Ops.empty()) {
1791       // The entry token is the only possible outcome.
1792       Result = DAG.getEntryNode();
1793     } else {
1794       if (DidPruneOps) {
1795         SmallVector<SDValue, 8> PrunedOps;
1796         //
1797         for (const SDValue &Op : Ops) {
1798           if (SeenChains.count(Op.getNode()) == 0)
1799             PrunedOps.push_back(Op);
1800         }
1801         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1802       } else {
1803         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1804       }
1805     }
1806     return Result;
1807   }
1808   return SDValue();
1809 }
1810 
1811 /// MERGE_VALUES can always be eliminated.
1812 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1813   WorklistRemover DeadNodes(*this);
1814   // Replacing results may cause a different MERGE_VALUES to suddenly
1815   // be CSE'd with N, and carry its uses with it. Iterate until no
1816   // uses remain, to ensure that the node can be safely deleted.
1817   // First add the users of this node to the work list so that they
1818   // can be tried again once they have new operands.
1819   AddUsersToWorklist(N);
1820   do {
1821     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1822       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1823   } while (!N->use_empty());
1824   deleteAndRecombine(N);
1825   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1826 }
1827 
1828 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1829 /// ConstantSDNode pointer else nullptr.
1830 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1831   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1832   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1833 }
1834 
1835 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1836   auto BinOpcode = BO->getOpcode();
1837   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1838           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1839           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1840           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1841           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1842           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1843           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1844           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1845           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1846          "Unexpected binary operator");
1847 
1848   // Bail out if any constants are opaque because we can't constant fold those.
1849   SDValue C1 = BO->getOperand(1);
1850   if (!isConstantOrConstantVector(C1, true) &&
1851       !isConstantFPBuildVectorOrConstantFP(C1))
1852     return SDValue();
1853 
1854   // Don't do this unless the old select is going away. We want to eliminate the
1855   // binary operator, not replace a binop with a select.
1856   // TODO: Handle ISD::SELECT_CC.
1857   SDValue Sel = BO->getOperand(0);
1858   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1859     return SDValue();
1860 
1861   SDValue CT = Sel.getOperand(1);
1862   if (!isConstantOrConstantVector(CT, true) &&
1863       !isConstantFPBuildVectorOrConstantFP(CT))
1864     return SDValue();
1865 
1866   SDValue CF = Sel.getOperand(2);
1867   if (!isConstantOrConstantVector(CF, true) &&
1868       !isConstantFPBuildVectorOrConstantFP(CF))
1869     return SDValue();
1870 
1871   // We have a select-of-constants followed by a binary operator with a
1872   // constant. Eliminate the binop by pulling the constant math into the select.
1873   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1874   EVT VT = Sel.getValueType();
1875   SDLoc DL(Sel);
1876   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1877   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1878           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1879          "Failed to constant fold a binop with constant operands");
1880 
1881   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1882   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1883           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1884          "Failed to constant fold a binop with constant operands");
1885 
1886   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1887 }
1888 
1889 SDValue DAGCombiner::visitADD(SDNode *N) {
1890   SDValue N0 = N->getOperand(0);
1891   SDValue N1 = N->getOperand(1);
1892   EVT VT = N0.getValueType();
1893   SDLoc DL(N);
1894 
1895   // fold vector ops
1896   if (VT.isVector()) {
1897     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1898       return FoldedVOp;
1899 
1900     // fold (add x, 0) -> x, vector edition
1901     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1902       return N0;
1903     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1904       return N1;
1905   }
1906 
1907   // fold (add x, undef) -> undef
1908   if (N0.isUndef())
1909     return N0;
1910 
1911   if (N1.isUndef())
1912     return N1;
1913 
1914   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1915     // canonicalize constant to RHS
1916     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1917       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1918     // fold (add c1, c2) -> c1+c2
1919     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1920                                       N1.getNode());
1921   }
1922 
1923   // fold (add x, 0) -> x
1924   if (isNullConstant(N1))
1925     return N0;
1926 
1927   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1928     // fold ((c1-A)+c2) -> (c1+c2)-A
1929     if (N0.getOpcode() == ISD::SUB &&
1930         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1931       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1932       return DAG.getNode(ISD::SUB, DL, VT,
1933                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1934                          N0.getOperand(1));
1935     }
1936 
1937     // add (sext i1 X), 1 -> zext (not i1 X)
1938     // We don't transform this pattern:
1939     //   add (zext i1 X), -1 -> sext (not i1 X)
1940     // because most (?) targets generate better code for the zext form.
1941     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1942         isOneConstantOrOneSplatConstant(N1)) {
1943       SDValue X = N0.getOperand(0);
1944       if ((!LegalOperations ||
1945            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1946             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1947           X.getScalarValueSizeInBits() == 1) {
1948         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1949         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1950       }
1951     }
1952 
1953     // Undo the add -> or combine to merge constant offsets from a frame index.
1954     if (N0.getOpcode() == ISD::OR &&
1955         isa<FrameIndexSDNode>(N0.getOperand(0)) &&
1956         isa<ConstantSDNode>(N0.getOperand(1)) &&
1957         DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
1958       SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
1959       return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
1960     }
1961   }
1962 
1963   if (SDValue NewSel = foldBinOpIntoSelect(N))
1964     return NewSel;
1965 
1966   // reassociate add
1967   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1968     return RADD;
1969 
1970   // fold ((0-A) + B) -> B-A
1971   if (N0.getOpcode() == ISD::SUB &&
1972       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1973     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1974 
1975   // fold (A + (0-B)) -> A-B
1976   if (N1.getOpcode() == ISD::SUB &&
1977       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1978     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1979 
1980   // fold (A+(B-A)) -> B
1981   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1982     return N1.getOperand(0);
1983 
1984   // fold ((B-A)+A) -> B
1985   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1986     return N0.getOperand(0);
1987 
1988   // fold (A+(B-(A+C))) to (B-C)
1989   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1990       N0 == N1.getOperand(1).getOperand(0))
1991     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1992                        N1.getOperand(1).getOperand(1));
1993 
1994   // fold (A+(B-(C+A))) to (B-C)
1995   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1996       N0 == N1.getOperand(1).getOperand(1))
1997     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1998                        N1.getOperand(1).getOperand(0));
1999 
2000   // fold (A+((B-A)+or-C)) to (B+or-C)
2001   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2002       N1.getOperand(0).getOpcode() == ISD::SUB &&
2003       N0 == N1.getOperand(0).getOperand(1))
2004     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2005                        N1.getOperand(1));
2006 
2007   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2008   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2009     SDValue N00 = N0.getOperand(0);
2010     SDValue N01 = N0.getOperand(1);
2011     SDValue N10 = N1.getOperand(0);
2012     SDValue N11 = N1.getOperand(1);
2013 
2014     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2015       return DAG.getNode(ISD::SUB, DL, VT,
2016                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2017                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2018   }
2019 
2020   if (SimplifyDemandedBits(SDValue(N, 0)))
2021     return SDValue(N, 0);
2022 
2023   // fold (a+b) -> (a|b) iff a and b share no bits.
2024   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2025       DAG.haveNoCommonBitsSet(N0, N1))
2026     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2027 
2028   if (SDValue Combined = visitADDLike(N0, N1, N))
2029     return Combined;
2030 
2031   if (SDValue Combined = visitADDLike(N1, N0, N))
2032     return Combined;
2033 
2034   return SDValue();
2035 }
2036 
2037 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2038   bool Masked = false;
2039 
2040   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2041   while (true) {
2042     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2043       V = V.getOperand(0);
2044       continue;
2045     }
2046 
2047     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2048       Masked = true;
2049       V = V.getOperand(0);
2050       continue;
2051     }
2052 
2053     break;
2054   }
2055 
2056   // If this is not a carry, return.
2057   if (V.getResNo() != 1)
2058     return SDValue();
2059 
2060   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2061       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2062     return SDValue();
2063 
2064   // If the result is masked, then no matter what kind of bool it is we can
2065   // return. If it isn't, then we need to make sure the bool type is either 0 or
2066   // 1 and not other values.
2067   if (Masked ||
2068       TLI.getBooleanContents(V.getValueType()) ==
2069           TargetLoweringBase::ZeroOrOneBooleanContent)
2070     return V;
2071 
2072   return SDValue();
2073 }
2074 
2075 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2076   EVT VT = N0.getValueType();
2077   SDLoc DL(LocReference);
2078 
2079   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2080   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2081       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2082     return DAG.getNode(ISD::SUB, DL, VT, N0,
2083                        DAG.getNode(ISD::SHL, DL, VT,
2084                                    N1.getOperand(0).getOperand(1),
2085                                    N1.getOperand(1)));
2086 
2087   if (N1.getOpcode() == ISD::AND) {
2088     SDValue AndOp0 = N1.getOperand(0);
2089     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2090     unsigned DestBits = VT.getScalarSizeInBits();
2091 
2092     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2093     // and similar xforms where the inner op is either ~0 or 0.
2094     if (NumSignBits == DestBits &&
2095         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2096       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2097   }
2098 
2099   // add (sext i1), X -> sub X, (zext i1)
2100   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2101       N0.getOperand(0).getValueType() == MVT::i1 &&
2102       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2103     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2104     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2105   }
2106 
2107   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2108   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2109     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2110     if (TN->getVT() == MVT::i1) {
2111       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2112                                  DAG.getConstant(1, DL, VT));
2113       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2114     }
2115   }
2116 
2117   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2118   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2119     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2120                        N0, N1.getOperand(0), N1.getOperand(2));
2121 
2122   // (add X, Carry) -> (addcarry X, 0, Carry)
2123   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2124     if (SDValue Carry = getAsCarry(TLI, N1))
2125       return DAG.getNode(ISD::ADDCARRY, DL,
2126                          DAG.getVTList(VT, Carry.getValueType()), N0,
2127                          DAG.getConstant(0, DL, VT), Carry);
2128 
2129   return SDValue();
2130 }
2131 
2132 SDValue DAGCombiner::visitADDC(SDNode *N) {
2133   SDValue N0 = N->getOperand(0);
2134   SDValue N1 = N->getOperand(1);
2135   EVT VT = N0.getValueType();
2136   SDLoc DL(N);
2137 
2138   // If the flag result is dead, turn this into an ADD.
2139   if (!N->hasAnyUseOfValue(1))
2140     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2141                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2142 
2143   // canonicalize constant to RHS.
2144   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2145   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2146   if (N0C && !N1C)
2147     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2148 
2149   // fold (addc x, 0) -> x + no carry out
2150   if (isNullConstant(N1))
2151     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2152                                         DL, MVT::Glue));
2153 
2154   // If it cannot overflow, transform into an add.
2155   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2156     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2157                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2158 
2159   return SDValue();
2160 }
2161 
2162 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2163   SDValue N0 = N->getOperand(0);
2164   SDValue N1 = N->getOperand(1);
2165   EVT VT = N0.getValueType();
2166   if (VT.isVector())
2167     return SDValue();
2168 
2169   EVT CarryVT = N->getValueType(1);
2170   SDLoc DL(N);
2171 
2172   // If the flag result is dead, turn this into an ADD.
2173   if (!N->hasAnyUseOfValue(1))
2174     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2175                      DAG.getUNDEF(CarryVT));
2176 
2177   // canonicalize constant to RHS.
2178   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2179   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2180   if (N0C && !N1C)
2181     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2182 
2183   // fold (uaddo x, 0) -> x + no carry out
2184   if (isNullConstant(N1))
2185     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2186 
2187   // If it cannot overflow, transform into an add.
2188   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2189     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2190                      DAG.getConstant(0, DL, CarryVT));
2191 
2192   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2193     return Combined;
2194 
2195   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2196     return Combined;
2197 
2198   return SDValue();
2199 }
2200 
2201 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2202   auto VT = N0.getValueType();
2203 
2204   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2205   // If Y + 1 cannot overflow.
2206   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2207     SDValue Y = N1.getOperand(0);
2208     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2209     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2210       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2211                          N1.getOperand(2));
2212   }
2213 
2214   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2215   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2216     if (SDValue Carry = getAsCarry(TLI, N1))
2217       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2218                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2219 
2220   return SDValue();
2221 }
2222 
2223 SDValue DAGCombiner::visitADDE(SDNode *N) {
2224   SDValue N0 = N->getOperand(0);
2225   SDValue N1 = N->getOperand(1);
2226   SDValue CarryIn = N->getOperand(2);
2227 
2228   // canonicalize constant to RHS
2229   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2230   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2231   if (N0C && !N1C)
2232     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2233                        N1, N0, CarryIn);
2234 
2235   // fold (adde x, y, false) -> (addc x, y)
2236   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2237     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2238 
2239   return SDValue();
2240 }
2241 
2242 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2243   SDValue N0 = N->getOperand(0);
2244   SDValue N1 = N->getOperand(1);
2245   SDValue CarryIn = N->getOperand(2);
2246   SDLoc DL(N);
2247 
2248   // canonicalize constant to RHS
2249   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2250   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2251   if (N0C && !N1C)
2252     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2253 
2254   // fold (addcarry x, y, false) -> (uaddo x, y)
2255   if (isNullConstant(CarryIn))
2256     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2257 
2258   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2259   if (isNullConstant(N0) && isNullConstant(N1)) {
2260     EVT VT = N0.getValueType();
2261     EVT CarryVT = CarryIn.getValueType();
2262     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2263     AddToWorklist(CarryExt.getNode());
2264     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2265                                     DAG.getConstant(1, DL, VT)),
2266                      DAG.getConstant(0, DL, CarryVT));
2267   }
2268 
2269   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2270     return Combined;
2271 
2272   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2273     return Combined;
2274 
2275   return SDValue();
2276 }
2277 
2278 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2279                                        SDNode *N) {
2280   // Iff the flag result is dead:
2281   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2282   if ((N0.getOpcode() == ISD::ADD ||
2283        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2284       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2285     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2286                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2287 
2288   /**
2289    * When one of the addcarry argument is itself a carry, we may be facing
2290    * a diamond carry propagation. In which case we try to transform the DAG
2291    * to ensure linear carry propagation if that is possible.
2292    *
2293    * We are trying to get:
2294    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2295    */
2296   if (auto Y = getAsCarry(TLI, N1)) {
2297     /**
2298      *            (uaddo A, B)
2299      *             /       \
2300      *          Carry      Sum
2301      *            |          \
2302      *            | (addcarry *, 0, Z)
2303      *            |       /
2304      *             \   Carry
2305      *              |   /
2306      * (addcarry X, *, *)
2307      */
2308     if (Y.getOpcode() == ISD::UADDO &&
2309         CarryIn.getResNo() == 1 &&
2310         CarryIn.getOpcode() == ISD::ADDCARRY &&
2311         isNullConstant(CarryIn.getOperand(1)) &&
2312         CarryIn.getOperand(0) == Y.getValue(0)) {
2313       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2314                               Y.getOperand(0), Y.getOperand(1),
2315                               CarryIn.getOperand(2));
2316       AddToWorklist(NewY.getNode());
2317       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2318                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2319                          NewY.getValue(1));
2320     }
2321   }
2322 
2323   return SDValue();
2324 }
2325 
2326 // Since it may not be valid to emit a fold to zero for vector initializers
2327 // check if we can before folding.
2328 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2329                              SelectionDAG &DAG, bool LegalOperations,
2330                              bool LegalTypes) {
2331   if (!VT.isVector())
2332     return DAG.getConstant(0, DL, VT);
2333   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2334     return DAG.getConstant(0, DL, VT);
2335   return SDValue();
2336 }
2337 
2338 SDValue DAGCombiner::visitSUB(SDNode *N) {
2339   SDValue N0 = N->getOperand(0);
2340   SDValue N1 = N->getOperand(1);
2341   EVT VT = N0.getValueType();
2342   SDLoc DL(N);
2343 
2344   // fold vector ops
2345   if (VT.isVector()) {
2346     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2347       return FoldedVOp;
2348 
2349     // fold (sub x, 0) -> x, vector edition
2350     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2351       return N0;
2352   }
2353 
2354   // fold (sub x, x) -> 0
2355   // FIXME: Refactor this and xor and other similar operations together.
2356   if (N0 == N1)
2357     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2358   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2359       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2360     // fold (sub c1, c2) -> c1-c2
2361     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2362                                       N1.getNode());
2363   }
2364 
2365   if (SDValue NewSel = foldBinOpIntoSelect(N))
2366     return NewSel;
2367 
2368   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2369 
2370   // fold (sub x, c) -> (add x, -c)
2371   if (N1C) {
2372     return DAG.getNode(ISD::ADD, DL, VT, N0,
2373                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2374   }
2375 
2376   if (isNullConstantOrNullSplatConstant(N0)) {
2377     unsigned BitWidth = VT.getScalarSizeInBits();
2378     // Right-shifting everything out but the sign bit followed by negation is
2379     // the same as flipping arithmetic/logical shift type without the negation:
2380     // -(X >>u 31) -> (X >>s 31)
2381     // -(X >>s 31) -> (X >>u 31)
2382     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2383       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2384       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2385         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2386         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2387           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2388       }
2389     }
2390 
2391     // 0 - X --> 0 if the sub is NUW.
2392     if (N->getFlags().hasNoUnsignedWrap())
2393       return N0;
2394 
2395     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2396       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2397       // N1 must be 0 because negating the minimum signed value is undefined.
2398       if (N->getFlags().hasNoSignedWrap())
2399         return N0;
2400 
2401       // 0 - X --> X if X is 0 or the minimum signed value.
2402       return N1;
2403     }
2404   }
2405 
2406   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2407   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2408     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2409 
2410   // fold A-(A-B) -> B
2411   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2412     return N1.getOperand(1);
2413 
2414   // fold (A+B)-A -> B
2415   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2416     return N0.getOperand(1);
2417 
2418   // fold (A+B)-B -> A
2419   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2420     return N0.getOperand(0);
2421 
2422   // fold C2-(A+C1) -> (C2-C1)-A
2423   if (N1.getOpcode() == ISD::ADD) {
2424     SDValue N11 = N1.getOperand(1);
2425     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2426         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2427       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2428       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2429     }
2430   }
2431 
2432   // fold ((A+(B+or-C))-B) -> A+or-C
2433   if (N0.getOpcode() == ISD::ADD &&
2434       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2435        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2436       N0.getOperand(1).getOperand(0) == N1)
2437     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2438                        N0.getOperand(1).getOperand(1));
2439 
2440   // fold ((A+(C+B))-B) -> A+C
2441   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2442       N0.getOperand(1).getOperand(1) == N1)
2443     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2444                        N0.getOperand(1).getOperand(0));
2445 
2446   // fold ((A-(B-C))-C) -> A-B
2447   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2448       N0.getOperand(1).getOperand(1) == N1)
2449     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2450                        N0.getOperand(1).getOperand(0));
2451 
2452   // If either operand of a sub is undef, the result is undef
2453   if (N0.isUndef())
2454     return N0;
2455   if (N1.isUndef())
2456     return N1;
2457 
2458   // If the relocation model supports it, consider symbol offsets.
2459   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2460     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2461       // fold (sub Sym, c) -> Sym-c
2462       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2463         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2464                                     GA->getOffset() -
2465                                         (uint64_t)N1C->getSExtValue());
2466       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2467       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2468         if (GA->getGlobal() == GB->getGlobal())
2469           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2470                                  DL, VT);
2471     }
2472 
2473   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2474   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2475     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2476     if (TN->getVT() == MVT::i1) {
2477       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2478                                  DAG.getConstant(1, DL, VT));
2479       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2480     }
2481   }
2482 
2483   return SDValue();
2484 }
2485 
2486 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2487   SDValue N0 = N->getOperand(0);
2488   SDValue N1 = N->getOperand(1);
2489   EVT VT = N0.getValueType();
2490   SDLoc DL(N);
2491 
2492   // If the flag result is dead, turn this into an SUB.
2493   if (!N->hasAnyUseOfValue(1))
2494     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2495                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2496 
2497   // fold (subc x, x) -> 0 + no borrow
2498   if (N0 == N1)
2499     return CombineTo(N, DAG.getConstant(0, DL, VT),
2500                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2501 
2502   // fold (subc x, 0) -> x + no borrow
2503   if (isNullConstant(N1))
2504     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2505 
2506   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2507   if (isAllOnesConstant(N0))
2508     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2509                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2510 
2511   return SDValue();
2512 }
2513 
2514 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2515   SDValue N0 = N->getOperand(0);
2516   SDValue N1 = N->getOperand(1);
2517   EVT VT = N0.getValueType();
2518   if (VT.isVector())
2519     return SDValue();
2520 
2521   EVT CarryVT = N->getValueType(1);
2522   SDLoc DL(N);
2523 
2524   // If the flag result is dead, turn this into an SUB.
2525   if (!N->hasAnyUseOfValue(1))
2526     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2527                      DAG.getUNDEF(CarryVT));
2528 
2529   // fold (usubo x, x) -> 0 + no borrow
2530   if (N0 == N1)
2531     return CombineTo(N, DAG.getConstant(0, DL, VT),
2532                      DAG.getConstant(0, DL, CarryVT));
2533 
2534   // fold (usubo x, 0) -> x + no borrow
2535   if (isNullConstant(N1))
2536     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2537 
2538   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2539   if (isAllOnesConstant(N0))
2540     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2541                      DAG.getConstant(0, DL, CarryVT));
2542 
2543   return SDValue();
2544 }
2545 
2546 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2547   SDValue N0 = N->getOperand(0);
2548   SDValue N1 = N->getOperand(1);
2549   SDValue CarryIn = N->getOperand(2);
2550 
2551   // fold (sube x, y, false) -> (subc x, y)
2552   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2553     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2554 
2555   return SDValue();
2556 }
2557 
2558 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2559   SDValue N0 = N->getOperand(0);
2560   SDValue N1 = N->getOperand(1);
2561   SDValue CarryIn = N->getOperand(2);
2562 
2563   // fold (subcarry x, y, false) -> (usubo x, y)
2564   if (isNullConstant(CarryIn))
2565     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2566 
2567   return SDValue();
2568 }
2569 
2570 SDValue DAGCombiner::visitMUL(SDNode *N) {
2571   SDValue N0 = N->getOperand(0);
2572   SDValue N1 = N->getOperand(1);
2573   EVT VT = N0.getValueType();
2574 
2575   // fold (mul x, undef) -> 0
2576   if (N0.isUndef() || N1.isUndef())
2577     return DAG.getConstant(0, SDLoc(N), VT);
2578 
2579   bool N0IsConst = false;
2580   bool N1IsConst = false;
2581   bool N1IsOpaqueConst = false;
2582   bool N0IsOpaqueConst = false;
2583   APInt ConstValue0, ConstValue1;
2584   // fold vector ops
2585   if (VT.isVector()) {
2586     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2587       return FoldedVOp;
2588 
2589     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2590     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2591   } else {
2592     N0IsConst = isa<ConstantSDNode>(N0);
2593     if (N0IsConst) {
2594       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2595       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2596     }
2597     N1IsConst = isa<ConstantSDNode>(N1);
2598     if (N1IsConst) {
2599       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2600       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2601     }
2602   }
2603 
2604   // fold (mul c1, c2) -> c1*c2
2605   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2606     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2607                                       N0.getNode(), N1.getNode());
2608 
2609   // canonicalize constant to RHS (vector doesn't have to splat)
2610   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2611      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2612     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2613   // fold (mul x, 0) -> 0
2614   if (N1IsConst && ConstValue1.isNullValue())
2615     return N1;
2616   // We require a splat of the entire scalar bit width for non-contiguous
2617   // bit patterns.
2618   bool IsFullSplat =
2619     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2620   // fold (mul x, 1) -> x
2621   if (N1IsConst && ConstValue1.isOneValue() && IsFullSplat)
2622     return N0;
2623 
2624   if (SDValue NewSel = foldBinOpIntoSelect(N))
2625     return NewSel;
2626 
2627   // fold (mul x, -1) -> 0-x
2628   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2629     SDLoc DL(N);
2630     return DAG.getNode(ISD::SUB, DL, VT,
2631                        DAG.getConstant(0, DL, VT), N0);
2632   }
2633   // fold (mul x, (1 << c)) -> x << c
2634   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2635       IsFullSplat) {
2636     SDLoc DL(N);
2637     return DAG.getNode(ISD::SHL, DL, VT, N0,
2638                        DAG.getConstant(ConstValue1.logBase2(), DL,
2639                                        getShiftAmountTy(N0.getValueType())));
2640   }
2641   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2642   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2643       IsFullSplat) {
2644     unsigned Log2Val = (-ConstValue1).logBase2();
2645     SDLoc DL(N);
2646     // FIXME: If the input is something that is easily negated (e.g. a
2647     // single-use add), we should put the negate there.
2648     return DAG.getNode(ISD::SUB, DL, VT,
2649                        DAG.getConstant(0, DL, VT),
2650                        DAG.getNode(ISD::SHL, DL, VT, N0,
2651                             DAG.getConstant(Log2Val, DL,
2652                                       getShiftAmountTy(N0.getValueType()))));
2653   }
2654 
2655   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2656   if (N0.getOpcode() == ISD::SHL &&
2657       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2658       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2659     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2660     if (isConstantOrConstantVector(C3))
2661       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2662   }
2663 
2664   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2665   // use.
2666   {
2667     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2668 
2669     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2670     if (N0.getOpcode() == ISD::SHL &&
2671         isConstantOrConstantVector(N0.getOperand(1)) &&
2672         N0.getNode()->hasOneUse()) {
2673       Sh = N0; Y = N1;
2674     } else if (N1.getOpcode() == ISD::SHL &&
2675                isConstantOrConstantVector(N1.getOperand(1)) &&
2676                N1.getNode()->hasOneUse()) {
2677       Sh = N1; Y = N0;
2678     }
2679 
2680     if (Sh.getNode()) {
2681       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2682       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2683     }
2684   }
2685 
2686   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2687   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2688       N0.getOpcode() == ISD::ADD &&
2689       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2690       isMulAddWithConstProfitable(N, N0, N1))
2691       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2692                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2693                                      N0.getOperand(0), N1),
2694                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2695                                      N0.getOperand(1), N1));
2696 
2697   // reassociate mul
2698   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2699     return RMUL;
2700 
2701   return SDValue();
2702 }
2703 
2704 /// Return true if divmod libcall is available.
2705 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2706                                      const TargetLowering &TLI) {
2707   RTLIB::Libcall LC;
2708   EVT NodeType = Node->getValueType(0);
2709   if (!NodeType.isSimple())
2710     return false;
2711   switch (NodeType.getSimpleVT().SimpleTy) {
2712   default: return false; // No libcall for vector types.
2713   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2714   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2715   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2716   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2717   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2718   }
2719 
2720   return TLI.getLibcallName(LC) != nullptr;
2721 }
2722 
2723 /// Issue divrem if both quotient and remainder are needed.
2724 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2725   if (Node->use_empty())
2726     return SDValue(); // This is a dead node, leave it alone.
2727 
2728   unsigned Opcode = Node->getOpcode();
2729   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2730   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2731 
2732   // DivMod lib calls can still work on non-legal types if using lib-calls.
2733   EVT VT = Node->getValueType(0);
2734   if (VT.isVector() || !VT.isInteger())
2735     return SDValue();
2736 
2737   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2738     return SDValue();
2739 
2740   // If DIVREM is going to get expanded into a libcall,
2741   // but there is no libcall available, then don't combine.
2742   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2743       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2744     return SDValue();
2745 
2746   // If div is legal, it's better to do the normal expansion
2747   unsigned OtherOpcode = 0;
2748   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2749     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2750     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2751       return SDValue();
2752   } else {
2753     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2754     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2755       return SDValue();
2756   }
2757 
2758   SDValue Op0 = Node->getOperand(0);
2759   SDValue Op1 = Node->getOperand(1);
2760   SDValue combined;
2761   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2762          UE = Op0.getNode()->use_end(); UI != UE;) {
2763     SDNode *User = *UI++;
2764     if (User == Node || User->use_empty())
2765       continue;
2766     // Convert the other matching node(s), too;
2767     // otherwise, the DIVREM may get target-legalized into something
2768     // target-specific that we won't be able to recognize.
2769     unsigned UserOpc = User->getOpcode();
2770     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2771         User->getOperand(0) == Op0 &&
2772         User->getOperand(1) == Op1) {
2773       if (!combined) {
2774         if (UserOpc == OtherOpcode) {
2775           SDVTList VTs = DAG.getVTList(VT, VT);
2776           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2777         } else if (UserOpc == DivRemOpc) {
2778           combined = SDValue(User, 0);
2779         } else {
2780           assert(UserOpc == Opcode);
2781           continue;
2782         }
2783       }
2784       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2785         CombineTo(User, combined);
2786       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2787         CombineTo(User, combined.getValue(1));
2788     }
2789   }
2790   return combined;
2791 }
2792 
2793 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2794   SDValue N0 = N->getOperand(0);
2795   SDValue N1 = N->getOperand(1);
2796   EVT VT = N->getValueType(0);
2797   SDLoc DL(N);
2798 
2799   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2800     return DAG.getUNDEF(VT);
2801 
2802   // undef / X -> 0
2803   // undef % X -> 0
2804   if (N0.isUndef())
2805     return DAG.getConstant(0, DL, VT);
2806 
2807   return SDValue();
2808 }
2809 
2810 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2811   SDValue N0 = N->getOperand(0);
2812   SDValue N1 = N->getOperand(1);
2813   EVT VT = N->getValueType(0);
2814 
2815   // fold vector ops
2816   if (VT.isVector())
2817     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2818       return FoldedVOp;
2819 
2820   SDLoc DL(N);
2821 
2822   // fold (sdiv c1, c2) -> c1/c2
2823   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2824   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2825   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2826     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2827   // fold (sdiv X, 1) -> X
2828   if (N1C && N1C->isOne())
2829     return N0;
2830   // fold (sdiv X, -1) -> 0-X
2831   if (N1C && N1C->isAllOnesValue())
2832     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2833 
2834   if (SDValue V = simplifyDivRem(N, DAG))
2835     return V;
2836 
2837   if (SDValue NewSel = foldBinOpIntoSelect(N))
2838     return NewSel;
2839 
2840   // If we know the sign bits of both operands are zero, strength reduce to a
2841   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2842   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2843     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2844 
2845   // fold (sdiv X, pow2) -> simple ops after legalize
2846   // FIXME: We check for the exact bit here because the generic lowering gives
2847   // better results in that case. The target-specific lowering should learn how
2848   // to handle exact sdivs efficiently.
2849   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2850       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2851                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2852     // Target-specific implementation of sdiv x, pow2.
2853     if (SDValue Res = BuildSDIVPow2(N))
2854       return Res;
2855 
2856     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2857 
2858     // Splat the sign bit into the register
2859     SDValue SGN =
2860         DAG.getNode(ISD::SRA, DL, VT, N0,
2861                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2862                                     getShiftAmountTy(N0.getValueType())));
2863     AddToWorklist(SGN.getNode());
2864 
2865     // Add (N0 < 0) ? abs2 - 1 : 0;
2866     SDValue SRL =
2867         DAG.getNode(ISD::SRL, DL, VT, SGN,
2868                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2869                                     getShiftAmountTy(SGN.getValueType())));
2870     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2871     AddToWorklist(SRL.getNode());
2872     AddToWorklist(ADD.getNode());    // Divide by pow2
2873     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2874                   DAG.getConstant(lg2, DL,
2875                                   getShiftAmountTy(ADD.getValueType())));
2876 
2877     // If we're dividing by a positive value, we're done.  Otherwise, we must
2878     // negate the result.
2879     if (N1C->getAPIntValue().isNonNegative())
2880       return SRA;
2881 
2882     AddToWorklist(SRA.getNode());
2883     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2884   }
2885 
2886   // If integer divide is expensive and we satisfy the requirements, emit an
2887   // alternate sequence.  Targets may check function attributes for size/speed
2888   // trade-offs.
2889   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2890   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2891     if (SDValue Op = BuildSDIV(N))
2892       return Op;
2893 
2894   // sdiv, srem -> sdivrem
2895   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2896   // true.  Otherwise, we break the simplification logic in visitREM().
2897   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2898     if (SDValue DivRem = useDivRem(N))
2899         return DivRem;
2900 
2901   return SDValue();
2902 }
2903 
2904 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2905   SDValue N0 = N->getOperand(0);
2906   SDValue N1 = N->getOperand(1);
2907   EVT VT = N->getValueType(0);
2908 
2909   // fold vector ops
2910   if (VT.isVector())
2911     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2912       return FoldedVOp;
2913 
2914   SDLoc DL(N);
2915 
2916   // fold (udiv c1, c2) -> c1/c2
2917   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2918   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2919   if (N0C && N1C)
2920     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2921                                                     N0C, N1C))
2922       return Folded;
2923 
2924   if (SDValue V = simplifyDivRem(N, DAG))
2925     return V;
2926 
2927   if (SDValue NewSel = foldBinOpIntoSelect(N))
2928     return NewSel;
2929 
2930   // fold (udiv x, (1 << c)) -> x >>u c
2931   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2932       DAG.isKnownToBeAPowerOfTwo(N1)) {
2933     SDValue LogBase2 = BuildLogBase2(N1, DL);
2934     AddToWorklist(LogBase2.getNode());
2935 
2936     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2937     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2938     AddToWorklist(Trunc.getNode());
2939     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2940   }
2941 
2942   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2943   if (N1.getOpcode() == ISD::SHL) {
2944     SDValue N10 = N1.getOperand(0);
2945     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2946         DAG.isKnownToBeAPowerOfTwo(N10)) {
2947       SDValue LogBase2 = BuildLogBase2(N10, DL);
2948       AddToWorklist(LogBase2.getNode());
2949 
2950       EVT ADDVT = N1.getOperand(1).getValueType();
2951       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2952       AddToWorklist(Trunc.getNode());
2953       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2954       AddToWorklist(Add.getNode());
2955       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2956     }
2957   }
2958 
2959   // fold (udiv x, c) -> alternate
2960   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2961   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2962     if (SDValue Op = BuildUDIV(N))
2963       return Op;
2964 
2965   // sdiv, srem -> sdivrem
2966   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2967   // true.  Otherwise, we break the simplification logic in visitREM().
2968   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2969     if (SDValue DivRem = useDivRem(N))
2970         return DivRem;
2971 
2972   return SDValue();
2973 }
2974 
2975 // handles ISD::SREM and ISD::UREM
2976 SDValue DAGCombiner::visitREM(SDNode *N) {
2977   unsigned Opcode = N->getOpcode();
2978   SDValue N0 = N->getOperand(0);
2979   SDValue N1 = N->getOperand(1);
2980   EVT VT = N->getValueType(0);
2981   bool isSigned = (Opcode == ISD::SREM);
2982   SDLoc DL(N);
2983 
2984   // fold (rem c1, c2) -> c1%c2
2985   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2986   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2987   if (N0C && N1C)
2988     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2989       return Folded;
2990 
2991   if (SDValue V = simplifyDivRem(N, DAG))
2992     return V;
2993 
2994   if (SDValue NewSel = foldBinOpIntoSelect(N))
2995     return NewSel;
2996 
2997   if (isSigned) {
2998     // If we know the sign bits of both operands are zero, strength reduce to a
2999     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
3000     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3001       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
3002   } else {
3003     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
3004     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
3005       // fold (urem x, pow2) -> (and x, pow2-1)
3006       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3007       AddToWorklist(Add.getNode());
3008       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3009     }
3010     if (N1.getOpcode() == ISD::SHL &&
3011         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
3012       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
3013       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3014       AddToWorklist(Add.getNode());
3015       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3016     }
3017   }
3018 
3019   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
3020 
3021   // If X/C can be simplified by the division-by-constant logic, lower
3022   // X%C to the equivalent of X-X/C*C.
3023   // To avoid mangling nodes, this simplification requires that the combine()
3024   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
3025   // against this by skipping the simplification if isIntDivCheap().  When
3026   // div is not cheap, combine will not return a DIVREM.  Regardless,
3027   // checking cheapness here makes sense since the simplification results in
3028   // fatter code.
3029   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
3030     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3031     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
3032     AddToWorklist(Div.getNode());
3033     SDValue OptimizedDiv = combine(Div.getNode());
3034     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
3035       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
3036              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
3037       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
3038       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3039       AddToWorklist(Mul.getNode());
3040       return Sub;
3041     }
3042   }
3043 
3044   // sdiv, srem -> sdivrem
3045   if (SDValue DivRem = useDivRem(N))
3046     return DivRem.getValue(1);
3047 
3048   return SDValue();
3049 }
3050 
3051 SDValue DAGCombiner::visitMULHS(SDNode *N) {
3052   SDValue N0 = N->getOperand(0);
3053   SDValue N1 = N->getOperand(1);
3054   EVT VT = N->getValueType(0);
3055   SDLoc DL(N);
3056 
3057   // fold (mulhs x, 0) -> 0
3058   if (isNullConstant(N1))
3059     return N1;
3060   // fold (mulhs x, 1) -> (sra x, size(x)-1)
3061   if (isOneConstant(N1)) {
3062     SDLoc DL(N);
3063     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3064                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3065                                        getShiftAmountTy(N0.getValueType())));
3066   }
3067   // fold (mulhs x, undef) -> 0
3068   if (N0.isUndef() || N1.isUndef())
3069     return DAG.getConstant(0, SDLoc(N), VT);
3070 
3071   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3072   // plus a shift.
3073   if (VT.isSimple() && !VT.isVector()) {
3074     MVT Simple = VT.getSimpleVT();
3075     unsigned SimpleSize = Simple.getSizeInBits();
3076     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3077     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3078       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3079       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3080       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3081       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3082             DAG.getConstant(SimpleSize, DL,
3083                             getShiftAmountTy(N1.getValueType())));
3084       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3085     }
3086   }
3087 
3088   return SDValue();
3089 }
3090 
3091 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3092   SDValue N0 = N->getOperand(0);
3093   SDValue N1 = N->getOperand(1);
3094   EVT VT = N->getValueType(0);
3095   SDLoc DL(N);
3096 
3097   // fold (mulhu x, 0) -> 0
3098   if (isNullConstant(N1))
3099     return N1;
3100   // fold (mulhu x, 1) -> 0
3101   if (isOneConstant(N1))
3102     return DAG.getConstant(0, DL, N0.getValueType());
3103   // fold (mulhu x, undef) -> 0
3104   if (N0.isUndef() || N1.isUndef())
3105     return DAG.getConstant(0, DL, VT);
3106 
3107   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3108   // plus a shift.
3109   if (VT.isSimple() && !VT.isVector()) {
3110     MVT Simple = VT.getSimpleVT();
3111     unsigned SimpleSize = Simple.getSizeInBits();
3112     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3113     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3114       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3115       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3116       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3117       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3118             DAG.getConstant(SimpleSize, DL,
3119                             getShiftAmountTy(N1.getValueType())));
3120       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3121     }
3122   }
3123 
3124   return SDValue();
3125 }
3126 
3127 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3128 /// give the opcodes for the two computations that are being performed. Return
3129 /// true if a simplification was made.
3130 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3131                                                 unsigned HiOp) {
3132   // If the high half is not needed, just compute the low half.
3133   bool HiExists = N->hasAnyUseOfValue(1);
3134   if (!HiExists &&
3135       (!LegalOperations ||
3136        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3137     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3138     return CombineTo(N, Res, Res);
3139   }
3140 
3141   // If the low half is not needed, just compute the high half.
3142   bool LoExists = N->hasAnyUseOfValue(0);
3143   if (!LoExists &&
3144       (!LegalOperations ||
3145        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3146     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3147     return CombineTo(N, Res, Res);
3148   }
3149 
3150   // If both halves are used, return as it is.
3151   if (LoExists && HiExists)
3152     return SDValue();
3153 
3154   // If the two computed results can be simplified separately, separate them.
3155   if (LoExists) {
3156     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3157     AddToWorklist(Lo.getNode());
3158     SDValue LoOpt = combine(Lo.getNode());
3159     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3160         (!LegalOperations ||
3161          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3162       return CombineTo(N, LoOpt, LoOpt);
3163   }
3164 
3165   if (HiExists) {
3166     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3167     AddToWorklist(Hi.getNode());
3168     SDValue HiOpt = combine(Hi.getNode());
3169     if (HiOpt.getNode() && HiOpt != Hi &&
3170         (!LegalOperations ||
3171          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3172       return CombineTo(N, HiOpt, HiOpt);
3173   }
3174 
3175   return SDValue();
3176 }
3177 
3178 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3179   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3180     return Res;
3181 
3182   EVT VT = N->getValueType(0);
3183   SDLoc DL(N);
3184 
3185   // If the type is twice as wide is legal, transform the mulhu to a wider
3186   // multiply plus a shift.
3187   if (VT.isSimple() && !VT.isVector()) {
3188     MVT Simple = VT.getSimpleVT();
3189     unsigned SimpleSize = Simple.getSizeInBits();
3190     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3191     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3192       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3193       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3194       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3195       // Compute the high part as N1.
3196       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3197             DAG.getConstant(SimpleSize, DL,
3198                             getShiftAmountTy(Lo.getValueType())));
3199       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3200       // Compute the low part as N0.
3201       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3202       return CombineTo(N, Lo, Hi);
3203     }
3204   }
3205 
3206   return SDValue();
3207 }
3208 
3209 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3210   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3211     return Res;
3212 
3213   EVT VT = N->getValueType(0);
3214   SDLoc DL(N);
3215 
3216   // If the type is twice as wide is legal, transform the mulhu to a wider
3217   // multiply plus a shift.
3218   if (VT.isSimple() && !VT.isVector()) {
3219     MVT Simple = VT.getSimpleVT();
3220     unsigned SimpleSize = Simple.getSizeInBits();
3221     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3222     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3223       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3224       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3225       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3226       // Compute the high part as N1.
3227       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3228             DAG.getConstant(SimpleSize, DL,
3229                             getShiftAmountTy(Lo.getValueType())));
3230       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3231       // Compute the low part as N0.
3232       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3233       return CombineTo(N, Lo, Hi);
3234     }
3235   }
3236 
3237   return SDValue();
3238 }
3239 
3240 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3241   // (smulo x, 2) -> (saddo x, x)
3242   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3243     if (C2->getAPIntValue() == 2)
3244       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3245                          N->getOperand(0), N->getOperand(0));
3246 
3247   return SDValue();
3248 }
3249 
3250 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3251   // (umulo x, 2) -> (uaddo x, x)
3252   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3253     if (C2->getAPIntValue() == 2)
3254       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3255                          N->getOperand(0), N->getOperand(0));
3256 
3257   return SDValue();
3258 }
3259 
3260 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3261   SDValue N0 = N->getOperand(0);
3262   SDValue N1 = N->getOperand(1);
3263   EVT VT = N0.getValueType();
3264 
3265   // fold vector ops
3266   if (VT.isVector())
3267     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3268       return FoldedVOp;
3269 
3270   // fold operation with constant operands.
3271   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3272   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3273   if (N0C && N1C)
3274     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3275 
3276   // canonicalize constant to RHS
3277   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3278      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3279     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3280 
3281   return SDValue();
3282 }
3283 
3284 /// If this is a binary operator with two operands of the same opcode, try to
3285 /// simplify it.
3286 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3287   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3288   EVT VT = N0.getValueType();
3289   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3290 
3291   // Bail early if none of these transforms apply.
3292   if (N0.getNumOperands() == 0) return SDValue();
3293 
3294   // For each of OP in AND/OR/XOR:
3295   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3296   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3297   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3298   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3299   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3300   //
3301   // do not sink logical op inside of a vector extend, since it may combine
3302   // into a vsetcc.
3303   EVT Op0VT = N0.getOperand(0).getValueType();
3304   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3305        N0.getOpcode() == ISD::SIGN_EXTEND ||
3306        N0.getOpcode() == ISD::BSWAP ||
3307        // Avoid infinite looping with PromoteIntBinOp.
3308        (N0.getOpcode() == ISD::ANY_EXTEND &&
3309         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3310        (N0.getOpcode() == ISD::TRUNCATE &&
3311         (!TLI.isZExtFree(VT, Op0VT) ||
3312          !TLI.isTruncateFree(Op0VT, VT)) &&
3313         TLI.isTypeLegal(Op0VT))) &&
3314       !VT.isVector() &&
3315       Op0VT == N1.getOperand(0).getValueType() &&
3316       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3317     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3318                                  N0.getOperand(0).getValueType(),
3319                                  N0.getOperand(0), N1.getOperand(0));
3320     AddToWorklist(ORNode.getNode());
3321     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3322   }
3323 
3324   // For each of OP in SHL/SRL/SRA/AND...
3325   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3326   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3327   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3328   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3329        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3330       N0.getOperand(1) == N1.getOperand(1)) {
3331     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3332                                  N0.getOperand(0).getValueType(),
3333                                  N0.getOperand(0), N1.getOperand(0));
3334     AddToWorklist(ORNode.getNode());
3335     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3336                        ORNode, N0.getOperand(1));
3337   }
3338 
3339   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3340   // Only perform this optimization up until type legalization, before
3341   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3342   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3343   // we don't want to undo this promotion.
3344   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3345   // on scalars.
3346   if ((N0.getOpcode() == ISD::BITCAST ||
3347        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3348        Level <= AfterLegalizeTypes) {
3349     SDValue In0 = N0.getOperand(0);
3350     SDValue In1 = N1.getOperand(0);
3351     EVT In0Ty = In0.getValueType();
3352     EVT In1Ty = In1.getValueType();
3353     SDLoc DL(N);
3354     // If both incoming values are integers, and the original types are the
3355     // same.
3356     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3357       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3358       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3359       AddToWorklist(Op.getNode());
3360       return BC;
3361     }
3362   }
3363 
3364   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3365   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3366   // If both shuffles use the same mask, and both shuffle within a single
3367   // vector, then it is worthwhile to move the swizzle after the operation.
3368   // The type-legalizer generates this pattern when loading illegal
3369   // vector types from memory. In many cases this allows additional shuffle
3370   // optimizations.
3371   // There are other cases where moving the shuffle after the xor/and/or
3372   // is profitable even if shuffles don't perform a swizzle.
3373   // If both shuffles use the same mask, and both shuffles have the same first
3374   // or second operand, then it might still be profitable to move the shuffle
3375   // after the xor/and/or operation.
3376   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3377     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3378     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3379 
3380     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3381            "Inputs to shuffles are not the same type");
3382 
3383     // Check that both shuffles use the same mask. The masks are known to be of
3384     // the same length because the result vector type is the same.
3385     // Check also that shuffles have only one use to avoid introducing extra
3386     // instructions.
3387     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3388         SVN0->getMask().equals(SVN1->getMask())) {
3389       SDValue ShOp = N0->getOperand(1);
3390 
3391       // Don't try to fold this node if it requires introducing a
3392       // build vector of all zeros that might be illegal at this stage.
3393       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3394         if (!LegalTypes)
3395           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3396         else
3397           ShOp = SDValue();
3398       }
3399 
3400       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3401       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3402       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3403       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3404         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3405                                       N0->getOperand(0), N1->getOperand(0));
3406         AddToWorklist(NewNode.getNode());
3407         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3408                                     SVN0->getMask());
3409       }
3410 
3411       // Don't try to fold this node if it requires introducing a
3412       // build vector of all zeros that might be illegal at this stage.
3413       ShOp = N0->getOperand(0);
3414       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3415         if (!LegalTypes)
3416           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3417         else
3418           ShOp = SDValue();
3419       }
3420 
3421       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3422       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3423       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3424       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3425         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3426                                       N0->getOperand(1), N1->getOperand(1));
3427         AddToWorklist(NewNode.getNode());
3428         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3429                                     SVN0->getMask());
3430       }
3431     }
3432   }
3433 
3434   return SDValue();
3435 }
3436 
3437 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3438 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3439                                        const SDLoc &DL) {
3440   SDValue LL, LR, RL, RR, N0CC, N1CC;
3441   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3442       !isSetCCEquivalent(N1, RL, RR, N1CC))
3443     return SDValue();
3444 
3445   assert(N0.getValueType() == N1.getValueType() &&
3446          "Unexpected operand types for bitwise logic op");
3447   assert(LL.getValueType() == LR.getValueType() &&
3448          RL.getValueType() == RR.getValueType() &&
3449          "Unexpected operand types for setcc");
3450 
3451   // If we're here post-legalization or the logic op type is not i1, the logic
3452   // op type must match a setcc result type. Also, all folds require new
3453   // operations on the left and right operands, so those types must match.
3454   EVT VT = N0.getValueType();
3455   EVT OpVT = LL.getValueType();
3456   if (LegalOperations || VT != MVT::i1)
3457     if (VT != getSetCCResultType(OpVT))
3458       return SDValue();
3459   if (OpVT != RL.getValueType())
3460     return SDValue();
3461 
3462   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3463   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3464   bool IsInteger = OpVT.isInteger();
3465   if (LR == RR && CC0 == CC1 && IsInteger) {
3466     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3467     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3468 
3469     // All bits clear?
3470     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3471     // All sign bits clear?
3472     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3473     // Any bits set?
3474     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3475     // Any sign bits set?
3476     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3477 
3478     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3479     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3480     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3481     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3482     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3483       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3484       AddToWorklist(Or.getNode());
3485       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3486     }
3487 
3488     // All bits set?
3489     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3490     // All sign bits set?
3491     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3492     // Any bits clear?
3493     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3494     // Any sign bits clear?
3495     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3496 
3497     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3498     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3499     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3500     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3501     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3502       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3503       AddToWorklist(And.getNode());
3504       return DAG.getSetCC(DL, VT, And, LR, CC1);
3505     }
3506   }
3507 
3508   // TODO: What is the 'or' equivalent of this fold?
3509   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3510   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3511       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3512        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3513     SDValue One = DAG.getConstant(1, DL, OpVT);
3514     SDValue Two = DAG.getConstant(2, DL, OpVT);
3515     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3516     AddToWorklist(Add.getNode());
3517     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3518   }
3519 
3520   // Try more general transforms if the predicates match and the only user of
3521   // the compares is the 'and' or 'or'.
3522   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3523       N0.hasOneUse() && N1.hasOneUse()) {
3524     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3525     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3526     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3527       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3528       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3529       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3530       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3531       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3532     }
3533   }
3534 
3535   // Canonicalize equivalent operands to LL == RL.
3536   if (LL == RR && LR == RL) {
3537     CC1 = ISD::getSetCCSwappedOperands(CC1);
3538     std::swap(RL, RR);
3539   }
3540 
3541   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3542   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3543   if (LL == RL && LR == RR) {
3544     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3545                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3546     if (NewCC != ISD::SETCC_INVALID &&
3547         (!LegalOperations ||
3548          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3549           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3550       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3551   }
3552 
3553   return SDValue();
3554 }
3555 
3556 /// This contains all DAGCombine rules which reduce two values combined by
3557 /// an And operation to a single value. This makes them reusable in the context
3558 /// of visitSELECT(). Rules involving constants are not included as
3559 /// visitSELECT() already handles those cases.
3560 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3561   EVT VT = N1.getValueType();
3562   SDLoc DL(N);
3563 
3564   // fold (and x, undef) -> 0
3565   if (N0.isUndef() || N1.isUndef())
3566     return DAG.getConstant(0, DL, VT);
3567 
3568   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3569     return V;
3570 
3571   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3572       VT.getSizeInBits() <= 64) {
3573     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3574       APInt ADDC = ADDI->getAPIntValue();
3575       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3576         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3577         // immediate for an add, but it is legal if its top c2 bits are set,
3578         // transform the ADD so the immediate doesn't need to be materialized
3579         // in a register.
3580         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3581           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3582                                              SRLI->getZExtValue());
3583           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3584             ADDC |= Mask;
3585             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3586               SDLoc DL0(N0);
3587               SDValue NewAdd =
3588                 DAG.getNode(ISD::ADD, DL0, VT,
3589                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3590               CombineTo(N0.getNode(), NewAdd);
3591               // Return N so it doesn't get rechecked!
3592               return SDValue(N, 0);
3593             }
3594           }
3595         }
3596       }
3597     }
3598   }
3599 
3600   // Reduce bit extract of low half of an integer to the narrower type.
3601   // (and (srl i64:x, K), KMask) ->
3602   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3603   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3604     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3605       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3606         unsigned Size = VT.getSizeInBits();
3607         const APInt &AndMask = CAnd->getAPIntValue();
3608         unsigned ShiftBits = CShift->getZExtValue();
3609 
3610         // Bail out, this node will probably disappear anyway.
3611         if (ShiftBits == 0)
3612           return SDValue();
3613 
3614         unsigned MaskBits = AndMask.countTrailingOnes();
3615         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3616 
3617         if (AndMask.isMask() &&
3618             // Required bits must not span the two halves of the integer and
3619             // must fit in the half size type.
3620             (ShiftBits + MaskBits <= Size / 2) &&
3621             TLI.isNarrowingProfitable(VT, HalfVT) &&
3622             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3623             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3624             TLI.isTruncateFree(VT, HalfVT) &&
3625             TLI.isZExtFree(HalfVT, VT)) {
3626           // The isNarrowingProfitable is to avoid regressions on PPC and
3627           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3628           // on downstream users of this. Those patterns could probably be
3629           // extended to handle extensions mixed in.
3630 
3631           SDValue SL(N0);
3632           assert(MaskBits <= Size);
3633 
3634           // Extracting the highest bit of the low half.
3635           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3636           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3637                                       N0.getOperand(0));
3638 
3639           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3640           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3641           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3642           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3643           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3644         }
3645       }
3646     }
3647   }
3648 
3649   return SDValue();
3650 }
3651 
3652 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3653                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3654                                    bool &NarrowLoad) {
3655   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3656 
3657   if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3658     return false;
3659 
3660   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3661   LoadedVT = LoadN->getMemoryVT();
3662 
3663   if (ExtVT == LoadedVT &&
3664       (!LegalOperations ||
3665        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3666     // ZEXTLOAD will match without needing to change the size of the value being
3667     // loaded.
3668     NarrowLoad = false;
3669     return true;
3670   }
3671 
3672   // Do not change the width of a volatile load.
3673   if (LoadN->isVolatile())
3674     return false;
3675 
3676   // Do not generate loads of non-round integer types since these can
3677   // be expensive (and would be wrong if the type is not byte sized).
3678   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3679     return false;
3680 
3681   if (LegalOperations &&
3682       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3683     return false;
3684 
3685   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3686     return false;
3687 
3688   NarrowLoad = true;
3689   return true;
3690 }
3691 
3692 SDValue DAGCombiner::visitAND(SDNode *N) {
3693   SDValue N0 = N->getOperand(0);
3694   SDValue N1 = N->getOperand(1);
3695   EVT VT = N1.getValueType();
3696 
3697   // x & x --> x
3698   if (N0 == N1)
3699     return N0;
3700 
3701   // fold vector ops
3702   if (VT.isVector()) {
3703     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3704       return FoldedVOp;
3705 
3706     // fold (and x, 0) -> 0, vector edition
3707     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3708       // do not return N0, because undef node may exist in N0
3709       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3710                              SDLoc(N), N0.getValueType());
3711     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3712       // do not return N1, because undef node may exist in N1
3713       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3714                              SDLoc(N), N1.getValueType());
3715 
3716     // fold (and x, -1) -> x, vector edition
3717     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3718       return N1;
3719     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3720       return N0;
3721   }
3722 
3723   // fold (and c1, c2) -> c1&c2
3724   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3725   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3726   if (N0C && N1C && !N1C->isOpaque())
3727     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3728   // canonicalize constant to RHS
3729   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3730      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3731     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3732   // fold (and x, -1) -> x
3733   if (isAllOnesConstant(N1))
3734     return N0;
3735   // if (and x, c) is known to be zero, return 0
3736   unsigned BitWidth = VT.getScalarSizeInBits();
3737   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3738                                    APInt::getAllOnesValue(BitWidth)))
3739     return DAG.getConstant(0, SDLoc(N), VT);
3740 
3741   if (SDValue NewSel = foldBinOpIntoSelect(N))
3742     return NewSel;
3743 
3744   // reassociate and
3745   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3746     return RAND;
3747   // fold (and (or x, C), D) -> D if (C & D) == D
3748   if (N1C && N0.getOpcode() == ISD::OR)
3749     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3750       if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue()))
3751         return N1;
3752   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3753   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3754     SDValue N0Op0 = N0.getOperand(0);
3755     APInt Mask = ~N1C->getAPIntValue();
3756     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3757     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3758       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3759                                  N0.getValueType(), N0Op0);
3760 
3761       // Replace uses of the AND with uses of the Zero extend node.
3762       CombineTo(N, Zext);
3763 
3764       // We actually want to replace all uses of the any_extend with the
3765       // zero_extend, to avoid duplicating things.  This will later cause this
3766       // AND to be folded.
3767       CombineTo(N0.getNode(), Zext);
3768       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3769     }
3770   }
3771   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3772   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3773   // already be zero by virtue of the width of the base type of the load.
3774   //
3775   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3776   // more cases.
3777   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3778        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3779        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3780        N0.getOperand(0).getResNo() == 0) ||
3781       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3782     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3783                                          N0 : N0.getOperand(0) );
3784 
3785     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3786     // This can be a pure constant or a vector splat, in which case we treat the
3787     // vector as a scalar and use the splat value.
3788     APInt Constant = APInt::getNullValue(1);
3789     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3790       Constant = C->getAPIntValue();
3791     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3792       APInt SplatValue, SplatUndef;
3793       unsigned SplatBitSize;
3794       bool HasAnyUndefs;
3795       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3796                                              SplatBitSize, HasAnyUndefs);
3797       if (IsSplat) {
3798         // Undef bits can contribute to a possible optimisation if set, so
3799         // set them.
3800         SplatValue |= SplatUndef;
3801 
3802         // The splat value may be something like "0x00FFFFFF", which means 0 for
3803         // the first vector value and FF for the rest, repeating. We need a mask
3804         // that will apply equally to all members of the vector, so AND all the
3805         // lanes of the constant together.
3806         EVT VT = Vector->getValueType(0);
3807         unsigned BitWidth = VT.getScalarSizeInBits();
3808 
3809         // If the splat value has been compressed to a bitlength lower
3810         // than the size of the vector lane, we need to re-expand it to
3811         // the lane size.
3812         if (BitWidth > SplatBitSize)
3813           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3814                SplatBitSize < BitWidth;
3815                SplatBitSize = SplatBitSize * 2)
3816             SplatValue |= SplatValue.shl(SplatBitSize);
3817 
3818         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3819         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3820         if (SplatBitSize % BitWidth == 0) {
3821           Constant = APInt::getAllOnesValue(BitWidth);
3822           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3823             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3824         }
3825       }
3826     }
3827 
3828     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3829     // actually legal and isn't going to get expanded, else this is a false
3830     // optimisation.
3831     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3832                                                     Load->getValueType(0),
3833                                                     Load->getMemoryVT());
3834 
3835     // Resize the constant to the same size as the original memory access before
3836     // extension. If it is still the AllOnesValue then this AND is completely
3837     // unneeded.
3838     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3839 
3840     bool B;
3841     switch (Load->getExtensionType()) {
3842     default: B = false; break;
3843     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3844     case ISD::ZEXTLOAD:
3845     case ISD::NON_EXTLOAD: B = true; break;
3846     }
3847 
3848     if (B && Constant.isAllOnesValue()) {
3849       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3850       // preserve semantics once we get rid of the AND.
3851       SDValue NewLoad(Load, 0);
3852 
3853       // Fold the AND away. NewLoad may get replaced immediately.
3854       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3855 
3856       if (Load->getExtensionType() == ISD::EXTLOAD) {
3857         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3858                               Load->getValueType(0), SDLoc(Load),
3859                               Load->getChain(), Load->getBasePtr(),
3860                               Load->getOffset(), Load->getMemoryVT(),
3861                               Load->getMemOperand());
3862         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3863         if (Load->getNumValues() == 3) {
3864           // PRE/POST_INC loads have 3 values.
3865           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3866                            NewLoad.getValue(2) };
3867           CombineTo(Load, To, 3, true);
3868         } else {
3869           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3870         }
3871       }
3872 
3873       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3874     }
3875   }
3876 
3877   // fold (and (load x), 255) -> (zextload x, i8)
3878   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3879   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3880   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3881                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3882                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3883     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3884     LoadSDNode *LN0 = HasAnyExt
3885       ? cast<LoadSDNode>(N0.getOperand(0))
3886       : cast<LoadSDNode>(N0);
3887     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3888         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3889       auto NarrowLoad = false;
3890       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3891       EVT ExtVT, LoadedVT;
3892       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3893                            NarrowLoad)) {
3894         if (!NarrowLoad) {
3895           SDValue NewLoad =
3896             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3897                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3898                            LN0->getMemOperand());
3899           AddToWorklist(N);
3900           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3901           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3902         } else {
3903           EVT PtrType = LN0->getOperand(1).getValueType();
3904 
3905           unsigned Alignment = LN0->getAlignment();
3906           SDValue NewPtr = LN0->getBasePtr();
3907 
3908           // For big endian targets, we need to add an offset to the pointer
3909           // to load the correct bytes.  For little endian systems, we merely
3910           // need to read fewer bytes from the same pointer.
3911           if (DAG.getDataLayout().isBigEndian()) {
3912             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3913             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3914             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3915             SDLoc DL(LN0);
3916             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3917                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3918             Alignment = MinAlign(Alignment, PtrOff);
3919           }
3920 
3921           AddToWorklist(NewPtr.getNode());
3922 
3923           SDValue Load = DAG.getExtLoad(
3924               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3925               LN0->getPointerInfo(), ExtVT, Alignment,
3926               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3927           AddToWorklist(N);
3928           CombineTo(LN0, Load, Load.getValue(1));
3929           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3930         }
3931       }
3932     }
3933   }
3934 
3935   if (SDValue Combined = visitANDLike(N0, N1, N))
3936     return Combined;
3937 
3938   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3939   if (N0.getOpcode() == N1.getOpcode())
3940     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3941       return Tmp;
3942 
3943   // Masking the negated extension of a boolean is just the zero-extended
3944   // boolean:
3945   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3946   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3947   //
3948   // Note: the SimplifyDemandedBits fold below can make an information-losing
3949   // transform, and then we have no way to find this better fold.
3950   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3951     if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
3952       SDValue SubRHS = N0.getOperand(1);
3953       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3954           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3955         return SubRHS;
3956       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3957           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3958         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3959     }
3960   }
3961 
3962   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3963   // fold (and (sra)) -> (and (srl)) when possible.
3964   if (SimplifyDemandedBits(SDValue(N, 0)))
3965     return SDValue(N, 0);
3966 
3967   // fold (zext_inreg (extload x)) -> (zextload x)
3968   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3969     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3970     EVT MemVT = LN0->getMemoryVT();
3971     // If we zero all the possible extended bits, then we can turn this into
3972     // a zextload if we are running before legalize or the operation is legal.
3973     unsigned BitWidth = N1.getScalarValueSizeInBits();
3974     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3975                            BitWidth - MemVT.getScalarSizeInBits())) &&
3976         ((!LegalOperations && !LN0->isVolatile()) ||
3977          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3978       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3979                                        LN0->getChain(), LN0->getBasePtr(),
3980                                        MemVT, LN0->getMemOperand());
3981       AddToWorklist(N);
3982       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3983       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3984     }
3985   }
3986   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3987   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3988       N0.hasOneUse()) {
3989     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3990     EVT MemVT = LN0->getMemoryVT();
3991     // If we zero all the possible extended bits, then we can turn this into
3992     // a zextload if we are running before legalize or the operation is legal.
3993     unsigned BitWidth = N1.getScalarValueSizeInBits();
3994     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3995                            BitWidth - MemVT.getScalarSizeInBits())) &&
3996         ((!LegalOperations && !LN0->isVolatile()) ||
3997          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3998       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3999                                        LN0->getChain(), LN0->getBasePtr(),
4000                                        MemVT, LN0->getMemOperand());
4001       AddToWorklist(N);
4002       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4003       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4004     }
4005   }
4006   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
4007   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
4008     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4009                                            N0.getOperand(1), false))
4010       return BSwap;
4011   }
4012 
4013   return SDValue();
4014 }
4015 
4016 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
4017 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
4018                                         bool DemandHighBits) {
4019   if (!LegalOperations)
4020     return SDValue();
4021 
4022   EVT VT = N->getValueType(0);
4023   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
4024     return SDValue();
4025   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4026     return SDValue();
4027 
4028   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
4029   bool LookPassAnd0 = false;
4030   bool LookPassAnd1 = false;
4031   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
4032       std::swap(N0, N1);
4033   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
4034       std::swap(N0, N1);
4035   if (N0.getOpcode() == ISD::AND) {
4036     if (!N0.getNode()->hasOneUse())
4037       return SDValue();
4038     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4039     if (!N01C || N01C->getZExtValue() != 0xFF00)
4040       return SDValue();
4041     N0 = N0.getOperand(0);
4042     LookPassAnd0 = true;
4043   }
4044 
4045   if (N1.getOpcode() == ISD::AND) {
4046     if (!N1.getNode()->hasOneUse())
4047       return SDValue();
4048     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4049     if (!N11C || N11C->getZExtValue() != 0xFF)
4050       return SDValue();
4051     N1 = N1.getOperand(0);
4052     LookPassAnd1 = true;
4053   }
4054 
4055   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
4056     std::swap(N0, N1);
4057   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4058     return SDValue();
4059   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4060     return SDValue();
4061 
4062   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4063   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4064   if (!N01C || !N11C)
4065     return SDValue();
4066   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4067     return SDValue();
4068 
4069   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4070   SDValue N00 = N0->getOperand(0);
4071   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4072     if (!N00.getNode()->hasOneUse())
4073       return SDValue();
4074     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4075     if (!N001C || N001C->getZExtValue() != 0xFF)
4076       return SDValue();
4077     N00 = N00.getOperand(0);
4078     LookPassAnd0 = true;
4079   }
4080 
4081   SDValue N10 = N1->getOperand(0);
4082   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4083     if (!N10.getNode()->hasOneUse())
4084       return SDValue();
4085     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4086     if (!N101C || N101C->getZExtValue() != 0xFF00)
4087       return SDValue();
4088     N10 = N10.getOperand(0);
4089     LookPassAnd1 = true;
4090   }
4091 
4092   if (N00 != N10)
4093     return SDValue();
4094 
4095   // Make sure everything beyond the low halfword gets set to zero since the SRL
4096   // 16 will clear the top bits.
4097   unsigned OpSizeInBits = VT.getSizeInBits();
4098   if (DemandHighBits && OpSizeInBits > 16) {
4099     // If the left-shift isn't masked out then the only way this is a bswap is
4100     // if all bits beyond the low 8 are 0. In that case the entire pattern
4101     // reduces to a left shift anyway: leave it for other parts of the combiner.
4102     if (!LookPassAnd0)
4103       return SDValue();
4104 
4105     // However, if the right shift isn't masked out then it might be because
4106     // it's not needed. See if we can spot that too.
4107     if (!LookPassAnd1 &&
4108         !DAG.MaskedValueIsZero(
4109             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4110       return SDValue();
4111   }
4112 
4113   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4114   if (OpSizeInBits > 16) {
4115     SDLoc DL(N);
4116     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4117                       DAG.getConstant(OpSizeInBits - 16, DL,
4118                                       getShiftAmountTy(VT)));
4119   }
4120   return Res;
4121 }
4122 
4123 /// Return true if the specified node is an element that makes up a 32-bit
4124 /// packed halfword byteswap.
4125 /// ((x & 0x000000ff) << 8) |
4126 /// ((x & 0x0000ff00) >> 8) |
4127 /// ((x & 0x00ff0000) << 8) |
4128 /// ((x & 0xff000000) >> 8)
4129 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4130   if (!N.getNode()->hasOneUse())
4131     return false;
4132 
4133   unsigned Opc = N.getOpcode();
4134   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4135     return false;
4136 
4137   SDValue N0 = N.getOperand(0);
4138   unsigned Opc0 = N0.getOpcode();
4139   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4140     return false;
4141 
4142   ConstantSDNode *N1C = nullptr;
4143   // SHL or SRL: look upstream for AND mask operand
4144   if (Opc == ISD::AND)
4145     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4146   else if (Opc0 == ISD::AND)
4147     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4148   if (!N1C)
4149     return false;
4150 
4151   unsigned MaskByteOffset;
4152   switch (N1C->getZExtValue()) {
4153   default:
4154     return false;
4155   case 0xFF:       MaskByteOffset = 0; break;
4156   case 0xFF00:     MaskByteOffset = 1; break;
4157   case 0xFF0000:   MaskByteOffset = 2; break;
4158   case 0xFF000000: MaskByteOffset = 3; break;
4159   }
4160 
4161   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4162   if (Opc == ISD::AND) {
4163     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4164       // (x >> 8) & 0xff
4165       // (x >> 8) & 0xff0000
4166       if (Opc0 != ISD::SRL)
4167         return false;
4168       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4169       if (!C || C->getZExtValue() != 8)
4170         return false;
4171     } else {
4172       // (x << 8) & 0xff00
4173       // (x << 8) & 0xff000000
4174       if (Opc0 != ISD::SHL)
4175         return false;
4176       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4177       if (!C || C->getZExtValue() != 8)
4178         return false;
4179     }
4180   } else if (Opc == ISD::SHL) {
4181     // (x & 0xff) << 8
4182     // (x & 0xff0000) << 8
4183     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4184       return false;
4185     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4186     if (!C || C->getZExtValue() != 8)
4187       return false;
4188   } else { // Opc == ISD::SRL
4189     // (x & 0xff00) >> 8
4190     // (x & 0xff000000) >> 8
4191     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4192       return false;
4193     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4194     if (!C || C->getZExtValue() != 8)
4195       return false;
4196   }
4197 
4198   if (Parts[MaskByteOffset])
4199     return false;
4200 
4201   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4202   return true;
4203 }
4204 
4205 /// Match a 32-bit packed halfword bswap. That is
4206 /// ((x & 0x000000ff) << 8) |
4207 /// ((x & 0x0000ff00) >> 8) |
4208 /// ((x & 0x00ff0000) << 8) |
4209 /// ((x & 0xff000000) >> 8)
4210 /// => (rotl (bswap x), 16)
4211 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4212   if (!LegalOperations)
4213     return SDValue();
4214 
4215   EVT VT = N->getValueType(0);
4216   if (VT != MVT::i32)
4217     return SDValue();
4218   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4219     return SDValue();
4220 
4221   // Look for either
4222   // (or (or (and), (and)), (or (and), (and)))
4223   // (or (or (or (and), (and)), (and)), (and))
4224   if (N0.getOpcode() != ISD::OR)
4225     return SDValue();
4226   SDValue N00 = N0.getOperand(0);
4227   SDValue N01 = N0.getOperand(1);
4228   SDNode *Parts[4] = {};
4229 
4230   if (N1.getOpcode() == ISD::OR &&
4231       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4232     // (or (or (and), (and)), (or (and), (and)))
4233     if (!isBSwapHWordElement(N00, Parts))
4234       return SDValue();
4235 
4236     if (!isBSwapHWordElement(N01, Parts))
4237       return SDValue();
4238     SDValue N10 = N1.getOperand(0);
4239     if (!isBSwapHWordElement(N10, Parts))
4240       return SDValue();
4241     SDValue N11 = N1.getOperand(1);
4242     if (!isBSwapHWordElement(N11, Parts))
4243       return SDValue();
4244   } else {
4245     // (or (or (or (and), (and)), (and)), (and))
4246     if (!isBSwapHWordElement(N1, Parts))
4247       return SDValue();
4248     if (!isBSwapHWordElement(N01, Parts))
4249       return SDValue();
4250     if (N00.getOpcode() != ISD::OR)
4251       return SDValue();
4252     SDValue N000 = N00.getOperand(0);
4253     if (!isBSwapHWordElement(N000, Parts))
4254       return SDValue();
4255     SDValue N001 = N00.getOperand(1);
4256     if (!isBSwapHWordElement(N001, Parts))
4257       return SDValue();
4258   }
4259 
4260   // Make sure the parts are all coming from the same node.
4261   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4262     return SDValue();
4263 
4264   SDLoc DL(N);
4265   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4266                               SDValue(Parts[0], 0));
4267 
4268   // Result of the bswap should be rotated by 16. If it's not legal, then
4269   // do  (x << 16) | (x >> 16).
4270   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4271   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4272     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4273   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4274     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4275   return DAG.getNode(ISD::OR, DL, VT,
4276                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4277                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4278 }
4279 
4280 /// This contains all DAGCombine rules which reduce two values combined by
4281 /// an Or operation to a single value \see visitANDLike().
4282 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4283   EVT VT = N1.getValueType();
4284   SDLoc DL(N);
4285 
4286   // fold (or x, undef) -> -1
4287   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4288     return DAG.getAllOnesConstant(DL, VT);
4289 
4290   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4291     return V;
4292 
4293   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4294   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4295       // Don't increase # computations.
4296       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4297     // We can only do this xform if we know that bits from X that are set in C2
4298     // but not in C1 are already zero.  Likewise for Y.
4299     if (const ConstantSDNode *N0O1C =
4300         getAsNonOpaqueConstant(N0.getOperand(1))) {
4301       if (const ConstantSDNode *N1O1C =
4302           getAsNonOpaqueConstant(N1.getOperand(1))) {
4303         // We can only do this xform if we know that bits from X that are set in
4304         // C2 but not in C1 are already zero.  Likewise for Y.
4305         const APInt &LHSMask = N0O1C->getAPIntValue();
4306         const APInt &RHSMask = N1O1C->getAPIntValue();
4307 
4308         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4309             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4310           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4311                                   N0.getOperand(0), N1.getOperand(0));
4312           return DAG.getNode(ISD::AND, DL, VT, X,
4313                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4314         }
4315       }
4316     }
4317   }
4318 
4319   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4320   if (N0.getOpcode() == ISD::AND &&
4321       N1.getOpcode() == ISD::AND &&
4322       N0.getOperand(0) == N1.getOperand(0) &&
4323       // Don't increase # computations.
4324       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4325     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4326                             N0.getOperand(1), N1.getOperand(1));
4327     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4328   }
4329 
4330   return SDValue();
4331 }
4332 
4333 SDValue DAGCombiner::visitOR(SDNode *N) {
4334   SDValue N0 = N->getOperand(0);
4335   SDValue N1 = N->getOperand(1);
4336   EVT VT = N1.getValueType();
4337 
4338   // x | x --> x
4339   if (N0 == N1)
4340     return N0;
4341 
4342   // fold vector ops
4343   if (VT.isVector()) {
4344     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4345       return FoldedVOp;
4346 
4347     // fold (or x, 0) -> x, vector edition
4348     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4349       return N1;
4350     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4351       return N0;
4352 
4353     // fold (or x, -1) -> -1, vector edition
4354     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4355       // do not return N0, because undef node may exist in N0
4356       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4357     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4358       // do not return N1, because undef node may exist in N1
4359       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4360 
4361     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4362     // Do this only if the resulting shuffle is legal.
4363     if (isa<ShuffleVectorSDNode>(N0) &&
4364         isa<ShuffleVectorSDNode>(N1) &&
4365         // Avoid folding a node with illegal type.
4366         TLI.isTypeLegal(VT)) {
4367       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4368       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4369       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4370       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4371       // Ensure both shuffles have a zero input.
4372       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4373         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4374         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4375         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4376         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4377         bool CanFold = true;
4378         int NumElts = VT.getVectorNumElements();
4379         SmallVector<int, 4> Mask(NumElts);
4380 
4381         for (int i = 0; i != NumElts; ++i) {
4382           int M0 = SV0->getMaskElt(i);
4383           int M1 = SV1->getMaskElt(i);
4384 
4385           // Determine if either index is pointing to a zero vector.
4386           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4387           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4388 
4389           // If one element is zero and the otherside is undef, keep undef.
4390           // This also handles the case that both are undef.
4391           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4392             Mask[i] = -1;
4393             continue;
4394           }
4395 
4396           // Make sure only one of the elements is zero.
4397           if (M0Zero == M1Zero) {
4398             CanFold = false;
4399             break;
4400           }
4401 
4402           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4403 
4404           // We have a zero and non-zero element. If the non-zero came from
4405           // SV0 make the index a LHS index. If it came from SV1, make it
4406           // a RHS index. We need to mod by NumElts because we don't care
4407           // which operand it came from in the original shuffles.
4408           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4409         }
4410 
4411         if (CanFold) {
4412           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4413           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4414 
4415           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4416           if (!LegalMask) {
4417             std::swap(NewLHS, NewRHS);
4418             ShuffleVectorSDNode::commuteMask(Mask);
4419             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4420           }
4421 
4422           if (LegalMask)
4423             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4424         }
4425       }
4426     }
4427   }
4428 
4429   // fold (or c1, c2) -> c1|c2
4430   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4431   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4432   if (N0C && N1C && !N1C->isOpaque())
4433     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4434   // canonicalize constant to RHS
4435   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4436      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4437     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4438   // fold (or x, 0) -> x
4439   if (isNullConstant(N1))
4440     return N0;
4441   // fold (or x, -1) -> -1
4442   if (isAllOnesConstant(N1))
4443     return N1;
4444 
4445   if (SDValue NewSel = foldBinOpIntoSelect(N))
4446     return NewSel;
4447 
4448   // fold (or x, c) -> c iff (x & ~c) == 0
4449   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4450     return N1;
4451 
4452   if (SDValue Combined = visitORLike(N0, N1, N))
4453     return Combined;
4454 
4455   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4456   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4457     return BSwap;
4458   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4459     return BSwap;
4460 
4461   // reassociate or
4462   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4463     return ROR;
4464 
4465   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4466   // iff (c1 & c2) != 0.
4467   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4468     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4469       if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4470         if (SDValue COR =
4471                 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4472           return DAG.getNode(
4473               ISD::AND, SDLoc(N), VT,
4474               DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4475         return SDValue();
4476       }
4477     }
4478   }
4479 
4480   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4481   if (N0.getOpcode() == N1.getOpcode())
4482     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4483       return Tmp;
4484 
4485   // See if this is some rotate idiom.
4486   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4487     return SDValue(Rot, 0);
4488 
4489   if (SDValue Load = MatchLoadCombine(N))
4490     return Load;
4491 
4492   // Simplify the operands using demanded-bits information.
4493   if (SimplifyDemandedBits(SDValue(N, 0)))
4494     return SDValue(N, 0);
4495 
4496   return SDValue();
4497 }
4498 
4499 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4500 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4501   if (Op.getOpcode() == ISD::AND) {
4502     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4503       Mask = Op.getOperand(1);
4504       Op = Op.getOperand(0);
4505     } else {
4506       return false;
4507     }
4508   }
4509 
4510   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4511     Shift = Op;
4512     return true;
4513   }
4514 
4515   return false;
4516 }
4517 
4518 // Return true if we can prove that, whenever Neg and Pos are both in the
4519 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4520 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4521 //
4522 //     (or (shift1 X, Neg), (shift2 X, Pos))
4523 //
4524 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4525 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4526 // to consider shift amounts with defined behavior.
4527 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4528   // If EltSize is a power of 2 then:
4529   //
4530   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4531   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4532   //
4533   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4534   // for the stronger condition:
4535   //
4536   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4537   //
4538   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4539   // we can just replace Neg with Neg' for the rest of the function.
4540   //
4541   // In other cases we check for the even stronger condition:
4542   //
4543   //     Neg == EltSize - Pos                                    [B]
4544   //
4545   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4546   // behavior if Pos == 0 (and consequently Neg == EltSize).
4547   //
4548   // We could actually use [A] whenever EltSize is a power of 2, but the
4549   // only extra cases that it would match are those uninteresting ones
4550   // where Neg and Pos are never in range at the same time.  E.g. for
4551   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4552   // as well as (sub 32, Pos), but:
4553   //
4554   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4555   //
4556   // always invokes undefined behavior for 32-bit X.
4557   //
4558   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4559   unsigned MaskLoBits = 0;
4560   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4561     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4562       if (NegC->getAPIntValue() == EltSize - 1) {
4563         Neg = Neg.getOperand(0);
4564         MaskLoBits = Log2_64(EltSize);
4565       }
4566     }
4567   }
4568 
4569   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4570   if (Neg.getOpcode() != ISD::SUB)
4571     return false;
4572   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4573   if (!NegC)
4574     return false;
4575   SDValue NegOp1 = Neg.getOperand(1);
4576 
4577   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4578   // Pos'.  The truncation is redundant for the purpose of the equality.
4579   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4580     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4581       if (PosC->getAPIntValue() == EltSize - 1)
4582         Pos = Pos.getOperand(0);
4583 
4584   // The condition we need is now:
4585   //
4586   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4587   //
4588   // If NegOp1 == Pos then we need:
4589   //
4590   //              EltSize & Mask == NegC & Mask
4591   //
4592   // (because "x & Mask" is a truncation and distributes through subtraction).
4593   APInt Width;
4594   if (Pos == NegOp1)
4595     Width = NegC->getAPIntValue();
4596 
4597   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4598   // Then the condition we want to prove becomes:
4599   //
4600   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4601   //
4602   // which, again because "x & Mask" is a truncation, becomes:
4603   //
4604   //                NegC & Mask == (EltSize - PosC) & Mask
4605   //             EltSize & Mask == (NegC + PosC) & Mask
4606   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4607     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4608       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4609     else
4610       return false;
4611   } else
4612     return false;
4613 
4614   // Now we just need to check that EltSize & Mask == Width & Mask.
4615   if (MaskLoBits)
4616     // EltSize & Mask is 0 since Mask is EltSize - 1.
4617     return Width.getLoBits(MaskLoBits) == 0;
4618   return Width == EltSize;
4619 }
4620 
4621 // A subroutine of MatchRotate used once we have found an OR of two opposite
4622 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4623 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4624 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4625 // Neg with outer conversions stripped away.
4626 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4627                                        SDValue Neg, SDValue InnerPos,
4628                                        SDValue InnerNeg, unsigned PosOpcode,
4629                                        unsigned NegOpcode, const SDLoc &DL) {
4630   // fold (or (shl x, (*ext y)),
4631   //          (srl x, (*ext (sub 32, y)))) ->
4632   //   (rotl x, y) or (rotr x, (sub 32, y))
4633   //
4634   // fold (or (shl x, (*ext (sub 32, y))),
4635   //          (srl x, (*ext y))) ->
4636   //   (rotr x, y) or (rotl x, (sub 32, y))
4637   EVT VT = Shifted.getValueType();
4638   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4639     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4640     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4641                        HasPos ? Pos : Neg).getNode();
4642   }
4643 
4644   return nullptr;
4645 }
4646 
4647 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4648 // idioms for rotate, and if the target supports rotation instructions, generate
4649 // a rot[lr].
4650 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4651   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4652   EVT VT = LHS.getValueType();
4653   if (!TLI.isTypeLegal(VT)) return nullptr;
4654 
4655   // The target must have at least one rotate flavor.
4656   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4657   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4658   if (!HasROTL && !HasROTR) return nullptr;
4659 
4660   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4661   SDValue LHSShift;   // The shift.
4662   SDValue LHSMask;    // AND value if any.
4663   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4664     return nullptr; // Not part of a rotate.
4665 
4666   SDValue RHSShift;   // The shift.
4667   SDValue RHSMask;    // AND value if any.
4668   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4669     return nullptr; // Not part of a rotate.
4670 
4671   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4672     return nullptr;   // Not shifting the same value.
4673 
4674   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4675     return nullptr;   // Shifts must disagree.
4676 
4677   // Canonicalize shl to left side in a shl/srl pair.
4678   if (RHSShift.getOpcode() == ISD::SHL) {
4679     std::swap(LHS, RHS);
4680     std::swap(LHSShift, RHSShift);
4681     std::swap(LHSMask, RHSMask);
4682   }
4683 
4684   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4685   SDValue LHSShiftArg = LHSShift.getOperand(0);
4686   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4687   SDValue RHSShiftArg = RHSShift.getOperand(0);
4688   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4689 
4690   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4691   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4692   auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
4693                                         ConstantSDNode *RHS) {
4694     return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
4695   };
4696   if (matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
4697     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4698                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4699 
4700     // If there is an AND of either shifted operand, apply it to the result.
4701     if (LHSMask.getNode() || RHSMask.getNode()) {
4702       SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4703       SDValue Mask = AllOnes;
4704 
4705       if (LHSMask.getNode()) {
4706         SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
4707         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4708                            DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
4709       }
4710       if (RHSMask.getNode()) {
4711         SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
4712         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4713                            DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
4714       }
4715 
4716       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4717     }
4718 
4719     return Rot.getNode();
4720   }
4721 
4722   // If there is a mask here, and we have a variable shift, we can't be sure
4723   // that we're masking out the right stuff.
4724   if (LHSMask.getNode() || RHSMask.getNode())
4725     return nullptr;
4726 
4727   // If the shift amount is sign/zext/any-extended just peel it off.
4728   SDValue LExtOp0 = LHSShiftAmt;
4729   SDValue RExtOp0 = RHSShiftAmt;
4730   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4731        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4732        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4733        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4734       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4735        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4736        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4737        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4738     LExtOp0 = LHSShiftAmt.getOperand(0);
4739     RExtOp0 = RHSShiftAmt.getOperand(0);
4740   }
4741 
4742   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4743                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4744   if (TryL)
4745     return TryL;
4746 
4747   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4748                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4749   if (TryR)
4750     return TryR;
4751 
4752   return nullptr;
4753 }
4754 
4755 namespace {
4756 /// Represents known origin of an individual byte in load combine pattern. The
4757 /// value of the byte is either constant zero or comes from memory.
4758 struct ByteProvider {
4759   // For constant zero providers Load is set to nullptr. For memory providers
4760   // Load represents the node which loads the byte from memory.
4761   // ByteOffset is the offset of the byte in the value produced by the load.
4762   LoadSDNode *Load;
4763   unsigned ByteOffset;
4764 
4765   ByteProvider() : Load(nullptr), ByteOffset(0) {}
4766 
4767   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4768     return ByteProvider(Load, ByteOffset);
4769   }
4770   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4771 
4772   bool isConstantZero() const { return !Load; }
4773   bool isMemory() const { return Load; }
4774 
4775   bool operator==(const ByteProvider &Other) const {
4776     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4777   }
4778 
4779 private:
4780   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4781       : Load(Load), ByteOffset(ByteOffset) {}
4782 };
4783 
4784 /// Recursively traverses the expression calculating the origin of the requested
4785 /// byte of the given value. Returns None if the provider can't be calculated.
4786 ///
4787 /// For all the values except the root of the expression verifies that the value
4788 /// has exactly one use and if it's not true return None. This way if the origin
4789 /// of the byte is returned it's guaranteed that the values which contribute to
4790 /// the byte are not used outside of this expression.
4791 ///
4792 /// Because the parts of the expression are not allowed to have more than one
4793 /// use this function iterates over trees, not DAGs. So it never visits the same
4794 /// node more than once.
4795 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4796                                                    unsigned Depth,
4797                                                    bool Root = false) {
4798   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4799   if (Depth == 10)
4800     return None;
4801 
4802   if (!Root && !Op.hasOneUse())
4803     return None;
4804 
4805   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4806   unsigned BitWidth = Op.getValueSizeInBits();
4807   if (BitWidth % 8 != 0)
4808     return None;
4809   unsigned ByteWidth = BitWidth / 8;
4810   assert(Index < ByteWidth && "invalid index requested");
4811   (void) ByteWidth;
4812 
4813   switch (Op.getOpcode()) {
4814   case ISD::OR: {
4815     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4816     if (!LHS)
4817       return None;
4818     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4819     if (!RHS)
4820       return None;
4821 
4822     if (LHS->isConstantZero())
4823       return RHS;
4824     if (RHS->isConstantZero())
4825       return LHS;
4826     return None;
4827   }
4828   case ISD::SHL: {
4829     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4830     if (!ShiftOp)
4831       return None;
4832 
4833     uint64_t BitShift = ShiftOp->getZExtValue();
4834     if (BitShift % 8 != 0)
4835       return None;
4836     uint64_t ByteShift = BitShift / 8;
4837 
4838     return Index < ByteShift
4839                ? ByteProvider::getConstantZero()
4840                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4841                                        Depth + 1);
4842   }
4843   case ISD::ANY_EXTEND:
4844   case ISD::SIGN_EXTEND:
4845   case ISD::ZERO_EXTEND: {
4846     SDValue NarrowOp = Op->getOperand(0);
4847     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4848     if (NarrowBitWidth % 8 != 0)
4849       return None;
4850     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4851 
4852     if (Index >= NarrowByteWidth)
4853       return Op.getOpcode() == ISD::ZERO_EXTEND
4854                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4855                  : None;
4856     return calculateByteProvider(NarrowOp, Index, Depth + 1);
4857   }
4858   case ISD::BSWAP:
4859     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4860                                  Depth + 1);
4861   case ISD::LOAD: {
4862     auto L = cast<LoadSDNode>(Op.getNode());
4863     if (L->isVolatile() || L->isIndexed())
4864       return None;
4865 
4866     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4867     if (NarrowBitWidth % 8 != 0)
4868       return None;
4869     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4870 
4871     if (Index >= NarrowByteWidth)
4872       return L->getExtensionType() == ISD::ZEXTLOAD
4873                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4874                  : None;
4875     return ByteProvider::getMemory(L, Index);
4876   }
4877   }
4878 
4879   return None;
4880 }
4881 } // namespace
4882 
4883 /// Match a pattern where a wide type scalar value is loaded by several narrow
4884 /// loads and combined by shifts and ors. Fold it into a single load or a load
4885 /// and a BSWAP if the targets supports it.
4886 ///
4887 /// Assuming little endian target:
4888 ///  i8 *a = ...
4889 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4890 /// =>
4891 ///  i32 val = *((i32)a)
4892 ///
4893 ///  i8 *a = ...
4894 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4895 /// =>
4896 ///  i32 val = BSWAP(*((i32)a))
4897 ///
4898 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4899 /// interact well with the worklist mechanism. When a part of the pattern is
4900 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4901 /// but the root node of the pattern which triggers the load combine is not
4902 /// necessarily a direct user of the changed node. For example, once the address
4903 /// of t28 load is reassociated load combine won't be triggered:
4904 ///             t25: i32 = add t4, Constant:i32<2>
4905 ///           t26: i64 = sign_extend t25
4906 ///        t27: i64 = add t2, t26
4907 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4908 ///     t29: i32 = zero_extend t28
4909 ///   t32: i32 = shl t29, Constant:i8<8>
4910 /// t33: i32 = or t23, t32
4911 /// As a possible fix visitLoad can check if the load can be a part of a load
4912 /// combine pattern and add corresponding OR roots to the worklist.
4913 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4914   assert(N->getOpcode() == ISD::OR &&
4915          "Can only match load combining against OR nodes");
4916 
4917   // Handles simple types only
4918   EVT VT = N->getValueType(0);
4919   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4920     return SDValue();
4921   unsigned ByteWidth = VT.getSizeInBits() / 8;
4922 
4923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4924   // Before legalize we can introduce too wide illegal loads which will be later
4925   // split into legal sized loads. This enables us to combine i64 load by i8
4926   // patterns to a couple of i32 loads on 32 bit targets.
4927   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4928     return SDValue();
4929 
4930   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4931     unsigned BW, unsigned i) { return i; };
4932   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4933     unsigned BW, unsigned i) { return BW - i - 1; };
4934 
4935   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4936   auto MemoryByteOffset = [&] (ByteProvider P) {
4937     assert(P.isMemory() && "Must be a memory byte provider");
4938     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4939     assert(LoadBitWidth % 8 == 0 &&
4940            "can only analyze providers for individual bytes not bit");
4941     unsigned LoadByteWidth = LoadBitWidth / 8;
4942     return IsBigEndianTarget
4943             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4944             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4945   };
4946 
4947   Optional<BaseIndexOffset> Base;
4948   SDValue Chain;
4949 
4950   SmallSet<LoadSDNode *, 8> Loads;
4951   Optional<ByteProvider> FirstByteProvider;
4952   int64_t FirstOffset = INT64_MAX;
4953 
4954   // Check if all the bytes of the OR we are looking at are loaded from the same
4955   // base address. Collect bytes offsets from Base address in ByteOffsets.
4956   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4957   for (unsigned i = 0; i < ByteWidth; i++) {
4958     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4959     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4960       return SDValue();
4961 
4962     LoadSDNode *L = P->Load;
4963     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4964            "Must be enforced by calculateByteProvider");
4965     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4966 
4967     // All loads must share the same chain
4968     SDValue LChain = L->getChain();
4969     if (!Chain)
4970       Chain = LChain;
4971     else if (Chain != LChain)
4972       return SDValue();
4973 
4974     // Loads must share the same base address
4975     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4976     int64_t ByteOffsetFromBase = 0;
4977     if (!Base)
4978       Base = Ptr;
4979     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
4980       return SDValue();
4981 
4982     // Calculate the offset of the current byte from the base address
4983     ByteOffsetFromBase += MemoryByteOffset(*P);
4984     ByteOffsets[i] = ByteOffsetFromBase;
4985 
4986     // Remember the first byte load
4987     if (ByteOffsetFromBase < FirstOffset) {
4988       FirstByteProvider = P;
4989       FirstOffset = ByteOffsetFromBase;
4990     }
4991 
4992     Loads.insert(L);
4993   }
4994   assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4995          "memory, so there must be at least one load which produces the value");
4996   assert(Base && "Base address of the accessed memory location must be set");
4997   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4998 
4999   // Check if the bytes of the OR we are looking at match with either big or
5000   // little endian value load
5001   bool BigEndian = true, LittleEndian = true;
5002   for (unsigned i = 0; i < ByteWidth; i++) {
5003     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
5004     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
5005     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
5006     if (!BigEndian && !LittleEndian)
5007       return SDValue();
5008   }
5009   assert((BigEndian != LittleEndian) && "should be either or");
5010   assert(FirstByteProvider && "must be set");
5011 
5012   // Ensure that the first byte is loaded from zero offset of the first load.
5013   // So the combined value can be loaded from the first load address.
5014   if (MemoryByteOffset(*FirstByteProvider) != 0)
5015     return SDValue();
5016   LoadSDNode *FirstLoad = FirstByteProvider->Load;
5017 
5018   // The node we are looking at matches with the pattern, check if we can
5019   // replace it with a single load and bswap if needed.
5020 
5021   // If the load needs byte swap check if the target supports it
5022   bool NeedsBswap = IsBigEndianTarget != BigEndian;
5023 
5024   // Before legalize we can introduce illegal bswaps which will be later
5025   // converted to an explicit bswap sequence. This way we end up with a single
5026   // load and byte shuffling instead of several loads and byte shuffling.
5027   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
5028     return SDValue();
5029 
5030   // Check that a load of the wide type is both allowed and fast on the target
5031   bool Fast = false;
5032   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
5033                                         VT, FirstLoad->getAddressSpace(),
5034                                         FirstLoad->getAlignment(), &Fast);
5035   if (!Allowed || !Fast)
5036     return SDValue();
5037 
5038   SDValue NewLoad =
5039       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
5040                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5041 
5042   // Transfer chain users from old loads to the new load.
5043   for (LoadSDNode *L : Loads)
5044     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5045 
5046   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5047 }
5048 
5049 SDValue DAGCombiner::visitXOR(SDNode *N) {
5050   SDValue N0 = N->getOperand(0);
5051   SDValue N1 = N->getOperand(1);
5052   EVT VT = N0.getValueType();
5053 
5054   // fold vector ops
5055   if (VT.isVector()) {
5056     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5057       return FoldedVOp;
5058 
5059     // fold (xor x, 0) -> x, vector edition
5060     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5061       return N1;
5062     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5063       return N0;
5064   }
5065 
5066   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5067   if (N0.isUndef() && N1.isUndef())
5068     return DAG.getConstant(0, SDLoc(N), VT);
5069   // fold (xor x, undef) -> undef
5070   if (N0.isUndef())
5071     return N0;
5072   if (N1.isUndef())
5073     return N1;
5074   // fold (xor c1, c2) -> c1^c2
5075   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5076   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5077   if (N0C && N1C)
5078     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5079   // canonicalize constant to RHS
5080   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5081      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5082     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5083   // fold (xor x, 0) -> x
5084   if (isNullConstant(N1))
5085     return N0;
5086 
5087   if (SDValue NewSel = foldBinOpIntoSelect(N))
5088     return NewSel;
5089 
5090   // reassociate xor
5091   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5092     return RXOR;
5093 
5094   // fold !(x cc y) -> (x !cc y)
5095   SDValue LHS, RHS, CC;
5096   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5097     bool isInt = LHS.getValueType().isInteger();
5098     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5099                                                isInt);
5100 
5101     if (!LegalOperations ||
5102         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5103       switch (N0.getOpcode()) {
5104       default:
5105         llvm_unreachable("Unhandled SetCC Equivalent!");
5106       case ISD::SETCC:
5107         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5108       case ISD::SELECT_CC:
5109         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5110                                N0.getOperand(3), NotCC);
5111       }
5112     }
5113   }
5114 
5115   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5116   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5117       N0.getNode()->hasOneUse() &&
5118       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5119     SDValue V = N0.getOperand(0);
5120     SDLoc DL(N0);
5121     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5122                     DAG.getConstant(1, DL, V.getValueType()));
5123     AddToWorklist(V.getNode());
5124     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5125   }
5126 
5127   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5128   if (isOneConstant(N1) && VT == MVT::i1 &&
5129       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5130     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5131     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5132       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5133       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5134       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5135       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5136       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5137     }
5138   }
5139   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5140   if (isAllOnesConstant(N1) &&
5141       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5142     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5143     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5144       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5145       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5146       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5147       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5148       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5149     }
5150   }
5151   // fold (xor (and x, y), y) -> (and (not x), y)
5152   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5153       N0->getOperand(1) == N1) {
5154     SDValue X = N0->getOperand(0);
5155     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5156     AddToWorklist(NotX.getNode());
5157     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5158   }
5159   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5160   if (N1C && N0.getOpcode() == ISD::XOR) {
5161     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5162       SDLoc DL(N);
5163       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5164                          DAG.getConstant(N1C->getAPIntValue() ^
5165                                          N00C->getAPIntValue(), DL, VT));
5166     }
5167     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5168       SDLoc DL(N);
5169       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5170                          DAG.getConstant(N1C->getAPIntValue() ^
5171                                          N01C->getAPIntValue(), DL, VT));
5172     }
5173   }
5174 
5175   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5176   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5177   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5178       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5179       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5180     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5181       if (C->getAPIntValue() == (OpSizeInBits - 1))
5182         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5183   }
5184 
5185   // fold (xor x, x) -> 0
5186   if (N0 == N1)
5187     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5188 
5189   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5190   // Here is a concrete example of this equivalence:
5191   // i16   x ==  14
5192   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5193   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5194   //
5195   // =>
5196   //
5197   // i16     ~1      == 0b1111111111111110
5198   // i16 rol(~1, 14) == 0b1011111111111111
5199   //
5200   // Some additional tips to help conceptualize this transform:
5201   // - Try to see the operation as placing a single zero in a value of all ones.
5202   // - There exists no value for x which would allow the result to contain zero.
5203   // - Values of x larger than the bitwidth are undefined and do not require a
5204   //   consistent result.
5205   // - Pushing the zero left requires shifting one bits in from the right.
5206   // A rotate left of ~1 is a nice way of achieving the desired result.
5207   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5208       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5209     SDLoc DL(N);
5210     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5211                        N0.getOperand(1));
5212   }
5213 
5214   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5215   if (N0.getOpcode() == N1.getOpcode())
5216     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5217       return Tmp;
5218 
5219   // Simplify the expression using non-local knowledge.
5220   if (SimplifyDemandedBits(SDValue(N, 0)))
5221     return SDValue(N, 0);
5222 
5223   return SDValue();
5224 }
5225 
5226 /// Handle transforms common to the three shifts, when the shift amount is a
5227 /// constant.
5228 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5229   SDNode *LHS = N->getOperand(0).getNode();
5230   if (!LHS->hasOneUse()) return SDValue();
5231 
5232   // We want to pull some binops through shifts, so that we have (and (shift))
5233   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5234   // thing happens with address calculations, so it's important to canonicalize
5235   // it.
5236   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5237 
5238   switch (LHS->getOpcode()) {
5239   default: return SDValue();
5240   case ISD::OR:
5241   case ISD::XOR:
5242     HighBitSet = false; // We can only transform sra if the high bit is clear.
5243     break;
5244   case ISD::AND:
5245     HighBitSet = true;  // We can only transform sra if the high bit is set.
5246     break;
5247   case ISD::ADD:
5248     if (N->getOpcode() != ISD::SHL)
5249       return SDValue(); // only shl(add) not sr[al](add).
5250     HighBitSet = false; // We can only transform sra if the high bit is clear.
5251     break;
5252   }
5253 
5254   // We require the RHS of the binop to be a constant and not opaque as well.
5255   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5256   if (!BinOpCst) return SDValue();
5257 
5258   // FIXME: disable this unless the input to the binop is a shift by a constant
5259   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5260   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5261   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5262                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5263                  BinOpLHSVal->getOpcode() == ISD::SRL;
5264   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5265                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5266 
5267   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5268       !isCopyOrSelect)
5269     return SDValue();
5270 
5271   if (isCopyOrSelect && N->hasOneUse())
5272     return SDValue();
5273 
5274   EVT VT = N->getValueType(0);
5275 
5276   // If this is a signed shift right, and the high bit is modified by the
5277   // logical operation, do not perform the transformation. The highBitSet
5278   // boolean indicates the value of the high bit of the constant which would
5279   // cause it to be modified for this operation.
5280   if (N->getOpcode() == ISD::SRA) {
5281     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5282     if (BinOpRHSSignSet != HighBitSet)
5283       return SDValue();
5284   }
5285 
5286   if (!TLI.isDesirableToCommuteWithShift(LHS))
5287     return SDValue();
5288 
5289   // Fold the constants, shifting the binop RHS by the shift amount.
5290   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5291                                N->getValueType(0),
5292                                LHS->getOperand(1), N->getOperand(1));
5293   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5294 
5295   // Create the new shift.
5296   SDValue NewShift = DAG.getNode(N->getOpcode(),
5297                                  SDLoc(LHS->getOperand(0)),
5298                                  VT, LHS->getOperand(0), N->getOperand(1));
5299 
5300   // Create the new binop.
5301   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5302 }
5303 
5304 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5305   assert(N->getOpcode() == ISD::TRUNCATE);
5306   assert(N->getOperand(0).getOpcode() == ISD::AND);
5307 
5308   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5309   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5310     SDValue N01 = N->getOperand(0).getOperand(1);
5311     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5312       SDLoc DL(N);
5313       EVT TruncVT = N->getValueType(0);
5314       SDValue N00 = N->getOperand(0).getOperand(0);
5315       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5316       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5317       AddToWorklist(Trunc00.getNode());
5318       AddToWorklist(Trunc01.getNode());
5319       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5320     }
5321   }
5322 
5323   return SDValue();
5324 }
5325 
5326 SDValue DAGCombiner::visitRotate(SDNode *N) {
5327   SDLoc dl(N);
5328   SDValue N0 = N->getOperand(0);
5329   SDValue N1 = N->getOperand(1);
5330   EVT VT = N->getValueType(0);
5331   unsigned Bitsize = VT.getScalarSizeInBits();
5332 
5333   // fold (rot x, 0) -> x
5334   if (isNullConstantOrNullSplatConstant(N1))
5335     return N0;
5336 
5337   // fold (rot x, c) -> (rot x, c % BitSize)
5338   if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5339     if (Cst->getAPIntValue().uge(Bitsize)) {
5340       uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5341       return DAG.getNode(N->getOpcode(), dl, VT, N0,
5342                          DAG.getConstant(RotAmt, dl, N1.getValueType()));
5343     }
5344   }
5345 
5346   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5347   if (N1.getOpcode() == ISD::TRUNCATE &&
5348       N1.getOperand(0).getOpcode() == ISD::AND) {
5349     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5350       return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5351   }
5352 
5353   unsigned NextOp = N0.getOpcode();
5354   // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5355   if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5356     SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5357     SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5358     if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5359       EVT ShiftVT = C1->getValueType(0);
5360       bool SameSide = (N->getOpcode() == NextOp);
5361       unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5362       if (SDValue CombinedShift =
5363               DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5364         SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5365         SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5366             ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5367             BitsizeC.getNode());
5368         return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5369                            CombinedShiftNorm);
5370       }
5371     }
5372   }
5373   return SDValue();
5374 }
5375 
5376 SDValue DAGCombiner::visitSHL(SDNode *N) {
5377   SDValue N0 = N->getOperand(0);
5378   SDValue N1 = N->getOperand(1);
5379   EVT VT = N0.getValueType();
5380   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5381 
5382   // fold vector ops
5383   if (VT.isVector()) {
5384     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5385       return FoldedVOp;
5386 
5387     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5388     // If setcc produces all-one true value then:
5389     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5390     if (N1CV && N1CV->isConstant()) {
5391       if (N0.getOpcode() == ISD::AND) {
5392         SDValue N00 = N0->getOperand(0);
5393         SDValue N01 = N0->getOperand(1);
5394         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5395 
5396         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5397             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5398                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5399           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5400                                                      N01CV, N1CV))
5401             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5402         }
5403       }
5404     }
5405   }
5406 
5407   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5408 
5409   // fold (shl c1, c2) -> c1<<c2
5410   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5411   if (N0C && N1C && !N1C->isOpaque())
5412     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5413   // fold (shl 0, x) -> 0
5414   if (isNullConstantOrNullSplatConstant(N0))
5415     return N0;
5416   // fold (shl x, c >= size(x)) -> undef
5417   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5418   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5419     return Val->getAPIntValue().uge(OpSizeInBits);
5420   };
5421   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5422     return DAG.getUNDEF(VT);
5423   // fold (shl x, 0) -> x
5424   if (N1C && N1C->isNullValue())
5425     return N0;
5426   // fold (shl undef, x) -> 0
5427   if (N0.isUndef())
5428     return DAG.getConstant(0, SDLoc(N), VT);
5429 
5430   if (SDValue NewSel = foldBinOpIntoSelect(N))
5431     return NewSel;
5432 
5433   // if (shl x, c) is known to be zero, return 0
5434   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5435                             APInt::getAllOnesValue(OpSizeInBits)))
5436     return DAG.getConstant(0, SDLoc(N), VT);
5437   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5438   if (N1.getOpcode() == ISD::TRUNCATE &&
5439       N1.getOperand(0).getOpcode() == ISD::AND) {
5440     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5441       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5442   }
5443 
5444   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5445     return SDValue(N, 0);
5446 
5447   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5448   if (N0.getOpcode() == ISD::SHL) {
5449     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5450                                           ConstantSDNode *RHS) {
5451       APInt c1 = LHS->getAPIntValue();
5452       APInt c2 = RHS->getAPIntValue();
5453       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5454       return (c1 + c2).uge(OpSizeInBits);
5455     };
5456     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5457       return DAG.getConstant(0, SDLoc(N), VT);
5458 
5459     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5460                                        ConstantSDNode *RHS) {
5461       APInt c1 = LHS->getAPIntValue();
5462       APInt c2 = RHS->getAPIntValue();
5463       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5464       return (c1 + c2).ult(OpSizeInBits);
5465     };
5466     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5467       SDLoc DL(N);
5468       EVT ShiftVT = N1.getValueType();
5469       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5470       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
5471     }
5472   }
5473 
5474   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5475   // For this to be valid, the second form must not preserve any of the bits
5476   // that are shifted out by the inner shift in the first form.  This means
5477   // the outer shift size must be >= the number of bits added by the ext.
5478   // As a corollary, we don't care what kind of ext it is.
5479   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5480               N0.getOpcode() == ISD::ANY_EXTEND ||
5481               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5482       N0.getOperand(0).getOpcode() == ISD::SHL) {
5483     SDValue N0Op0 = N0.getOperand(0);
5484     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5485       APInt c1 = N0Op0C1->getAPIntValue();
5486       APInt c2 = N1C->getAPIntValue();
5487       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5488 
5489       EVT InnerShiftVT = N0Op0.getValueType();
5490       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5491       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5492         SDLoc DL(N0);
5493         APInt Sum = c1 + c2;
5494         if (Sum.uge(OpSizeInBits))
5495           return DAG.getConstant(0, DL, VT);
5496 
5497         return DAG.getNode(
5498             ISD::SHL, DL, VT,
5499             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5500             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5501       }
5502     }
5503   }
5504 
5505   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5506   // Only fold this if the inner zext has no other uses to avoid increasing
5507   // the total number of instructions.
5508   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5509       N0.getOperand(0).getOpcode() == ISD::SRL) {
5510     SDValue N0Op0 = N0.getOperand(0);
5511     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5512       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5513         uint64_t c1 = N0Op0C1->getZExtValue();
5514         uint64_t c2 = N1C->getZExtValue();
5515         if (c1 == c2) {
5516           SDValue NewOp0 = N0.getOperand(0);
5517           EVT CountVT = NewOp0.getOperand(1).getValueType();
5518           SDLoc DL(N);
5519           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5520                                        NewOp0,
5521                                        DAG.getConstant(c2, DL, CountVT));
5522           AddToWorklist(NewSHL.getNode());
5523           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5524         }
5525       }
5526     }
5527   }
5528 
5529   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5530   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5531   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5532       N0->getFlags().hasExact()) {
5533     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5534       uint64_t C1 = N0C1->getZExtValue();
5535       uint64_t C2 = N1C->getZExtValue();
5536       SDLoc DL(N);
5537       if (C1 <= C2)
5538         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5539                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5540       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5541                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5542     }
5543   }
5544 
5545   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5546   //                               (and (srl x, (sub c1, c2), MASK)
5547   // Only fold this if the inner shift has no other uses -- if it does, folding
5548   // this will increase the total number of instructions.
5549   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5550     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5551       uint64_t c1 = N0C1->getZExtValue();
5552       if (c1 < OpSizeInBits) {
5553         uint64_t c2 = N1C->getZExtValue();
5554         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5555         SDValue Shift;
5556         if (c2 > c1) {
5557           Mask <<= c2 - c1;
5558           SDLoc DL(N);
5559           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5560                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5561         } else {
5562           Mask.lshrInPlace(c1 - c2);
5563           SDLoc DL(N);
5564           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5565                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5566         }
5567         SDLoc DL(N0);
5568         return DAG.getNode(ISD::AND, DL, VT, Shift,
5569                            DAG.getConstant(Mask, DL, VT));
5570       }
5571     }
5572   }
5573 
5574   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5575   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5576       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5577     SDLoc DL(N);
5578     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5579     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5580     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5581   }
5582 
5583   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5584   // Variant of version done on multiply, except mul by a power of 2 is turned
5585   // into a shift.
5586   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5587       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5588       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5589     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5590     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5591     AddToWorklist(Shl0.getNode());
5592     AddToWorklist(Shl1.getNode());
5593     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5594   }
5595 
5596   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5597   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5598       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5599       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5600     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5601     if (isConstantOrConstantVector(Shl))
5602       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5603   }
5604 
5605   if (N1C && !N1C->isOpaque())
5606     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5607       return NewSHL;
5608 
5609   return SDValue();
5610 }
5611 
5612 SDValue DAGCombiner::visitSRA(SDNode *N) {
5613   SDValue N0 = N->getOperand(0);
5614   SDValue N1 = N->getOperand(1);
5615   EVT VT = N0.getValueType();
5616   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5617 
5618   // Arithmetic shifting an all-sign-bit value is a no-op.
5619   // fold (sra 0, x) -> 0
5620   // fold (sra -1, x) -> -1
5621   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5622     return N0;
5623 
5624   // fold vector ops
5625   if (VT.isVector())
5626     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5627       return FoldedVOp;
5628 
5629   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5630 
5631   // fold (sra c1, c2) -> (sra c1, c2)
5632   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5633   if (N0C && N1C && !N1C->isOpaque())
5634     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5635   // fold (sra x, c >= size(x)) -> undef
5636   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5637   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5638     return Val->getAPIntValue().uge(OpSizeInBits);
5639   };
5640   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5641     return DAG.getUNDEF(VT);
5642   // fold (sra x, 0) -> x
5643   if (N1C && N1C->isNullValue())
5644     return N0;
5645 
5646   if (SDValue NewSel = foldBinOpIntoSelect(N))
5647     return NewSel;
5648 
5649   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5650   // sext_inreg.
5651   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5652     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5653     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5654     if (VT.isVector())
5655       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5656                                ExtVT, VT.getVectorNumElements());
5657     if ((!LegalOperations ||
5658          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5659       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5660                          N0.getOperand(0), DAG.getValueType(ExtVT));
5661   }
5662 
5663   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5664   if (N0.getOpcode() == ISD::SRA) {
5665     SDLoc DL(N);
5666     EVT ShiftVT = N1.getValueType();
5667 
5668     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5669                                           ConstantSDNode *RHS) {
5670       APInt c1 = LHS->getAPIntValue();
5671       APInt c2 = RHS->getAPIntValue();
5672       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5673       return (c1 + c2).uge(OpSizeInBits);
5674     };
5675     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5676       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
5677                          DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT));
5678 
5679     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5680                                        ConstantSDNode *RHS) {
5681       APInt c1 = LHS->getAPIntValue();
5682       APInt c2 = RHS->getAPIntValue();
5683       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5684       return (c1 + c2).ult(OpSizeInBits);
5685     };
5686     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5687       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5688       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum);
5689     }
5690   }
5691 
5692   // fold (sra (shl X, m), (sub result_size, n))
5693   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5694   // result_size - n != m.
5695   // If truncate is free for the target sext(shl) is likely to result in better
5696   // code.
5697   if (N0.getOpcode() == ISD::SHL && N1C) {
5698     // Get the two constanst of the shifts, CN0 = m, CN = n.
5699     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5700     if (N01C) {
5701       LLVMContext &Ctx = *DAG.getContext();
5702       // Determine what the truncate's result bitsize and type would be.
5703       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5704 
5705       if (VT.isVector())
5706         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5707 
5708       // Determine the residual right-shift amount.
5709       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5710 
5711       // If the shift is not a no-op (in which case this should be just a sign
5712       // extend already), the truncated to type is legal, sign_extend is legal
5713       // on that type, and the truncate to that type is both legal and free,
5714       // perform the transform.
5715       if ((ShiftAmt > 0) &&
5716           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5717           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5718           TLI.isTruncateFree(VT, TruncVT)) {
5719 
5720         SDLoc DL(N);
5721         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5722             getShiftAmountTy(N0.getOperand(0).getValueType()));
5723         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5724                                     N0.getOperand(0), Amt);
5725         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5726                                     Shift);
5727         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5728                            N->getValueType(0), Trunc);
5729       }
5730     }
5731   }
5732 
5733   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5734   if (N1.getOpcode() == ISD::TRUNCATE &&
5735       N1.getOperand(0).getOpcode() == ISD::AND) {
5736     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5737       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5738   }
5739 
5740   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5741   //      if c1 is equal to the number of bits the trunc removes
5742   if (N0.getOpcode() == ISD::TRUNCATE &&
5743       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5744        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5745       N0.getOperand(0).hasOneUse() &&
5746       N0.getOperand(0).getOperand(1).hasOneUse() &&
5747       N1C) {
5748     SDValue N0Op0 = N0.getOperand(0);
5749     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5750       unsigned LargeShiftVal = LargeShift->getZExtValue();
5751       EVT LargeVT = N0Op0.getValueType();
5752 
5753       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5754         SDLoc DL(N);
5755         SDValue Amt =
5756           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5757                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5758         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5759                                   N0Op0.getOperand(0), Amt);
5760         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5761       }
5762     }
5763   }
5764 
5765   // Simplify, based on bits shifted out of the LHS.
5766   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5767     return SDValue(N, 0);
5768 
5769 
5770   // If the sign bit is known to be zero, switch this to a SRL.
5771   if (DAG.SignBitIsZero(N0))
5772     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5773 
5774   if (N1C && !N1C->isOpaque())
5775     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5776       return NewSRA;
5777 
5778   return SDValue();
5779 }
5780 
5781 SDValue DAGCombiner::visitSRL(SDNode *N) {
5782   SDValue N0 = N->getOperand(0);
5783   SDValue N1 = N->getOperand(1);
5784   EVT VT = N0.getValueType();
5785   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5786 
5787   // fold vector ops
5788   if (VT.isVector())
5789     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5790       return FoldedVOp;
5791 
5792   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5793 
5794   // fold (srl c1, c2) -> c1 >>u c2
5795   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5796   if (N0C && N1C && !N1C->isOpaque())
5797     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5798   // fold (srl 0, x) -> 0
5799   if (isNullConstantOrNullSplatConstant(N0))
5800     return N0;
5801   // fold (srl x, c >= size(x)) -> undef
5802   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5803   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5804     return Val->getAPIntValue().uge(OpSizeInBits);
5805   };
5806   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5807     return DAG.getUNDEF(VT);
5808   // fold (srl x, 0) -> x
5809   if (N1C && N1C->isNullValue())
5810     return N0;
5811 
5812   if (SDValue NewSel = foldBinOpIntoSelect(N))
5813     return NewSel;
5814 
5815   // if (srl x, c) is known to be zero, return 0
5816   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5817                                    APInt::getAllOnesValue(OpSizeInBits)))
5818     return DAG.getConstant(0, SDLoc(N), VT);
5819 
5820   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5821   if (N0.getOpcode() == ISD::SRL) {
5822     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5823                                           ConstantSDNode *RHS) {
5824       APInt c1 = LHS->getAPIntValue();
5825       APInt c2 = RHS->getAPIntValue();
5826       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5827       return (c1 + c2).uge(OpSizeInBits);
5828     };
5829     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5830       return DAG.getConstant(0, SDLoc(N), VT);
5831 
5832     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5833                                        ConstantSDNode *RHS) {
5834       APInt c1 = LHS->getAPIntValue();
5835       APInt c2 = RHS->getAPIntValue();
5836       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5837       return (c1 + c2).ult(OpSizeInBits);
5838     };
5839     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5840       SDLoc DL(N);
5841       EVT ShiftVT = N1.getValueType();
5842       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5843       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
5844     }
5845   }
5846 
5847   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5848   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5849       N0.getOperand(0).getOpcode() == ISD::SRL) {
5850     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5851       uint64_t c1 = N001C->getZExtValue();
5852       uint64_t c2 = N1C->getZExtValue();
5853       EVT InnerShiftVT = N0.getOperand(0).getValueType();
5854       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5855       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5856       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5857       if (c1 + OpSizeInBits == InnerShiftSize) {
5858         SDLoc DL(N0);
5859         if (c1 + c2 >= InnerShiftSize)
5860           return DAG.getConstant(0, DL, VT);
5861         return DAG.getNode(ISD::TRUNCATE, DL, VT,
5862                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5863                                        N0.getOperand(0).getOperand(0),
5864                                        DAG.getConstant(c1 + c2, DL,
5865                                                        ShiftCountVT)));
5866       }
5867     }
5868   }
5869 
5870   // fold (srl (shl x, c), c) -> (and x, cst2)
5871   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5872       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5873     SDLoc DL(N);
5874     SDValue Mask =
5875         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5876     AddToWorklist(Mask.getNode());
5877     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5878   }
5879 
5880   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5881   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5882     // Shifting in all undef bits?
5883     EVT SmallVT = N0.getOperand(0).getValueType();
5884     unsigned BitSize = SmallVT.getScalarSizeInBits();
5885     if (N1C->getZExtValue() >= BitSize)
5886       return DAG.getUNDEF(VT);
5887 
5888     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5889       uint64_t ShiftAmt = N1C->getZExtValue();
5890       SDLoc DL0(N0);
5891       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5892                                        N0.getOperand(0),
5893                           DAG.getConstant(ShiftAmt, DL0,
5894                                           getShiftAmountTy(SmallVT)));
5895       AddToWorklist(SmallShift.getNode());
5896       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5897       SDLoc DL(N);
5898       return DAG.getNode(ISD::AND, DL, VT,
5899                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5900                          DAG.getConstant(Mask, DL, VT));
5901     }
5902   }
5903 
5904   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5905   // bit, which is unmodified by sra.
5906   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5907     if (N0.getOpcode() == ISD::SRA)
5908       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5909   }
5910 
5911   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5912   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5913       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5914     KnownBits Known;
5915     DAG.computeKnownBits(N0.getOperand(0), Known);
5916 
5917     // If any of the input bits are KnownOne, then the input couldn't be all
5918     // zeros, thus the result of the srl will always be zero.
5919     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5920 
5921     // If all of the bits input the to ctlz node are known to be zero, then
5922     // the result of the ctlz is "32" and the result of the shift is one.
5923     APInt UnknownBits = ~Known.Zero;
5924     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5925 
5926     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5927     if (UnknownBits.isPowerOf2()) {
5928       // Okay, we know that only that the single bit specified by UnknownBits
5929       // could be set on input to the CTLZ node. If this bit is set, the SRL
5930       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5931       // to an SRL/XOR pair, which is likely to simplify more.
5932       unsigned ShAmt = UnknownBits.countTrailingZeros();
5933       SDValue Op = N0.getOperand(0);
5934 
5935       if (ShAmt) {
5936         SDLoc DL(N0);
5937         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5938                   DAG.getConstant(ShAmt, DL,
5939                                   getShiftAmountTy(Op.getValueType())));
5940         AddToWorklist(Op.getNode());
5941       }
5942 
5943       SDLoc DL(N);
5944       return DAG.getNode(ISD::XOR, DL, VT,
5945                          Op, DAG.getConstant(1, DL, VT));
5946     }
5947   }
5948 
5949   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5950   if (N1.getOpcode() == ISD::TRUNCATE &&
5951       N1.getOperand(0).getOpcode() == ISD::AND) {
5952     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5953       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5954   }
5955 
5956   // fold operands of srl based on knowledge that the low bits are not
5957   // demanded.
5958   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5959     return SDValue(N, 0);
5960 
5961   if (N1C && !N1C->isOpaque())
5962     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5963       return NewSRL;
5964 
5965   // Attempt to convert a srl of a load into a narrower zero-extending load.
5966   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5967     return NarrowLoad;
5968 
5969   // Here is a common situation. We want to optimize:
5970   //
5971   //   %a = ...
5972   //   %b = and i32 %a, 2
5973   //   %c = srl i32 %b, 1
5974   //   brcond i32 %c ...
5975   //
5976   // into
5977   //
5978   //   %a = ...
5979   //   %b = and %a, 2
5980   //   %c = setcc eq %b, 0
5981   //   brcond %c ...
5982   //
5983   // However when after the source operand of SRL is optimized into AND, the SRL
5984   // itself may not be optimized further. Look for it and add the BRCOND into
5985   // the worklist.
5986   if (N->hasOneUse()) {
5987     SDNode *Use = *N->use_begin();
5988     if (Use->getOpcode() == ISD::BRCOND)
5989       AddToWorklist(Use);
5990     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5991       // Also look pass the truncate.
5992       Use = *Use->use_begin();
5993       if (Use->getOpcode() == ISD::BRCOND)
5994         AddToWorklist(Use);
5995     }
5996   }
5997 
5998   return SDValue();
5999 }
6000 
6001 SDValue DAGCombiner::visitABS(SDNode *N) {
6002   SDValue N0 = N->getOperand(0);
6003   EVT VT = N->getValueType(0);
6004 
6005   // fold (abs c1) -> c2
6006   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6007     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
6008   // fold (abs (abs x)) -> (abs x)
6009   if (N0.getOpcode() == ISD::ABS)
6010     return N0;
6011   // fold (abs x) -> x iff not-negative
6012   if (DAG.SignBitIsZero(N0))
6013     return N0;
6014   return SDValue();
6015 }
6016 
6017 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
6018   SDValue N0 = N->getOperand(0);
6019   EVT VT = N->getValueType(0);
6020 
6021   // fold (bswap c1) -> c2
6022   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6023     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
6024   // fold (bswap (bswap x)) -> x
6025   if (N0.getOpcode() == ISD::BSWAP)
6026     return N0->getOperand(0);
6027   return SDValue();
6028 }
6029 
6030 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
6031   SDValue N0 = N->getOperand(0);
6032   EVT VT = N->getValueType(0);
6033 
6034   // fold (bitreverse c1) -> c2
6035   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6036     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
6037   // fold (bitreverse (bitreverse x)) -> x
6038   if (N0.getOpcode() == ISD::BITREVERSE)
6039     return N0.getOperand(0);
6040   return SDValue();
6041 }
6042 
6043 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
6044   SDValue N0 = N->getOperand(0);
6045   EVT VT = N->getValueType(0);
6046 
6047   // fold (ctlz c1) -> c2
6048   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6049     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
6050   return SDValue();
6051 }
6052 
6053 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
6054   SDValue N0 = N->getOperand(0);
6055   EVT VT = N->getValueType(0);
6056 
6057   // fold (ctlz_zero_undef c1) -> c2
6058   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6059     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6060   return SDValue();
6061 }
6062 
6063 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
6064   SDValue N0 = N->getOperand(0);
6065   EVT VT = N->getValueType(0);
6066 
6067   // fold (cttz c1) -> c2
6068   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6069     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
6070   return SDValue();
6071 }
6072 
6073 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
6074   SDValue N0 = N->getOperand(0);
6075   EVT VT = N->getValueType(0);
6076 
6077   // fold (cttz_zero_undef c1) -> c2
6078   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6079     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6080   return SDValue();
6081 }
6082 
6083 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6084   SDValue N0 = N->getOperand(0);
6085   EVT VT = N->getValueType(0);
6086 
6087   // fold (ctpop c1) -> c2
6088   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6089     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6090   return SDValue();
6091 }
6092 
6093 
6094 /// \brief Generate Min/Max node
6095 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6096                                    SDValue RHS, SDValue True, SDValue False,
6097                                    ISD::CondCode CC, const TargetLowering &TLI,
6098                                    SelectionDAG &DAG) {
6099   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6100     return SDValue();
6101 
6102   switch (CC) {
6103   case ISD::SETOLT:
6104   case ISD::SETOLE:
6105   case ISD::SETLT:
6106   case ISD::SETLE:
6107   case ISD::SETULT:
6108   case ISD::SETULE: {
6109     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6110     if (TLI.isOperationLegal(Opcode, VT))
6111       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6112     return SDValue();
6113   }
6114   case ISD::SETOGT:
6115   case ISD::SETOGE:
6116   case ISD::SETGT:
6117   case ISD::SETGE:
6118   case ISD::SETUGT:
6119   case ISD::SETUGE: {
6120     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6121     if (TLI.isOperationLegal(Opcode, VT))
6122       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6123     return SDValue();
6124   }
6125   default:
6126     return SDValue();
6127   }
6128 }
6129 
6130 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6131   SDValue Cond = N->getOperand(0);
6132   SDValue N1 = N->getOperand(1);
6133   SDValue N2 = N->getOperand(2);
6134   EVT VT = N->getValueType(0);
6135   EVT CondVT = Cond.getValueType();
6136   SDLoc DL(N);
6137 
6138   if (!VT.isInteger())
6139     return SDValue();
6140 
6141   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6142   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6143   if (!C1 || !C2)
6144     return SDValue();
6145 
6146   // Only do this before legalization to avoid conflicting with target-specific
6147   // transforms in the other direction (create a select from a zext/sext). There
6148   // is also a target-independent combine here in DAGCombiner in the other
6149   // direction for (select Cond, -1, 0) when the condition is not i1.
6150   if (CondVT == MVT::i1 && !LegalOperations) {
6151     if (C1->isNullValue() && C2->isOne()) {
6152       // select Cond, 0, 1 --> zext (!Cond)
6153       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6154       if (VT != MVT::i1)
6155         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6156       return NotCond;
6157     }
6158     if (C1->isNullValue() && C2->isAllOnesValue()) {
6159       // select Cond, 0, -1 --> sext (!Cond)
6160       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6161       if (VT != MVT::i1)
6162         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6163       return NotCond;
6164     }
6165     if (C1->isOne() && C2->isNullValue()) {
6166       // select Cond, 1, 0 --> zext (Cond)
6167       if (VT != MVT::i1)
6168         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6169       return Cond;
6170     }
6171     if (C1->isAllOnesValue() && C2->isNullValue()) {
6172       // select Cond, -1, 0 --> sext (Cond)
6173       if (VT != MVT::i1)
6174         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6175       return Cond;
6176     }
6177 
6178     // For any constants that differ by 1, we can transform the select into an
6179     // extend and add. Use a target hook because some targets may prefer to
6180     // transform in the other direction.
6181     if (TLI.convertSelectOfConstantsToMath()) {
6182       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6183         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6184         if (VT != MVT::i1)
6185           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6186         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6187       }
6188       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6189         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6190         if (VT != MVT::i1)
6191           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6192         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6193       }
6194     }
6195 
6196     return SDValue();
6197   }
6198 
6199   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6200   // We can't do this reliably if integer based booleans have different contents
6201   // to floating point based booleans. This is because we can't tell whether we
6202   // have an integer-based boolean or a floating-point-based boolean unless we
6203   // can find the SETCC that produced it and inspect its operands. This is
6204   // fairly easy if C is the SETCC node, but it can potentially be
6205   // undiscoverable (or not reasonably discoverable). For example, it could be
6206   // in another basic block or it could require searching a complicated
6207   // expression.
6208   if (CondVT.isInteger() &&
6209       TLI.getBooleanContents(false, true) ==
6210           TargetLowering::ZeroOrOneBooleanContent &&
6211       TLI.getBooleanContents(false, false) ==
6212           TargetLowering::ZeroOrOneBooleanContent &&
6213       C1->isNullValue() && C2->isOne()) {
6214     SDValue NotCond =
6215         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6216     if (VT.bitsEq(CondVT))
6217       return NotCond;
6218     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6219   }
6220 
6221   return SDValue();
6222 }
6223 
6224 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6225   SDValue N0 = N->getOperand(0);
6226   SDValue N1 = N->getOperand(1);
6227   SDValue N2 = N->getOperand(2);
6228   EVT VT = N->getValueType(0);
6229   EVT VT0 = N0.getValueType();
6230   SDLoc DL(N);
6231 
6232   // fold (select C, X, X) -> X
6233   if (N1 == N2)
6234     return N1;
6235 
6236   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6237     // fold (select true, X, Y) -> X
6238     // fold (select false, X, Y) -> Y
6239     return !N0C->isNullValue() ? N1 : N2;
6240   }
6241 
6242   // fold (select X, X, Y) -> (or X, Y)
6243   // fold (select X, 1, Y) -> (or C, Y)
6244   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6245     return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6246 
6247   if (SDValue V = foldSelectOfConstants(N))
6248     return V;
6249 
6250   // fold (select C, 0, X) -> (and (not C), X)
6251   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6252     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6253     AddToWorklist(NOTNode.getNode());
6254     return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6255   }
6256   // fold (select C, X, 1) -> (or (not C), X)
6257   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6258     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6259     AddToWorklist(NOTNode.getNode());
6260     return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6261   }
6262   // fold (select X, Y, X) -> (and X, Y)
6263   // fold (select X, Y, 0) -> (and X, Y)
6264   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6265     return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6266 
6267   // If we can fold this based on the true/false value, do so.
6268   if (SimplifySelectOps(N, N1, N2))
6269     return SDValue(N, 0); // Don't revisit N.
6270 
6271   if (VT0 == MVT::i1) {
6272     // The code in this block deals with the following 2 equivalences:
6273     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6274     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6275     // The target can specify its preferred form with the
6276     // shouldNormalizeToSelectSequence() callback. However we always transform
6277     // to the right anyway if we find the inner select exists in the DAG anyway
6278     // and we always transform to the left side if we know that we can further
6279     // optimize the combination of the conditions.
6280     bool normalizeToSequence =
6281         TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6282     // select (and Cond0, Cond1), X, Y
6283     //   -> select Cond0, (select Cond1, X, Y), Y
6284     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6285       SDValue Cond0 = N0->getOperand(0);
6286       SDValue Cond1 = N0->getOperand(1);
6287       SDValue InnerSelect =
6288           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6289       if (normalizeToSequence || !InnerSelect.use_empty())
6290         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6291                            InnerSelect, N2);
6292     }
6293     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6294     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6295       SDValue Cond0 = N0->getOperand(0);
6296       SDValue Cond1 = N0->getOperand(1);
6297       SDValue InnerSelect =
6298           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6299       if (normalizeToSequence || !InnerSelect.use_empty())
6300         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6301                            InnerSelect);
6302     }
6303 
6304     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6305     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6306       SDValue N1_0 = N1->getOperand(0);
6307       SDValue N1_1 = N1->getOperand(1);
6308       SDValue N1_2 = N1->getOperand(2);
6309       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6310         // Create the actual and node if we can generate good code for it.
6311         if (!normalizeToSequence) {
6312           SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6313           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6314         }
6315         // Otherwise see if we can optimize the "and" to a better pattern.
6316         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6317           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6318                              N2);
6319       }
6320     }
6321     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6322     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6323       SDValue N2_0 = N2->getOperand(0);
6324       SDValue N2_1 = N2->getOperand(1);
6325       SDValue N2_2 = N2->getOperand(2);
6326       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6327         // Create the actual or node if we can generate good code for it.
6328         if (!normalizeToSequence) {
6329           SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6330           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6331         }
6332         // Otherwise see if we can optimize to a better pattern.
6333         if (SDValue Combined = visitORLike(N0, N2_0, N))
6334           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6335                              N2_2);
6336       }
6337     }
6338   }
6339 
6340   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6341   if (VT0 == MVT::i1) {
6342     if (N0->getOpcode() == ISD::XOR) {
6343       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6344         SDValue Cond0 = N0->getOperand(0);
6345         if (C->isOne())
6346           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6347       }
6348     }
6349   }
6350 
6351   // fold selects based on a setcc into other things, such as min/max/abs
6352   if (N0.getOpcode() == ISD::SETCC) {
6353     // select x, y (fcmp lt x, y) -> fminnum x, y
6354     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6355     //
6356     // This is OK if we don't care about what happens if either operand is a
6357     // NaN.
6358     //
6359 
6360     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6361     // no signed zeros as well as no nans.
6362     const TargetOptions &Options = DAG.getTarget().Options;
6363     if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6364         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6365       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6366 
6367       if (SDValue FMinMax = combineMinNumMaxNum(
6368               DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6369         return FMinMax;
6370     }
6371 
6372     if ((!LegalOperations &&
6373          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6374         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6375       return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6376                          N0.getOperand(1), N1, N2, N0.getOperand(2));
6377     return SimplifySelect(DL, N0, N1, N2);
6378   }
6379 
6380   return SDValue();
6381 }
6382 
6383 static
6384 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6385   SDLoc DL(N);
6386   EVT LoVT, HiVT;
6387   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6388 
6389   // Split the inputs.
6390   SDValue Lo, Hi, LL, LH, RL, RH;
6391   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6392   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6393 
6394   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6395   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6396 
6397   return std::make_pair(Lo, Hi);
6398 }
6399 
6400 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6401 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6402 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6403   SDLoc DL(N);
6404   SDValue Cond = N->getOperand(0);
6405   SDValue LHS = N->getOperand(1);
6406   SDValue RHS = N->getOperand(2);
6407   EVT VT = N->getValueType(0);
6408   int NumElems = VT.getVectorNumElements();
6409   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6410          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6411          Cond.getOpcode() == ISD::BUILD_VECTOR);
6412 
6413   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6414   // binary ones here.
6415   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6416     return SDValue();
6417 
6418   // We're sure we have an even number of elements due to the
6419   // concat_vectors we have as arguments to vselect.
6420   // Skip BV elements until we find one that's not an UNDEF
6421   // After we find an UNDEF element, keep looping until we get to half the
6422   // length of the BV and see if all the non-undef nodes are the same.
6423   ConstantSDNode *BottomHalf = nullptr;
6424   for (int i = 0; i < NumElems / 2; ++i) {
6425     if (Cond->getOperand(i)->isUndef())
6426       continue;
6427 
6428     if (BottomHalf == nullptr)
6429       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6430     else if (Cond->getOperand(i).getNode() != BottomHalf)
6431       return SDValue();
6432   }
6433 
6434   // Do the same for the second half of the BuildVector
6435   ConstantSDNode *TopHalf = nullptr;
6436   for (int i = NumElems / 2; i < NumElems; ++i) {
6437     if (Cond->getOperand(i)->isUndef())
6438       continue;
6439 
6440     if (TopHalf == nullptr)
6441       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6442     else if (Cond->getOperand(i).getNode() != TopHalf)
6443       return SDValue();
6444   }
6445 
6446   assert(TopHalf && BottomHalf &&
6447          "One half of the selector was all UNDEFs and the other was all the "
6448          "same value. This should have been addressed before this function.");
6449   return DAG.getNode(
6450       ISD::CONCAT_VECTORS, DL, VT,
6451       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6452       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6453 }
6454 
6455 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6456 
6457   if (Level >= AfterLegalizeTypes)
6458     return SDValue();
6459 
6460   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6461   SDValue Mask = MSC->getMask();
6462   SDValue Data  = MSC->getValue();
6463   SDLoc DL(N);
6464 
6465   // If the MSCATTER data type requires splitting and the mask is provided by a
6466   // SETCC, then split both nodes and its operands before legalization. This
6467   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6468   // and enables future optimizations (e.g. min/max pattern matching on X86).
6469   if (Mask.getOpcode() != ISD::SETCC)
6470     return SDValue();
6471 
6472   // Check if any splitting is required.
6473   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6474       TargetLowering::TypeSplitVector)
6475     return SDValue();
6476   SDValue MaskLo, MaskHi, Lo, Hi;
6477   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6478 
6479   EVT LoVT, HiVT;
6480   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6481 
6482   SDValue Chain = MSC->getChain();
6483 
6484   EVT MemoryVT = MSC->getMemoryVT();
6485   unsigned Alignment = MSC->getOriginalAlignment();
6486 
6487   EVT LoMemVT, HiMemVT;
6488   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6489 
6490   SDValue DataLo, DataHi;
6491   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6492 
6493   SDValue BasePtr = MSC->getBasePtr();
6494   SDValue IndexLo, IndexHi;
6495   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6496 
6497   MachineMemOperand *MMO = DAG.getMachineFunction().
6498     getMachineMemOperand(MSC->getPointerInfo(),
6499                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6500                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6501 
6502   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6503   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6504                             DL, OpsLo, MMO);
6505 
6506   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6507   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6508                             DL, OpsHi, MMO);
6509 
6510   AddToWorklist(Lo.getNode());
6511   AddToWorklist(Hi.getNode());
6512 
6513   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6514 }
6515 
6516 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6517 
6518   if (Level >= AfterLegalizeTypes)
6519     return SDValue();
6520 
6521   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6522   SDValue Mask = MST->getMask();
6523   SDValue Data  = MST->getValue();
6524   EVT VT = Data.getValueType();
6525   SDLoc DL(N);
6526 
6527   // If the MSTORE data type requires splitting and the mask is provided by a
6528   // SETCC, then split both nodes and its operands before legalization. This
6529   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6530   // and enables future optimizations (e.g. min/max pattern matching on X86).
6531   if (Mask.getOpcode() == ISD::SETCC) {
6532 
6533     // Check if any splitting is required.
6534     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6535         TargetLowering::TypeSplitVector)
6536       return SDValue();
6537 
6538     SDValue MaskLo, MaskHi, Lo, Hi;
6539     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6540 
6541     SDValue Chain = MST->getChain();
6542     SDValue Ptr   = MST->getBasePtr();
6543 
6544     EVT MemoryVT = MST->getMemoryVT();
6545     unsigned Alignment = MST->getOriginalAlignment();
6546 
6547     // if Alignment is equal to the vector size,
6548     // take the half of it for the second part
6549     unsigned SecondHalfAlignment =
6550       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6551 
6552     EVT LoMemVT, HiMemVT;
6553     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6554 
6555     SDValue DataLo, DataHi;
6556     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6557 
6558     MachineMemOperand *MMO = DAG.getMachineFunction().
6559       getMachineMemOperand(MST->getPointerInfo(),
6560                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6561                            Alignment, MST->getAAInfo(), MST->getRanges());
6562 
6563     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6564                             MST->isTruncatingStore(),
6565                             MST->isCompressingStore());
6566 
6567     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6568                                      MST->isCompressingStore());
6569 
6570     MMO = DAG.getMachineFunction().
6571       getMachineMemOperand(MST->getPointerInfo(),
6572                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6573                            SecondHalfAlignment, MST->getAAInfo(),
6574                            MST->getRanges());
6575 
6576     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6577                             MST->isTruncatingStore(),
6578                             MST->isCompressingStore());
6579 
6580     AddToWorklist(Lo.getNode());
6581     AddToWorklist(Hi.getNode());
6582 
6583     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6584   }
6585   return SDValue();
6586 }
6587 
6588 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6589 
6590   if (Level >= AfterLegalizeTypes)
6591     return SDValue();
6592 
6593   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6594   SDValue Mask = MGT->getMask();
6595   SDLoc DL(N);
6596 
6597   // If the MGATHER result requires splitting and the mask is provided by a
6598   // SETCC, then split both nodes and its operands before legalization. This
6599   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6600   // and enables future optimizations (e.g. min/max pattern matching on X86).
6601 
6602   if (Mask.getOpcode() != ISD::SETCC)
6603     return SDValue();
6604 
6605   EVT VT = N->getValueType(0);
6606 
6607   // Check if any splitting is required.
6608   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6609       TargetLowering::TypeSplitVector)
6610     return SDValue();
6611 
6612   SDValue MaskLo, MaskHi, Lo, Hi;
6613   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6614 
6615   SDValue Src0 = MGT->getValue();
6616   SDValue Src0Lo, Src0Hi;
6617   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6618 
6619   EVT LoVT, HiVT;
6620   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6621 
6622   SDValue Chain = MGT->getChain();
6623   EVT MemoryVT = MGT->getMemoryVT();
6624   unsigned Alignment = MGT->getOriginalAlignment();
6625 
6626   EVT LoMemVT, HiMemVT;
6627   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6628 
6629   SDValue BasePtr = MGT->getBasePtr();
6630   SDValue Index = MGT->getIndex();
6631   SDValue IndexLo, IndexHi;
6632   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6633 
6634   MachineMemOperand *MMO = DAG.getMachineFunction().
6635     getMachineMemOperand(MGT->getPointerInfo(),
6636                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6637                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6638 
6639   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6640   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6641                             MMO);
6642 
6643   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6644   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6645                             MMO);
6646 
6647   AddToWorklist(Lo.getNode());
6648   AddToWorklist(Hi.getNode());
6649 
6650   // Build a factor node to remember that this load is independent of the
6651   // other one.
6652   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6653                       Hi.getValue(1));
6654 
6655   // Legalized the chain result - switch anything that used the old chain to
6656   // use the new one.
6657   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6658 
6659   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6660 
6661   SDValue RetOps[] = { GatherRes, Chain };
6662   return DAG.getMergeValues(RetOps, DL);
6663 }
6664 
6665 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6666 
6667   if (Level >= AfterLegalizeTypes)
6668     return SDValue();
6669 
6670   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6671   SDValue Mask = MLD->getMask();
6672   SDLoc DL(N);
6673 
6674   // If the MLOAD result requires splitting and the mask is provided by a
6675   // SETCC, then split both nodes and its operands before legalization. This
6676   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6677   // and enables future optimizations (e.g. min/max pattern matching on X86).
6678 
6679   if (Mask.getOpcode() == ISD::SETCC) {
6680     EVT VT = N->getValueType(0);
6681 
6682     // Check if any splitting is required.
6683     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6684         TargetLowering::TypeSplitVector)
6685       return SDValue();
6686 
6687     SDValue MaskLo, MaskHi, Lo, Hi;
6688     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6689 
6690     SDValue Src0 = MLD->getSrc0();
6691     SDValue Src0Lo, Src0Hi;
6692     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6693 
6694     EVT LoVT, HiVT;
6695     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6696 
6697     SDValue Chain = MLD->getChain();
6698     SDValue Ptr   = MLD->getBasePtr();
6699     EVT MemoryVT = MLD->getMemoryVT();
6700     unsigned Alignment = MLD->getOriginalAlignment();
6701 
6702     // if Alignment is equal to the vector size,
6703     // take the half of it for the second part
6704     unsigned SecondHalfAlignment =
6705       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6706          Alignment/2 : Alignment;
6707 
6708     EVT LoMemVT, HiMemVT;
6709     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6710 
6711     MachineMemOperand *MMO = DAG.getMachineFunction().
6712     getMachineMemOperand(MLD->getPointerInfo(),
6713                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6714                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6715 
6716     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6717                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6718 
6719     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6720                                      MLD->isExpandingLoad());
6721 
6722     MMO = DAG.getMachineFunction().
6723     getMachineMemOperand(MLD->getPointerInfo(),
6724                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6725                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6726 
6727     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6728                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6729 
6730     AddToWorklist(Lo.getNode());
6731     AddToWorklist(Hi.getNode());
6732 
6733     // Build a factor node to remember that this load is independent of the
6734     // other one.
6735     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6736                         Hi.getValue(1));
6737 
6738     // Legalized the chain result - switch anything that used the old chain to
6739     // use the new one.
6740     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6741 
6742     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6743 
6744     SDValue RetOps[] = { LoadRes, Chain };
6745     return DAG.getMergeValues(RetOps, DL);
6746   }
6747   return SDValue();
6748 }
6749 
6750 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6751   SDValue N0 = N->getOperand(0);
6752   SDValue N1 = N->getOperand(1);
6753   SDValue N2 = N->getOperand(2);
6754   SDLoc DL(N);
6755 
6756   // fold (vselect C, X, X) -> X
6757   if (N1 == N2)
6758     return N1;
6759 
6760   // Canonicalize integer abs.
6761   // vselect (setg[te] X,  0),  X, -X ->
6762   // vselect (setgt    X, -1),  X, -X ->
6763   // vselect (setl[te] X,  0), -X,  X ->
6764   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6765   if (N0.getOpcode() == ISD::SETCC) {
6766     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6767     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6768     bool isAbs = false;
6769     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6770 
6771     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6772          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6773         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6774       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6775     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6776              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6777       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6778 
6779     if (isAbs) {
6780       EVT VT = LHS.getValueType();
6781       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
6782         return DAG.getNode(ISD::ABS, DL, VT, LHS);
6783 
6784       SDValue Shift = DAG.getNode(
6785           ISD::SRA, DL, VT, LHS,
6786           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6787       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6788       AddToWorklist(Shift.getNode());
6789       AddToWorklist(Add.getNode());
6790       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6791     }
6792   }
6793 
6794   if (SimplifySelectOps(N, N1, N2))
6795     return SDValue(N, 0);  // Don't revisit N.
6796 
6797   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6798   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6799     return N1;
6800   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6801   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6802     return N2;
6803 
6804   // The ConvertSelectToConcatVector function is assuming both the above
6805   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6806   // and addressed.
6807   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6808       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6809       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6810     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6811       return CV;
6812   }
6813 
6814   return SDValue();
6815 }
6816 
6817 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6818   SDValue N0 = N->getOperand(0);
6819   SDValue N1 = N->getOperand(1);
6820   SDValue N2 = N->getOperand(2);
6821   SDValue N3 = N->getOperand(3);
6822   SDValue N4 = N->getOperand(4);
6823   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6824 
6825   // fold select_cc lhs, rhs, x, x, cc -> x
6826   if (N2 == N3)
6827     return N2;
6828 
6829   // Determine if the condition we're dealing with is constant
6830   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6831                                   CC, SDLoc(N), false)) {
6832     AddToWorklist(SCC.getNode());
6833 
6834     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6835       if (!SCCC->isNullValue())
6836         return N2;    // cond always true -> true val
6837       else
6838         return N3;    // cond always false -> false val
6839     } else if (SCC->isUndef()) {
6840       // When the condition is UNDEF, just return the first operand. This is
6841       // coherent the DAG creation, no setcc node is created in this case
6842       return N2;
6843     } else if (SCC.getOpcode() == ISD::SETCC) {
6844       // Fold to a simpler select_cc
6845       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6846                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6847                          SCC.getOperand(2));
6848     }
6849   }
6850 
6851   // If we can fold this based on the true/false value, do so.
6852   if (SimplifySelectOps(N, N2, N3))
6853     return SDValue(N, 0);  // Don't revisit N.
6854 
6855   // fold select_cc into other things, such as min/max/abs
6856   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6857 }
6858 
6859 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6860   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6861                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6862                        SDLoc(N));
6863 }
6864 
6865 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6866   SDValue LHS = N->getOperand(0);
6867   SDValue RHS = N->getOperand(1);
6868   SDValue Carry = N->getOperand(2);
6869   SDValue Cond = N->getOperand(3);
6870 
6871   // If Carry is false, fold to a regular SETCC.
6872   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6873     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6874 
6875   return SDValue();
6876 }
6877 
6878 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
6879   SDValue LHS = N->getOperand(0);
6880   SDValue RHS = N->getOperand(1);
6881   SDValue Carry = N->getOperand(2);
6882   SDValue Cond = N->getOperand(3);
6883 
6884   // If Carry is false, fold to a regular SETCC.
6885   if (isNullConstant(Carry))
6886     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6887 
6888   return SDValue();
6889 }
6890 
6891 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6892 /// a build_vector of constants.
6893 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6894 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6895 /// Vector extends are not folded if operations are legal; this is to
6896 /// avoid introducing illegal build_vector dag nodes.
6897 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6898                                          SelectionDAG &DAG, bool LegalTypes,
6899                                          bool LegalOperations) {
6900   unsigned Opcode = N->getOpcode();
6901   SDValue N0 = N->getOperand(0);
6902   EVT VT = N->getValueType(0);
6903 
6904   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6905          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6906          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6907          && "Expected EXTEND dag node in input!");
6908 
6909   // fold (sext c1) -> c1
6910   // fold (zext c1) -> c1
6911   // fold (aext c1) -> c1
6912   if (isa<ConstantSDNode>(N0))
6913     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6914 
6915   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6916   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6917   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6918   EVT SVT = VT.getScalarType();
6919   if (!(VT.isVector() &&
6920       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6921       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6922     return nullptr;
6923 
6924   // We can fold this node into a build_vector.
6925   unsigned VTBits = SVT.getSizeInBits();
6926   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6927   SmallVector<SDValue, 8> Elts;
6928   unsigned NumElts = VT.getVectorNumElements();
6929   SDLoc DL(N);
6930 
6931   for (unsigned i=0; i != NumElts; ++i) {
6932     SDValue Op = N0->getOperand(i);
6933     if (Op->isUndef()) {
6934       Elts.push_back(DAG.getUNDEF(SVT));
6935       continue;
6936     }
6937 
6938     SDLoc DL(Op);
6939     // Get the constant value and if needed trunc it to the size of the type.
6940     // Nodes like build_vector might have constants wider than the scalar type.
6941     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6942     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6943       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6944     else
6945       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6946   }
6947 
6948   return DAG.getBuildVector(VT, DL, Elts).getNode();
6949 }
6950 
6951 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6952 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6953 // transformation. Returns true if extension are possible and the above
6954 // mentioned transformation is profitable.
6955 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6956                                     unsigned ExtOpc,
6957                                     SmallVectorImpl<SDNode *> &ExtendNodes,
6958                                     const TargetLowering &TLI) {
6959   bool HasCopyToRegUses = false;
6960   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6961   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6962                             UE = N0.getNode()->use_end();
6963        UI != UE; ++UI) {
6964     SDNode *User = *UI;
6965     if (User == N)
6966       continue;
6967     if (UI.getUse().getResNo() != N0.getResNo())
6968       continue;
6969     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6970     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6971       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6972       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6973         // Sign bits will be lost after a zext.
6974         return false;
6975       bool Add = false;
6976       for (unsigned i = 0; i != 2; ++i) {
6977         SDValue UseOp = User->getOperand(i);
6978         if (UseOp == N0)
6979           continue;
6980         if (!isa<ConstantSDNode>(UseOp))
6981           return false;
6982         Add = true;
6983       }
6984       if (Add)
6985         ExtendNodes.push_back(User);
6986       continue;
6987     }
6988     // If truncates aren't free and there are users we can't
6989     // extend, it isn't worthwhile.
6990     if (!isTruncFree)
6991       return false;
6992     // Remember if this value is live-out.
6993     if (User->getOpcode() == ISD::CopyToReg)
6994       HasCopyToRegUses = true;
6995   }
6996 
6997   if (HasCopyToRegUses) {
6998     bool BothLiveOut = false;
6999     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7000          UI != UE; ++UI) {
7001       SDUse &Use = UI.getUse();
7002       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
7003         BothLiveOut = true;
7004         break;
7005       }
7006     }
7007     if (BothLiveOut)
7008       // Both unextended and extended values are live out. There had better be
7009       // a good reason for the transformation.
7010       return ExtendNodes.size();
7011   }
7012   return true;
7013 }
7014 
7015 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
7016                                   SDValue Trunc, SDValue ExtLoad,
7017                                   const SDLoc &DL, ISD::NodeType ExtType) {
7018   // Extend SetCC uses if necessary.
7019   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
7020     SDNode *SetCC = SetCCs[i];
7021     SmallVector<SDValue, 4> Ops;
7022 
7023     for (unsigned j = 0; j != 2; ++j) {
7024       SDValue SOp = SetCC->getOperand(j);
7025       if (SOp == Trunc)
7026         Ops.push_back(ExtLoad);
7027       else
7028         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
7029     }
7030 
7031     Ops.push_back(SetCC->getOperand(2));
7032     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7033   }
7034 }
7035 
7036 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
7037 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
7038   SDValue N0 = N->getOperand(0);
7039   EVT DstVT = N->getValueType(0);
7040   EVT SrcVT = N0.getValueType();
7041 
7042   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
7043           N->getOpcode() == ISD::ZERO_EXTEND) &&
7044          "Unexpected node type (not an extend)!");
7045 
7046   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
7047   // For example, on a target with legal v4i32, but illegal v8i32, turn:
7048   //   (v8i32 (sext (v8i16 (load x))))
7049   // into:
7050   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
7051   //                          (v4i32 (sextload (x + 16)))))
7052   // Where uses of the original load, i.e.:
7053   //   (v8i16 (load x))
7054   // are replaced with:
7055   //   (v8i16 (truncate
7056   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
7057   //                            (v4i32 (sextload (x + 16)))))))
7058   //
7059   // This combine is only applicable to illegal, but splittable, vectors.
7060   // All legal types, and illegal non-vector types, are handled elsewhere.
7061   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
7062   //
7063   if (N0->getOpcode() != ISD::LOAD)
7064     return SDValue();
7065 
7066   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7067 
7068   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
7069       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
7070       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
7071     return SDValue();
7072 
7073   SmallVector<SDNode *, 4> SetCCs;
7074   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
7075     return SDValue();
7076 
7077   ISD::LoadExtType ExtType =
7078       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7079 
7080   // Try to split the vector types to get down to legal types.
7081   EVT SplitSrcVT = SrcVT;
7082   EVT SplitDstVT = DstVT;
7083   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7084          SplitSrcVT.getVectorNumElements() > 1) {
7085     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7086     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7087   }
7088 
7089   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7090     return SDValue();
7091 
7092   SDLoc DL(N);
7093   const unsigned NumSplits =
7094       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7095   const unsigned Stride = SplitSrcVT.getStoreSize();
7096   SmallVector<SDValue, 4> Loads;
7097   SmallVector<SDValue, 4> Chains;
7098 
7099   SDValue BasePtr = LN0->getBasePtr();
7100   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7101     const unsigned Offset = Idx * Stride;
7102     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7103 
7104     SDValue SplitLoad = DAG.getExtLoad(
7105         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7106         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7107         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7108 
7109     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7110                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7111 
7112     Loads.push_back(SplitLoad.getValue(0));
7113     Chains.push_back(SplitLoad.getValue(1));
7114   }
7115 
7116   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7117   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7118 
7119   // Simplify TF.
7120   AddToWorklist(NewChain.getNode());
7121 
7122   CombineTo(N, NewValue);
7123 
7124   // Replace uses of the original load (before extension)
7125   // with a truncate of the concatenated sextloaded vectors.
7126   SDValue Trunc =
7127       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7128   CombineTo(N0.getNode(), Trunc, NewChain);
7129   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7130                   (ISD::NodeType)N->getOpcode());
7131   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7132 }
7133 
7134 /// If we're narrowing or widening the result of a vector select and the final
7135 /// size is the same size as a setcc (compare) feeding the select, then try to
7136 /// apply the cast operation to the select's operands because matching vector
7137 /// sizes for a select condition and other operands should be more efficient.
7138 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7139   unsigned CastOpcode = Cast->getOpcode();
7140   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7141           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7142           CastOpcode == ISD::FP_ROUND) &&
7143          "Unexpected opcode for vector select narrowing/widening");
7144 
7145   // We only do this transform before legal ops because the pattern may be
7146   // obfuscated by target-specific operations after legalization. Do not create
7147   // an illegal select op, however, because that may be difficult to lower.
7148   EVT VT = Cast->getValueType(0);
7149   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7150     return SDValue();
7151 
7152   SDValue VSel = Cast->getOperand(0);
7153   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7154       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7155     return SDValue();
7156 
7157   // Does the setcc have the same vector size as the casted select?
7158   SDValue SetCC = VSel.getOperand(0);
7159   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7160   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7161     return SDValue();
7162 
7163   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7164   SDValue A = VSel.getOperand(1);
7165   SDValue B = VSel.getOperand(2);
7166   SDValue CastA, CastB;
7167   SDLoc DL(Cast);
7168   if (CastOpcode == ISD::FP_ROUND) {
7169     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7170     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7171     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7172   } else {
7173     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7174     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7175   }
7176   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7177 }
7178 
7179 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7180   SDValue N0 = N->getOperand(0);
7181   EVT VT = N->getValueType(0);
7182   SDLoc DL(N);
7183 
7184   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7185                                               LegalOperations))
7186     return SDValue(Res, 0);
7187 
7188   // fold (sext (sext x)) -> (sext x)
7189   // fold (sext (aext x)) -> (sext x)
7190   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7191     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7192 
7193   if (N0.getOpcode() == ISD::TRUNCATE) {
7194     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7195     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7196     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7197       SDNode *oye = N0.getOperand(0).getNode();
7198       if (NarrowLoad.getNode() != N0.getNode()) {
7199         CombineTo(N0.getNode(), NarrowLoad);
7200         // CombineTo deleted the truncate, if needed, but not what's under it.
7201         AddToWorklist(oye);
7202       }
7203       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7204     }
7205 
7206     // See if the value being truncated is already sign extended.  If so, just
7207     // eliminate the trunc/sext pair.
7208     SDValue Op = N0.getOperand(0);
7209     unsigned OpBits   = Op.getScalarValueSizeInBits();
7210     unsigned MidBits  = N0.getScalarValueSizeInBits();
7211     unsigned DestBits = VT.getScalarSizeInBits();
7212     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7213 
7214     if (OpBits == DestBits) {
7215       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7216       // bits, it is already ready.
7217       if (NumSignBits > DestBits-MidBits)
7218         return Op;
7219     } else if (OpBits < DestBits) {
7220       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7221       // bits, just sext from i32.
7222       if (NumSignBits > OpBits-MidBits)
7223         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7224     } else {
7225       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7226       // bits, just truncate to i32.
7227       if (NumSignBits > OpBits-MidBits)
7228         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7229     }
7230 
7231     // fold (sext (truncate x)) -> (sextinreg x).
7232     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7233                                                  N0.getValueType())) {
7234       if (OpBits < DestBits)
7235         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7236       else if (OpBits > DestBits)
7237         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7238       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7239                          DAG.getValueType(N0.getValueType()));
7240     }
7241   }
7242 
7243   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7244   // Only generate vector extloads when 1) they're legal, and 2) they are
7245   // deemed desirable by the target.
7246   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7247       ((!LegalOperations && !VT.isVector() &&
7248         !cast<LoadSDNode>(N0)->isVolatile()) ||
7249        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7250     bool DoXform = true;
7251     SmallVector<SDNode*, 4> SetCCs;
7252     if (!N0.hasOneUse())
7253       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7254     if (VT.isVector())
7255       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7256     if (DoXform) {
7257       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7258       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7259                                        LN0->getBasePtr(), N0.getValueType(),
7260                                        LN0->getMemOperand());
7261       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7262                                   N0.getValueType(), ExtLoad);
7263       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7264       // If the load value is used only by N, replace it via CombineTo N.
7265       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7266       CombineTo(N, ExtLoad);
7267       if (NoReplaceTrunc)
7268         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7269       else
7270         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7271       return SDValue(N, 0);
7272     }
7273   }
7274 
7275   // fold (sext (load x)) to multiple smaller sextloads.
7276   // Only on illegal but splittable vectors.
7277   if (SDValue ExtLoad = CombineExtLoad(N))
7278     return ExtLoad;
7279 
7280   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7281   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7282   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7283       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7284     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7285     EVT MemVT = LN0->getMemoryVT();
7286     if ((!LegalOperations && !LN0->isVolatile()) ||
7287         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7288       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7289                                        LN0->getBasePtr(), MemVT,
7290                                        LN0->getMemOperand());
7291       CombineTo(N, ExtLoad);
7292       CombineTo(N0.getNode(),
7293                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7294                             N0.getValueType(), ExtLoad),
7295                 ExtLoad.getValue(1));
7296       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7297     }
7298   }
7299 
7300   // fold (sext (and/or/xor (load x), cst)) ->
7301   //      (and/or/xor (sextload x), (sext cst))
7302   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7303        N0.getOpcode() == ISD::XOR) &&
7304       isa<LoadSDNode>(N0.getOperand(0)) &&
7305       N0.getOperand(1).getOpcode() == ISD::Constant &&
7306       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7307       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7308     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7309     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7310       bool DoXform = true;
7311       SmallVector<SDNode*, 4> SetCCs;
7312       if (!N0.hasOneUse())
7313         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7314                                           SetCCs, TLI);
7315       if (DoXform) {
7316         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7317                                          LN0->getChain(), LN0->getBasePtr(),
7318                                          LN0->getMemoryVT(),
7319                                          LN0->getMemOperand());
7320         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7321         Mask = Mask.sext(VT.getSizeInBits());
7322         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7323                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7324         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7325                                     SDLoc(N0.getOperand(0)),
7326                                     N0.getOperand(0).getValueType(), ExtLoad);
7327         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7328         bool NoReplaceTruncAnd = !N0.hasOneUse();
7329         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7330         CombineTo(N, And);
7331         // If N0 has multiple uses, change other uses as well.
7332         if (NoReplaceTruncAnd) {
7333           SDValue TruncAnd =
7334               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7335           CombineTo(N0.getNode(), TruncAnd);
7336         }
7337         if (NoReplaceTrunc)
7338           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7339         else
7340           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7341         return SDValue(N,0); // Return N so it doesn't get rechecked!
7342       }
7343     }
7344   }
7345 
7346   if (N0.getOpcode() == ISD::SETCC) {
7347     SDValue N00 = N0.getOperand(0);
7348     SDValue N01 = N0.getOperand(1);
7349     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7350     EVT N00VT = N0.getOperand(0).getValueType();
7351 
7352     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7353     // Only do this before legalize for now.
7354     if (VT.isVector() && !LegalOperations &&
7355         TLI.getBooleanContents(N00VT) ==
7356             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7357       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7358       // of the same size as the compared operands. Only optimize sext(setcc())
7359       // if this is the case.
7360       EVT SVT = getSetCCResultType(N00VT);
7361 
7362       // We know that the # elements of the results is the same as the
7363       // # elements of the compare (and the # elements of the compare result
7364       // for that matter).  Check to see that they are the same size.  If so,
7365       // we know that the element size of the sext'd result matches the
7366       // element size of the compare operands.
7367       if (VT.getSizeInBits() == SVT.getSizeInBits())
7368         return DAG.getSetCC(DL, VT, N00, N01, CC);
7369 
7370       // If the desired elements are smaller or larger than the source
7371       // elements, we can use a matching integer vector type and then
7372       // truncate/sign extend.
7373       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7374       if (SVT == MatchingVecType) {
7375         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7376         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7377       }
7378     }
7379 
7380     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7381     // Here, T can be 1 or -1, depending on the type of the setcc and
7382     // getBooleanContents().
7383     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7384 
7385     // To determine the "true" side of the select, we need to know the high bit
7386     // of the value returned by the setcc if it evaluates to true.
7387     // If the type of the setcc is i1, then the true case of the select is just
7388     // sext(i1 1), that is, -1.
7389     // If the type of the setcc is larger (say, i8) then the value of the high
7390     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7391     // of the appropriate width.
7392     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7393                                            : TLI.getConstTrueVal(DAG, VT, DL);
7394     SDValue Zero = DAG.getConstant(0, DL, VT);
7395     if (SDValue SCC =
7396             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7397       return SCC;
7398 
7399     if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath()) {
7400       EVT SetCCVT = getSetCCResultType(N00VT);
7401       // Don't do this transform for i1 because there's a select transform
7402       // that would reverse it.
7403       // TODO: We should not do this transform at all without a target hook
7404       // because a sext is likely cheaper than a select?
7405       if (SetCCVT.getScalarSizeInBits() != 1 &&
7406           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7407         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7408         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7409       }
7410     }
7411   }
7412 
7413   // fold (sext x) -> (zext x) if the sign bit is known zero.
7414   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7415       DAG.SignBitIsZero(N0))
7416     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7417 
7418   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7419     return NewVSel;
7420 
7421   return SDValue();
7422 }
7423 
7424 // isTruncateOf - If N is a truncate of some other value, return true, record
7425 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7426 // This function computes KnownBits to avoid a duplicated call to
7427 // computeKnownBits in the caller.
7428 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7429                          KnownBits &Known) {
7430   if (N->getOpcode() == ISD::TRUNCATE) {
7431     Op = N->getOperand(0);
7432     DAG.computeKnownBits(Op, Known);
7433     return true;
7434   }
7435 
7436   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7437       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7438     return false;
7439 
7440   SDValue Op0 = N->getOperand(0);
7441   SDValue Op1 = N->getOperand(1);
7442   assert(Op0.getValueType() == Op1.getValueType());
7443 
7444   if (isNullConstant(Op0))
7445     Op = Op1;
7446   else if (isNullConstant(Op1))
7447     Op = Op0;
7448   else
7449     return false;
7450 
7451   DAG.computeKnownBits(Op, Known);
7452 
7453   if (!(Known.Zero | 1).isAllOnesValue())
7454     return false;
7455 
7456   return true;
7457 }
7458 
7459 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7460   SDValue N0 = N->getOperand(0);
7461   EVT VT = N->getValueType(0);
7462 
7463   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7464                                               LegalOperations))
7465     return SDValue(Res, 0);
7466 
7467   // fold (zext (zext x)) -> (zext x)
7468   // fold (zext (aext x)) -> (zext x)
7469   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7470     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7471                        N0.getOperand(0));
7472 
7473   // fold (zext (truncate x)) -> (zext x) or
7474   //      (zext (truncate x)) -> (truncate x)
7475   // This is valid when the truncated bits of x are already zero.
7476   // FIXME: We should extend this to work for vectors too.
7477   SDValue Op;
7478   KnownBits Known;
7479   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7480     APInt TruncatedBits =
7481       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7482       APInt(Op.getValueSizeInBits(), 0) :
7483       APInt::getBitsSet(Op.getValueSizeInBits(),
7484                         N0.getValueSizeInBits(),
7485                         std::min(Op.getValueSizeInBits(),
7486                                  VT.getSizeInBits()));
7487     if (TruncatedBits.isSubsetOf(Known.Zero))
7488       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7489   }
7490 
7491   // fold (zext (truncate (load x))) -> (zext (smaller load x))
7492   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7493   if (N0.getOpcode() == ISD::TRUNCATE) {
7494     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7495       SDNode *oye = N0.getOperand(0).getNode();
7496       if (NarrowLoad.getNode() != N0.getNode()) {
7497         CombineTo(N0.getNode(), NarrowLoad);
7498         // CombineTo deleted the truncate, if needed, but not what's under it.
7499         AddToWorklist(oye);
7500       }
7501       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7502     }
7503   }
7504 
7505   // fold (zext (truncate x)) -> (and x, mask)
7506   if (N0.getOpcode() == ISD::TRUNCATE) {
7507     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7508     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7509     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7510       SDNode *oye = N0.getOperand(0).getNode();
7511       if (NarrowLoad.getNode() != N0.getNode()) {
7512         CombineTo(N0.getNode(), NarrowLoad);
7513         // CombineTo deleted the truncate, if needed, but not what's under it.
7514         AddToWorklist(oye);
7515       }
7516       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7517     }
7518 
7519     EVT SrcVT = N0.getOperand(0).getValueType();
7520     EVT MinVT = N0.getValueType();
7521 
7522     // Try to mask before the extension to avoid having to generate a larger mask,
7523     // possibly over several sub-vectors.
7524     if (SrcVT.bitsLT(VT)) {
7525       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7526                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7527         SDValue Op = N0.getOperand(0);
7528         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7529         AddToWorklist(Op.getNode());
7530         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7531       }
7532     }
7533 
7534     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7535       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7536       AddToWorklist(Op.getNode());
7537       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7538     }
7539   }
7540 
7541   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7542   // if either of the casts is not free.
7543   if (N0.getOpcode() == ISD::AND &&
7544       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7545       N0.getOperand(1).getOpcode() == ISD::Constant &&
7546       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7547                            N0.getValueType()) ||
7548        !TLI.isZExtFree(N0.getValueType(), VT))) {
7549     SDValue X = N0.getOperand(0).getOperand(0);
7550     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7551     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7552     Mask = Mask.zext(VT.getSizeInBits());
7553     SDLoc DL(N);
7554     return DAG.getNode(ISD::AND, DL, VT,
7555                        X, DAG.getConstant(Mask, DL, VT));
7556   }
7557 
7558   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7559   // Only generate vector extloads when 1) they're legal, and 2) they are
7560   // deemed desirable by the target.
7561   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7562       ((!LegalOperations && !VT.isVector() &&
7563         !cast<LoadSDNode>(N0)->isVolatile()) ||
7564        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7565     bool DoXform = true;
7566     SmallVector<SDNode*, 4> SetCCs;
7567     if (!N0.hasOneUse())
7568       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7569     if (VT.isVector())
7570       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7571     if (DoXform) {
7572       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7573       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7574                                        LN0->getChain(),
7575                                        LN0->getBasePtr(), N0.getValueType(),
7576                                        LN0->getMemOperand());
7577 
7578       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7579                                   N0.getValueType(), ExtLoad);
7580       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7581       // If the load value is used only by N, replace it via CombineTo N.
7582       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7583       CombineTo(N, ExtLoad);
7584       if (NoReplaceTrunc)
7585         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7586       else
7587         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7588       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7589     }
7590   }
7591 
7592   // fold (zext (load x)) to multiple smaller zextloads.
7593   // Only on illegal but splittable vectors.
7594   if (SDValue ExtLoad = CombineExtLoad(N))
7595     return ExtLoad;
7596 
7597   // fold (zext (and/or/xor (load x), cst)) ->
7598   //      (and/or/xor (zextload x), (zext cst))
7599   // Unless (and (load x) cst) will match as a zextload already and has
7600   // additional users.
7601   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7602        N0.getOpcode() == ISD::XOR) &&
7603       isa<LoadSDNode>(N0.getOperand(0)) &&
7604       N0.getOperand(1).getOpcode() == ISD::Constant &&
7605       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7606       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7607     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7608     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7609       bool DoXform = true;
7610       SmallVector<SDNode*, 4> SetCCs;
7611       if (!N0.hasOneUse()) {
7612         if (N0.getOpcode() == ISD::AND) {
7613           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7614           auto NarrowLoad = false;
7615           EVT LoadResultTy = AndC->getValueType(0);
7616           EVT ExtVT, LoadedVT;
7617           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7618                                NarrowLoad))
7619             DoXform = false;
7620         }
7621         if (DoXform)
7622           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7623                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7624       }
7625       if (DoXform) {
7626         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7627                                          LN0->getChain(), LN0->getBasePtr(),
7628                                          LN0->getMemoryVT(),
7629                                          LN0->getMemOperand());
7630         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7631         Mask = Mask.zext(VT.getSizeInBits());
7632         SDLoc DL(N);
7633         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7634                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7635         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7636                                     SDLoc(N0.getOperand(0)),
7637                                     N0.getOperand(0).getValueType(), ExtLoad);
7638         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND);
7639         bool NoReplaceTruncAnd = !N0.hasOneUse();
7640         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7641         CombineTo(N, And);
7642         // If N0 has multiple uses, change other uses as well.
7643         if (NoReplaceTruncAnd) {
7644           SDValue TruncAnd =
7645               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7646           CombineTo(N0.getNode(), TruncAnd);
7647         }
7648         if (NoReplaceTrunc)
7649           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7650         else
7651           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7652         return SDValue(N,0); // Return N so it doesn't get rechecked!
7653       }
7654     }
7655   }
7656 
7657   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7658   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7659   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7660       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7661     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7662     EVT MemVT = LN0->getMemoryVT();
7663     if ((!LegalOperations && !LN0->isVolatile()) ||
7664         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7665       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7666                                        LN0->getChain(),
7667                                        LN0->getBasePtr(), MemVT,
7668                                        LN0->getMemOperand());
7669       CombineTo(N, ExtLoad);
7670       CombineTo(N0.getNode(),
7671                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7672                             ExtLoad),
7673                 ExtLoad.getValue(1));
7674       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7675     }
7676   }
7677 
7678   if (N0.getOpcode() == ISD::SETCC) {
7679     // Only do this before legalize for now.
7680     if (!LegalOperations && VT.isVector() &&
7681         N0.getValueType().getVectorElementType() == MVT::i1) {
7682       EVT N00VT = N0.getOperand(0).getValueType();
7683       if (getSetCCResultType(N00VT) == N0.getValueType())
7684         return SDValue();
7685 
7686       // We know that the # elements of the results is the same as the #
7687       // elements of the compare (and the # elements of the compare result for
7688       // that matter). Check to see that they are the same size. If so, we know
7689       // that the element size of the sext'd result matches the element size of
7690       // the compare operands.
7691       SDLoc DL(N);
7692       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7693       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7694         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7695         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7696                                      N0.getOperand(1), N0.getOperand(2));
7697         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7698       }
7699 
7700       // If the desired elements are smaller or larger than the source
7701       // elements we can use a matching integer vector type and then
7702       // truncate/sign extend.
7703       EVT MatchingElementType = EVT::getIntegerVT(
7704           *DAG.getContext(), N00VT.getScalarSizeInBits());
7705       EVT MatchingVectorType = EVT::getVectorVT(
7706           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7707       SDValue VsetCC =
7708           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7709                       N0.getOperand(1), N0.getOperand(2));
7710       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7711                          VecOnes);
7712     }
7713 
7714     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7715     SDLoc DL(N);
7716     if (SDValue SCC = SimplifySelectCC(
7717             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7718             DAG.getConstant(0, DL, VT),
7719             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7720       return SCC;
7721   }
7722 
7723   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7724   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7725       isa<ConstantSDNode>(N0.getOperand(1)) &&
7726       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7727       N0.hasOneUse()) {
7728     SDValue ShAmt = N0.getOperand(1);
7729     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7730     if (N0.getOpcode() == ISD::SHL) {
7731       SDValue InnerZExt = N0.getOperand(0);
7732       // If the original shl may be shifting out bits, do not perform this
7733       // transformation.
7734       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7735         InnerZExt.getOperand(0).getValueSizeInBits();
7736       if (ShAmtVal > KnownZeroBits)
7737         return SDValue();
7738     }
7739 
7740     SDLoc DL(N);
7741 
7742     // Ensure that the shift amount is wide enough for the shifted value.
7743     if (VT.getSizeInBits() >= 256)
7744       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7745 
7746     return DAG.getNode(N0.getOpcode(), DL, VT,
7747                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7748                        ShAmt);
7749   }
7750 
7751   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7752     return NewVSel;
7753 
7754   return SDValue();
7755 }
7756 
7757 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7758   SDValue N0 = N->getOperand(0);
7759   EVT VT = N->getValueType(0);
7760 
7761   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7762                                               LegalOperations))
7763     return SDValue(Res, 0);
7764 
7765   // fold (aext (aext x)) -> (aext x)
7766   // fold (aext (zext x)) -> (zext x)
7767   // fold (aext (sext x)) -> (sext x)
7768   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7769       N0.getOpcode() == ISD::ZERO_EXTEND ||
7770       N0.getOpcode() == ISD::SIGN_EXTEND)
7771     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7772 
7773   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7774   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7775   if (N0.getOpcode() == ISD::TRUNCATE) {
7776     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7777       SDNode *oye = N0.getOperand(0).getNode();
7778       if (NarrowLoad.getNode() != N0.getNode()) {
7779         CombineTo(N0.getNode(), NarrowLoad);
7780         // CombineTo deleted the truncate, if needed, but not what's under it.
7781         AddToWorklist(oye);
7782       }
7783       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7784     }
7785   }
7786 
7787   // fold (aext (truncate x))
7788   if (N0.getOpcode() == ISD::TRUNCATE)
7789     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7790 
7791   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7792   // if the trunc is not free.
7793   if (N0.getOpcode() == ISD::AND &&
7794       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7795       N0.getOperand(1).getOpcode() == ISD::Constant &&
7796       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7797                           N0.getValueType())) {
7798     SDLoc DL(N);
7799     SDValue X = N0.getOperand(0).getOperand(0);
7800     X = DAG.getAnyExtOrTrunc(X, DL, VT);
7801     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7802     Mask = Mask.zext(VT.getSizeInBits());
7803     return DAG.getNode(ISD::AND, DL, VT,
7804                        X, DAG.getConstant(Mask, DL, VT));
7805   }
7806 
7807   // fold (aext (load x)) -> (aext (truncate (extload x)))
7808   // None of the supported targets knows how to perform load and any_ext
7809   // on vectors in one instruction.  We only perform this transformation on
7810   // scalars.
7811   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7812       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7813       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7814     bool DoXform = true;
7815     SmallVector<SDNode*, 4> SetCCs;
7816     if (!N0.hasOneUse())
7817       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7818     if (DoXform) {
7819       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7820       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7821                                        LN0->getChain(),
7822                                        LN0->getBasePtr(), N0.getValueType(),
7823                                        LN0->getMemOperand());
7824       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7825                                   N0.getValueType(), ExtLoad);
7826       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7827                       ISD::ANY_EXTEND);
7828       // If the load value is used only by N, replace it via CombineTo N.
7829       bool NoReplaceTrunc = N0.hasOneUse();
7830       CombineTo(N, ExtLoad);
7831       if (NoReplaceTrunc)
7832         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7833       else
7834         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7835       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7836     }
7837   }
7838 
7839   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7840   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7841   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7842   if (N0.getOpcode() == ISD::LOAD &&
7843       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7844       N0.hasOneUse()) {
7845     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7846     ISD::LoadExtType ExtType = LN0->getExtensionType();
7847     EVT MemVT = LN0->getMemoryVT();
7848     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7849       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7850                                        VT, LN0->getChain(), LN0->getBasePtr(),
7851                                        MemVT, LN0->getMemOperand());
7852       CombineTo(N, ExtLoad);
7853       CombineTo(N0.getNode(),
7854                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7855                             N0.getValueType(), ExtLoad),
7856                 ExtLoad.getValue(1));
7857       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7858     }
7859   }
7860 
7861   if (N0.getOpcode() == ISD::SETCC) {
7862     // For vectors:
7863     // aext(setcc) -> vsetcc
7864     // aext(setcc) -> truncate(vsetcc)
7865     // aext(setcc) -> aext(vsetcc)
7866     // Only do this before legalize for now.
7867     if (VT.isVector() && !LegalOperations) {
7868       EVT N0VT = N0.getOperand(0).getValueType();
7869         // We know that the # elements of the results is the same as the
7870         // # elements of the compare (and the # elements of the compare result
7871         // for that matter).  Check to see that they are the same size.  If so,
7872         // we know that the element size of the sext'd result matches the
7873         // element size of the compare operands.
7874       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7875         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7876                              N0.getOperand(1),
7877                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7878       // If the desired elements are smaller or larger than the source
7879       // elements we can use a matching integer vector type and then
7880       // truncate/any extend
7881       else {
7882         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7883         SDValue VsetCC =
7884           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7885                         N0.getOperand(1),
7886                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7887         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7888       }
7889     }
7890 
7891     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7892     SDLoc DL(N);
7893     if (SDValue SCC = SimplifySelectCC(
7894             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7895             DAG.getConstant(0, DL, VT),
7896             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7897       return SCC;
7898   }
7899 
7900   return SDValue();
7901 }
7902 
7903 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7904   SDValue N0 = N->getOperand(0);
7905   SDValue N1 = N->getOperand(1);
7906   EVT EVT = cast<VTSDNode>(N1)->getVT();
7907 
7908   // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7909   if (N0.getOpcode() == ISD::AssertZext &&
7910       EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7911     return N0;
7912 
7913   return SDValue();
7914 }
7915 
7916 /// If the result of a wider load is shifted to right of N  bits and then
7917 /// truncated to a narrower type and where N is a multiple of number of bits of
7918 /// the narrower type, transform it to a narrower load from address + N / num of
7919 /// bits of new type. If the result is to be extended, also fold the extension
7920 /// to form a extending load.
7921 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7922   unsigned Opc = N->getOpcode();
7923 
7924   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7925   SDValue N0 = N->getOperand(0);
7926   EVT VT = N->getValueType(0);
7927   EVT ExtVT = VT;
7928 
7929   // This transformation isn't valid for vector loads.
7930   if (VT.isVector())
7931     return SDValue();
7932 
7933   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7934   // extended to VT.
7935   if (Opc == ISD::SIGN_EXTEND_INREG) {
7936     ExtType = ISD::SEXTLOAD;
7937     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7938   } else if (Opc == ISD::SRL) {
7939     // Another special-case: SRL is basically zero-extending a narrower value.
7940     ExtType = ISD::ZEXTLOAD;
7941     N0 = SDValue(N, 0);
7942     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7943     if (!N01) return SDValue();
7944     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7945                               VT.getSizeInBits() - N01->getZExtValue());
7946   }
7947   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7948     return SDValue();
7949 
7950   unsigned EVTBits = ExtVT.getSizeInBits();
7951 
7952   // Do not generate loads of non-round integer types since these can
7953   // be expensive (and would be wrong if the type is not byte sized).
7954   if (!ExtVT.isRound())
7955     return SDValue();
7956 
7957   unsigned ShAmt = 0;
7958   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7959     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7960       ShAmt = N01->getZExtValue();
7961       // Is the shift amount a multiple of size of VT?
7962       if ((ShAmt & (EVTBits-1)) == 0) {
7963         N0 = N0.getOperand(0);
7964         // Is the load width a multiple of size of VT?
7965         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7966           return SDValue();
7967       }
7968 
7969       // At this point, we must have a load or else we can't do the transform.
7970       if (!isa<LoadSDNode>(N0)) return SDValue();
7971 
7972       // Because a SRL must be assumed to *need* to zero-extend the high bits
7973       // (as opposed to anyext the high bits), we can't combine the zextload
7974       // lowering of SRL and an sextload.
7975       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7976         return SDValue();
7977 
7978       // If the shift amount is larger than the input type then we're not
7979       // accessing any of the loaded bytes.  If the load was a zextload/extload
7980       // then the result of the shift+trunc is zero/undef (handled elsewhere).
7981       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7982         return SDValue();
7983     }
7984   }
7985 
7986   // If the load is shifted left (and the result isn't shifted back right),
7987   // we can fold the truncate through the shift.
7988   unsigned ShLeftAmt = 0;
7989   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7990       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7991     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7992       ShLeftAmt = N01->getZExtValue();
7993       N0 = N0.getOperand(0);
7994     }
7995   }
7996 
7997   // If we haven't found a load, we can't narrow it.  Don't transform one with
7998   // multiple uses, this would require adding a new load.
7999   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
8000     return SDValue();
8001 
8002   // Don't change the width of a volatile load.
8003   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8004   if (LN0->isVolatile())
8005     return SDValue();
8006 
8007   // Verify that we are actually reducing a load width here.
8008   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
8009     return SDValue();
8010 
8011   // For the transform to be legal, the load must produce only two values
8012   // (the value loaded and the chain).  Don't transform a pre-increment
8013   // load, for example, which produces an extra value.  Otherwise the
8014   // transformation is not equivalent, and the downstream logic to replace
8015   // uses gets things wrong.
8016   if (LN0->getNumValues() > 2)
8017     return SDValue();
8018 
8019   // If the load that we're shrinking is an extload and we're not just
8020   // discarding the extension we can't simply shrink the load. Bail.
8021   // TODO: It would be possible to merge the extensions in some cases.
8022   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
8023       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
8024     return SDValue();
8025 
8026   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
8027     return SDValue();
8028 
8029   EVT PtrType = N0.getOperand(1).getValueType();
8030 
8031   if (PtrType == MVT::Untyped || PtrType.isExtended())
8032     // It's not possible to generate a constant of extended or untyped type.
8033     return SDValue();
8034 
8035   // For big endian targets, we need to adjust the offset to the pointer to
8036   // load the correct bytes.
8037   if (DAG.getDataLayout().isBigEndian()) {
8038     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
8039     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
8040     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
8041   }
8042 
8043   uint64_t PtrOff = ShAmt / 8;
8044   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8045   SDLoc DL(LN0);
8046   // The original load itself didn't wrap, so an offset within it doesn't.
8047   SDNodeFlags Flags;
8048   Flags.setNoUnsignedWrap(true);
8049   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8050                                PtrType, LN0->getBasePtr(),
8051                                DAG.getConstant(PtrOff, DL, PtrType),
8052                                Flags);
8053   AddToWorklist(NewPtr.getNode());
8054 
8055   SDValue Load;
8056   if (ExtType == ISD::NON_EXTLOAD)
8057     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8058                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8059                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8060   else
8061     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8062                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8063                           NewAlign, LN0->getMemOperand()->getFlags(),
8064                           LN0->getAAInfo());
8065 
8066   // Replace the old load's chain with the new load's chain.
8067   WorklistRemover DeadNodes(*this);
8068   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8069 
8070   // Shift the result left, if we've swallowed a left shift.
8071   SDValue Result = Load;
8072   if (ShLeftAmt != 0) {
8073     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8074     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8075       ShImmTy = VT;
8076     // If the shift amount is as large as the result size (but, presumably,
8077     // no larger than the source) then the useful bits of the result are
8078     // zero; we can't simply return the shortened shift, because the result
8079     // of that operation is undefined.
8080     SDLoc DL(N0);
8081     if (ShLeftAmt >= VT.getSizeInBits())
8082       Result = DAG.getConstant(0, DL, VT);
8083     else
8084       Result = DAG.getNode(ISD::SHL, DL, VT,
8085                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8086   }
8087 
8088   // Return the new loaded value.
8089   return Result;
8090 }
8091 
8092 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8093   SDValue N0 = N->getOperand(0);
8094   SDValue N1 = N->getOperand(1);
8095   EVT VT = N->getValueType(0);
8096   EVT EVT = cast<VTSDNode>(N1)->getVT();
8097   unsigned VTBits = VT.getScalarSizeInBits();
8098   unsigned EVTBits = EVT.getScalarSizeInBits();
8099 
8100   if (N0.isUndef())
8101     return DAG.getUNDEF(VT);
8102 
8103   // fold (sext_in_reg c1) -> c1
8104   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8105     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8106 
8107   // If the input is already sign extended, just drop the extension.
8108   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8109     return N0;
8110 
8111   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8112   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8113       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8114     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8115                        N0.getOperand(0), N1);
8116 
8117   // fold (sext_in_reg (sext x)) -> (sext x)
8118   // fold (sext_in_reg (aext x)) -> (sext x)
8119   // if x is small enough.
8120   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8121     SDValue N00 = N0.getOperand(0);
8122     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8123         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8124       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8125   }
8126 
8127   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8128   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8129        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8130        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8131       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8132     if (!LegalOperations ||
8133         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8134       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8135   }
8136 
8137   // fold (sext_in_reg (zext x)) -> (sext x)
8138   // iff we are extending the source sign bit.
8139   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8140     SDValue N00 = N0.getOperand(0);
8141     if (N00.getScalarValueSizeInBits() == EVTBits &&
8142         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8143       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8144   }
8145 
8146   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8147   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8148     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8149 
8150   // fold operands of sext_in_reg based on knowledge that the top bits are not
8151   // demanded.
8152   if (SimplifyDemandedBits(SDValue(N, 0)))
8153     return SDValue(N, 0);
8154 
8155   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8156   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8157   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8158     return NarrowLoad;
8159 
8160   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8161   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8162   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8163   if (N0.getOpcode() == ISD::SRL) {
8164     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8165       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8166         // We can turn this into an SRA iff the input to the SRL is already sign
8167         // extended enough.
8168         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8169         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8170           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8171                              N0.getOperand(0), N0.getOperand(1));
8172       }
8173   }
8174 
8175   // fold (sext_inreg (extload x)) -> (sextload x)
8176   if (ISD::isEXTLoad(N0.getNode()) &&
8177       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8178       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8179       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8180        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8181     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8182     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8183                                      LN0->getChain(),
8184                                      LN0->getBasePtr(), EVT,
8185                                      LN0->getMemOperand());
8186     CombineTo(N, ExtLoad);
8187     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8188     AddToWorklist(ExtLoad.getNode());
8189     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8190   }
8191   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8192   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8193       N0.hasOneUse() &&
8194       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8195       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8196        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8197     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8198     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8199                                      LN0->getChain(),
8200                                      LN0->getBasePtr(), EVT,
8201                                      LN0->getMemOperand());
8202     CombineTo(N, ExtLoad);
8203     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8204     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8205   }
8206 
8207   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8208   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8209     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8210                                            N0.getOperand(1), false))
8211       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8212                          BSwap, N1);
8213   }
8214 
8215   return SDValue();
8216 }
8217 
8218 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8219   SDValue N0 = N->getOperand(0);
8220   EVT VT = N->getValueType(0);
8221 
8222   if (N0.isUndef())
8223     return DAG.getUNDEF(VT);
8224 
8225   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8226                                               LegalOperations))
8227     return SDValue(Res, 0);
8228 
8229   return SDValue();
8230 }
8231 
8232 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8233   SDValue N0 = N->getOperand(0);
8234   EVT VT = N->getValueType(0);
8235 
8236   if (N0.isUndef())
8237     return DAG.getUNDEF(VT);
8238 
8239   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8240                                               LegalOperations))
8241     return SDValue(Res, 0);
8242 
8243   return SDValue();
8244 }
8245 
8246 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8247   SDValue N0 = N->getOperand(0);
8248   EVT VT = N->getValueType(0);
8249   bool isLE = DAG.getDataLayout().isLittleEndian();
8250 
8251   // noop truncate
8252   if (N0.getValueType() == N->getValueType(0))
8253     return N0;
8254   // fold (truncate c1) -> c1
8255   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8256     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8257   // fold (truncate (truncate x)) -> (truncate x)
8258   if (N0.getOpcode() == ISD::TRUNCATE)
8259     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8260   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8261   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8262       N0.getOpcode() == ISD::SIGN_EXTEND ||
8263       N0.getOpcode() == ISD::ANY_EXTEND) {
8264     // if the source is smaller than the dest, we still need an extend.
8265     if (N0.getOperand(0).getValueType().bitsLT(VT))
8266       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8267     // if the source is larger than the dest, than we just need the truncate.
8268     if (N0.getOperand(0).getValueType().bitsGT(VT))
8269       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8270     // if the source and dest are the same type, we can drop both the extend
8271     // and the truncate.
8272     return N0.getOperand(0);
8273   }
8274 
8275   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8276   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8277     return SDValue();
8278 
8279   // Fold extract-and-trunc into a narrow extract. For example:
8280   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8281   //   i32 y = TRUNCATE(i64 x)
8282   //        -- becomes --
8283   //   v16i8 b = BITCAST (v2i64 val)
8284   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8285   //
8286   // Note: We only run this optimization after type legalization (which often
8287   // creates this pattern) and before operation legalization after which
8288   // we need to be more careful about the vector instructions that we generate.
8289   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8290       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8291 
8292     EVT VecTy = N0.getOperand(0).getValueType();
8293     EVT ExTy = N0.getValueType();
8294     EVT TrTy = N->getValueType(0);
8295 
8296     unsigned NumElem = VecTy.getVectorNumElements();
8297     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8298 
8299     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8300     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8301 
8302     SDValue EltNo = N0->getOperand(1);
8303     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8304       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8305       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8306       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8307 
8308       SDLoc DL(N);
8309       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8310                          DAG.getBitcast(NVT, N0.getOperand(0)),
8311                          DAG.getConstant(Index, DL, IndexTy));
8312     }
8313   }
8314 
8315   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8316   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8317     EVT SrcVT = N0.getValueType();
8318     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8319         TLI.isTruncateFree(SrcVT, VT)) {
8320       SDLoc SL(N0);
8321       SDValue Cond = N0.getOperand(0);
8322       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8323       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8324       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8325     }
8326   }
8327 
8328   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8329   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8330       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8331       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8332     SDValue Amt = N0.getOperand(1);
8333     KnownBits Known;
8334     DAG.computeKnownBits(Amt, Known);
8335     unsigned Size = VT.getScalarSizeInBits();
8336     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8337       SDLoc SL(N);
8338       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8339 
8340       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8341       if (AmtVT != Amt.getValueType()) {
8342         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8343         AddToWorklist(Amt.getNode());
8344       }
8345       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8346     }
8347   }
8348 
8349   // Fold a series of buildvector, bitcast, and truncate if possible.
8350   // For example fold
8351   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8352   //   (2xi32 (buildvector x, y)).
8353   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8354       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8355       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8356       N0.getOperand(0).hasOneUse()) {
8357 
8358     SDValue BuildVect = N0.getOperand(0);
8359     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8360     EVT TruncVecEltTy = VT.getVectorElementType();
8361 
8362     // Check that the element types match.
8363     if (BuildVectEltTy == TruncVecEltTy) {
8364       // Now we only need to compute the offset of the truncated elements.
8365       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8366       unsigned TruncVecNumElts = VT.getVectorNumElements();
8367       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8368 
8369       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8370              "Invalid number of elements");
8371 
8372       SmallVector<SDValue, 8> Opnds;
8373       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8374         Opnds.push_back(BuildVect.getOperand(i));
8375 
8376       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8377     }
8378   }
8379 
8380   // See if we can simplify the input to this truncate through knowledge that
8381   // only the low bits are being used.
8382   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8383   // Currently we only perform this optimization on scalars because vectors
8384   // may have different active low bits.
8385   if (!VT.isVector()) {
8386     APInt Mask =
8387         APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
8388     if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
8389       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8390   }
8391 
8392   // fold (truncate (load x)) -> (smaller load x)
8393   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8394   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8395     if (SDValue Reduced = ReduceLoadWidth(N))
8396       return Reduced;
8397 
8398     // Handle the case where the load remains an extending load even
8399     // after truncation.
8400     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8401       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8402       if (!LN0->isVolatile() &&
8403           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8404         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8405                                          VT, LN0->getChain(), LN0->getBasePtr(),
8406                                          LN0->getMemoryVT(),
8407                                          LN0->getMemOperand());
8408         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8409         return NewLoad;
8410       }
8411     }
8412   }
8413 
8414   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8415   // where ... are all 'undef'.
8416   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8417     SmallVector<EVT, 8> VTs;
8418     SDValue V;
8419     unsigned Idx = 0;
8420     unsigned NumDefs = 0;
8421 
8422     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8423       SDValue X = N0.getOperand(i);
8424       if (!X.isUndef()) {
8425         V = X;
8426         Idx = i;
8427         NumDefs++;
8428       }
8429       // Stop if more than one members are non-undef.
8430       if (NumDefs > 1)
8431         break;
8432       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8433                                      VT.getVectorElementType(),
8434                                      X.getValueType().getVectorNumElements()));
8435     }
8436 
8437     if (NumDefs == 0)
8438       return DAG.getUNDEF(VT);
8439 
8440     if (NumDefs == 1) {
8441       assert(V.getNode() && "The single defined operand is empty!");
8442       SmallVector<SDValue, 8> Opnds;
8443       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8444         if (i != Idx) {
8445           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8446           continue;
8447         }
8448         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8449         AddToWorklist(NV.getNode());
8450         Opnds.push_back(NV);
8451       }
8452       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8453     }
8454   }
8455 
8456   // Fold truncate of a bitcast of a vector to an extract of the low vector
8457   // element.
8458   //
8459   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
8460   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8461     SDValue VecSrc = N0.getOperand(0);
8462     EVT SrcVT = VecSrc.getValueType();
8463     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8464         (!LegalOperations ||
8465          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8466       SDLoc SL(N);
8467 
8468       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8469       unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1;
8470       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8471                          VecSrc, DAG.getConstant(Idx, SL, IdxVT));
8472     }
8473   }
8474 
8475   // Simplify the operands using demanded-bits information.
8476   if (!VT.isVector() &&
8477       SimplifyDemandedBits(SDValue(N, 0)))
8478     return SDValue(N, 0);
8479 
8480   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8481   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8482   // When the adde's carry is not used.
8483   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8484       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8485       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8486     SDLoc SL(N);
8487     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8488     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8489     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8490     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8491   }
8492 
8493   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8494     return NewVSel;
8495 
8496   return SDValue();
8497 }
8498 
8499 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8500   SDValue Elt = N->getOperand(i);
8501   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8502     return Elt.getNode();
8503   return Elt.getOperand(Elt.getResNo()).getNode();
8504 }
8505 
8506 /// build_pair (load, load) -> load
8507 /// if load locations are consecutive.
8508 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8509   assert(N->getOpcode() == ISD::BUILD_PAIR);
8510 
8511   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8512   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8513   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8514       LD1->getAddressSpace() != LD2->getAddressSpace())
8515     return SDValue();
8516   EVT LD1VT = LD1->getValueType(0);
8517   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8518   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8519       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8520     unsigned Align = LD1->getAlignment();
8521     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8522         VT.getTypeForEVT(*DAG.getContext()));
8523 
8524     if (NewAlign <= Align &&
8525         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8526       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8527                          LD1->getPointerInfo(), Align);
8528   }
8529 
8530   return SDValue();
8531 }
8532 
8533 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8534   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8535   // and Lo parts; on big-endian machines it doesn't.
8536   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8537 }
8538 
8539 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8540                                     const TargetLowering &TLI) {
8541   // If this is not a bitcast to an FP type or if the target doesn't have
8542   // IEEE754-compliant FP logic, we're done.
8543   EVT VT = N->getValueType(0);
8544   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8545     return SDValue();
8546 
8547   // TODO: Use splat values for the constant-checking below and remove this
8548   // restriction.
8549   SDValue N0 = N->getOperand(0);
8550   EVT SourceVT = N0.getValueType();
8551   if (SourceVT.isVector())
8552     return SDValue();
8553 
8554   unsigned FPOpcode;
8555   APInt SignMask;
8556   switch (N0.getOpcode()) {
8557   case ISD::AND:
8558     FPOpcode = ISD::FABS;
8559     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8560     break;
8561   case ISD::XOR:
8562     FPOpcode = ISD::FNEG;
8563     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8564     break;
8565   // TODO: ISD::OR --> ISD::FNABS?
8566   default:
8567     return SDValue();
8568   }
8569 
8570   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8571   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8572   SDValue LogicOp0 = N0.getOperand(0);
8573   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8574   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8575       LogicOp0.getOpcode() == ISD::BITCAST &&
8576       LogicOp0->getOperand(0).getValueType() == VT)
8577     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8578 
8579   return SDValue();
8580 }
8581 
8582 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8583   SDValue N0 = N->getOperand(0);
8584   EVT VT = N->getValueType(0);
8585 
8586   if (N0.isUndef())
8587     return DAG.getUNDEF(VT);
8588 
8589   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8590   // Only do this before legalize, since afterward the target may be depending
8591   // on the bitconvert.
8592   // First check to see if this is all constant.
8593   if (!LegalTypes &&
8594       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8595       VT.isVector()) {
8596     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8597 
8598     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8599     assert(!DestEltVT.isVector() &&
8600            "Element type of vector ValueType must not be vector!");
8601     if (isSimple)
8602       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8603   }
8604 
8605   // If the input is a constant, let getNode fold it.
8606   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8607     // If we can't allow illegal operations, we need to check that this is just
8608     // a fp -> int or int -> conversion and that the resulting operation will
8609     // be legal.
8610     if (!LegalOperations ||
8611         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8612          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8613         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8614          TLI.isOperationLegal(ISD::Constant, VT)))
8615       return DAG.getBitcast(VT, N0);
8616   }
8617 
8618   // (conv (conv x, t1), t2) -> (conv x, t2)
8619   if (N0.getOpcode() == ISD::BITCAST)
8620     return DAG.getBitcast(VT, N0.getOperand(0));
8621 
8622   // fold (conv (load x)) -> (load (conv*)x)
8623   // If the resultant load doesn't need a higher alignment than the original!
8624   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8625       // Do not change the width of a volatile load.
8626       !cast<LoadSDNode>(N0)->isVolatile() &&
8627       // Do not remove the cast if the types differ in endian layout.
8628       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8629           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8630       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8631       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8632     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8633     unsigned OrigAlign = LN0->getAlignment();
8634 
8635     bool Fast = false;
8636     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8637                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8638         Fast) {
8639       SDValue Load =
8640           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8641                       LN0->getPointerInfo(), OrigAlign,
8642                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8643       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8644       return Load;
8645     }
8646   }
8647 
8648   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8649     return V;
8650 
8651   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8652   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8653   //
8654   // For ppc_fp128:
8655   // fold (bitcast (fneg x)) ->
8656   //     flipbit = signbit
8657   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8658   //
8659   // fold (bitcast (fabs x)) ->
8660   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8661   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8662   // This often reduces constant pool loads.
8663   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8664        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8665       N0.getNode()->hasOneUse() && VT.isInteger() &&
8666       !VT.isVector() && !N0.getValueType().isVector()) {
8667     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8668     AddToWorklist(NewConv.getNode());
8669 
8670     SDLoc DL(N);
8671     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8672       assert(VT.getSizeInBits() == 128);
8673       SDValue SignBit = DAG.getConstant(
8674           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8675       SDValue FlipBit;
8676       if (N0.getOpcode() == ISD::FNEG) {
8677         FlipBit = SignBit;
8678         AddToWorklist(FlipBit.getNode());
8679       } else {
8680         assert(N0.getOpcode() == ISD::FABS);
8681         SDValue Hi =
8682             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8683                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8684                                               SDLoc(NewConv)));
8685         AddToWorklist(Hi.getNode());
8686         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8687         AddToWorklist(FlipBit.getNode());
8688       }
8689       SDValue FlipBits =
8690           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8691       AddToWorklist(FlipBits.getNode());
8692       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8693     }
8694     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8695     if (N0.getOpcode() == ISD::FNEG)
8696       return DAG.getNode(ISD::XOR, DL, VT,
8697                          NewConv, DAG.getConstant(SignBit, DL, VT));
8698     assert(N0.getOpcode() == ISD::FABS);
8699     return DAG.getNode(ISD::AND, DL, VT,
8700                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8701   }
8702 
8703   // fold (bitconvert (fcopysign cst, x)) ->
8704   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8705   // Note that we don't handle (copysign x, cst) because this can always be
8706   // folded to an fneg or fabs.
8707   //
8708   // For ppc_fp128:
8709   // fold (bitcast (fcopysign cst, x)) ->
8710   //     flipbit = (and (extract_element
8711   //                     (xor (bitcast cst), (bitcast x)), 0),
8712   //                    signbit)
8713   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8714   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8715       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8716       VT.isInteger() && !VT.isVector()) {
8717     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8718     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8719     if (isTypeLegal(IntXVT)) {
8720       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8721       AddToWorklist(X.getNode());
8722 
8723       // If X has a different width than the result/lhs, sext it or truncate it.
8724       unsigned VTWidth = VT.getSizeInBits();
8725       if (OrigXWidth < VTWidth) {
8726         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8727         AddToWorklist(X.getNode());
8728       } else if (OrigXWidth > VTWidth) {
8729         // To get the sign bit in the right place, we have to shift it right
8730         // before truncating.
8731         SDLoc DL(X);
8732         X = DAG.getNode(ISD::SRL, DL,
8733                         X.getValueType(), X,
8734                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8735                                         X.getValueType()));
8736         AddToWorklist(X.getNode());
8737         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8738         AddToWorklist(X.getNode());
8739       }
8740 
8741       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8742         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8743         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8744         AddToWorklist(Cst.getNode());
8745         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8746         AddToWorklist(X.getNode());
8747         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8748         AddToWorklist(XorResult.getNode());
8749         SDValue XorResult64 = DAG.getNode(
8750             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8751             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8752                                   SDLoc(XorResult)));
8753         AddToWorklist(XorResult64.getNode());
8754         SDValue FlipBit =
8755             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8756                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8757         AddToWorklist(FlipBit.getNode());
8758         SDValue FlipBits =
8759             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8760         AddToWorklist(FlipBits.getNode());
8761         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8762       }
8763       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8764       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8765                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8766       AddToWorklist(X.getNode());
8767 
8768       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8769       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8770                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8771       AddToWorklist(Cst.getNode());
8772 
8773       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8774     }
8775   }
8776 
8777   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8778   if (N0.getOpcode() == ISD::BUILD_PAIR)
8779     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8780       return CombineLD;
8781 
8782   // Remove double bitcasts from shuffles - this is often a legacy of
8783   // XformToShuffleWithZero being used to combine bitmaskings (of
8784   // float vectors bitcast to integer vectors) into shuffles.
8785   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8786   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8787       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8788       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8789       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8790     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8791 
8792     // If operands are a bitcast, peek through if it casts the original VT.
8793     // If operands are a constant, just bitcast back to original VT.
8794     auto PeekThroughBitcast = [&](SDValue Op) {
8795       if (Op.getOpcode() == ISD::BITCAST &&
8796           Op.getOperand(0).getValueType() == VT)
8797         return SDValue(Op.getOperand(0));
8798       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8799           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8800         return DAG.getBitcast(VT, Op);
8801       return SDValue();
8802     };
8803 
8804     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8805     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8806     if (!(SV0 && SV1))
8807       return SDValue();
8808 
8809     int MaskScale =
8810         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8811     SmallVector<int, 8> NewMask;
8812     for (int M : SVN->getMask())
8813       for (int i = 0; i != MaskScale; ++i)
8814         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8815 
8816     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8817     if (!LegalMask) {
8818       std::swap(SV0, SV1);
8819       ShuffleVectorSDNode::commuteMask(NewMask);
8820       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8821     }
8822 
8823     if (LegalMask)
8824       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8825   }
8826 
8827   return SDValue();
8828 }
8829 
8830 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8831   EVT VT = N->getValueType(0);
8832   return CombineConsecutiveLoads(N, VT);
8833 }
8834 
8835 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8836 /// operands. DstEltVT indicates the destination element value type.
8837 SDValue DAGCombiner::
8838 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8839   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8840 
8841   // If this is already the right type, we're done.
8842   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8843 
8844   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8845   unsigned DstBitSize = DstEltVT.getSizeInBits();
8846 
8847   // If this is a conversion of N elements of one type to N elements of another
8848   // type, convert each element.  This handles FP<->INT cases.
8849   if (SrcBitSize == DstBitSize) {
8850     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8851                               BV->getValueType(0).getVectorNumElements());
8852 
8853     // Due to the FP element handling below calling this routine recursively,
8854     // we can end up with a scalar-to-vector node here.
8855     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8856       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8857                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8858 
8859     SmallVector<SDValue, 8> Ops;
8860     for (SDValue Op : BV->op_values()) {
8861       // If the vector element type is not legal, the BUILD_VECTOR operands
8862       // are promoted and implicitly truncated.  Make that explicit here.
8863       if (Op.getValueType() != SrcEltVT)
8864         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8865       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8866       AddToWorklist(Ops.back().getNode());
8867     }
8868     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8869   }
8870 
8871   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8872   // handle annoying details of growing/shrinking FP values, we convert them to
8873   // int first.
8874   if (SrcEltVT.isFloatingPoint()) {
8875     // Convert the input float vector to a int vector where the elements are the
8876     // same sizes.
8877     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8878     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8879     SrcEltVT = IntVT;
8880   }
8881 
8882   // Now we know the input is an integer vector.  If the output is a FP type,
8883   // convert to integer first, then to FP of the right size.
8884   if (DstEltVT.isFloatingPoint()) {
8885     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8886     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8887 
8888     // Next, convert to FP elements of the same size.
8889     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8890   }
8891 
8892   SDLoc DL(BV);
8893 
8894   // Okay, we know the src/dst types are both integers of differing types.
8895   // Handling growing first.
8896   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8897   if (SrcBitSize < DstBitSize) {
8898     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8899 
8900     SmallVector<SDValue, 8> Ops;
8901     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8902          i += NumInputsPerOutput) {
8903       bool isLE = DAG.getDataLayout().isLittleEndian();
8904       APInt NewBits = APInt(DstBitSize, 0);
8905       bool EltIsUndef = true;
8906       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8907         // Shift the previously computed bits over.
8908         NewBits <<= SrcBitSize;
8909         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8910         if (Op.isUndef()) continue;
8911         EltIsUndef = false;
8912 
8913         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8914                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
8915       }
8916 
8917       if (EltIsUndef)
8918         Ops.push_back(DAG.getUNDEF(DstEltVT));
8919       else
8920         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8921     }
8922 
8923     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8924     return DAG.getBuildVector(VT, DL, Ops);
8925   }
8926 
8927   // Finally, this must be the case where we are shrinking elements: each input
8928   // turns into multiple outputs.
8929   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8930   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8931                             NumOutputsPerInput*BV->getNumOperands());
8932   SmallVector<SDValue, 8> Ops;
8933 
8934   for (const SDValue &Op : BV->op_values()) {
8935     if (Op.isUndef()) {
8936       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8937       continue;
8938     }
8939 
8940     APInt OpVal = cast<ConstantSDNode>(Op)->
8941                   getAPIntValue().zextOrTrunc(SrcBitSize);
8942 
8943     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8944       APInt ThisVal = OpVal.trunc(DstBitSize);
8945       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8946       OpVal.lshrInPlace(DstBitSize);
8947     }
8948 
8949     // For big endian targets, swap the order of the pieces of each element.
8950     if (DAG.getDataLayout().isBigEndian())
8951       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8952   }
8953 
8954   return DAG.getBuildVector(VT, DL, Ops);
8955 }
8956 
8957 static bool isContractable(SDNode *N) {
8958   SDNodeFlags F = N->getFlags();
8959   return F.hasAllowContract() || F.hasUnsafeAlgebra();
8960 }
8961 
8962 /// Try to perform FMA combining on a given FADD node.
8963 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8964   SDValue N0 = N->getOperand(0);
8965   SDValue N1 = N->getOperand(1);
8966   EVT VT = N->getValueType(0);
8967   SDLoc SL(N);
8968 
8969   const TargetOptions &Options = DAG.getTarget().Options;
8970 
8971   // Floating-point multiply-add with intermediate rounding.
8972   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8973 
8974   // Floating-point multiply-add without intermediate rounding.
8975   bool HasFMA =
8976       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8977       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8978 
8979   // No valid opcode, do not combine.
8980   if (!HasFMAD && !HasFMA)
8981     return SDValue();
8982 
8983   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8984                               Options.UnsafeFPMath || HasFMAD);
8985   // If the addition is not contractable, do not combine.
8986   if (!AllowFusionGlobally && !isContractable(N))
8987     return SDValue();
8988 
8989   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8990   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8991     return SDValue();
8992 
8993   // Always prefer FMAD to FMA for precision.
8994   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8995   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8996   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8997 
8998   // Is the node an FMUL and contractable either due to global flags or
8999   // SDNodeFlags.
9000   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9001     if (N.getOpcode() != ISD::FMUL)
9002       return false;
9003     return AllowFusionGlobally || isContractable(N.getNode());
9004   };
9005   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
9006   // prefer to fold the multiply with fewer uses.
9007   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
9008     if (N0.getNode()->use_size() > N1.getNode()->use_size())
9009       std::swap(N0, N1);
9010   }
9011 
9012   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
9013   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9014     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9015                        N0.getOperand(0), N0.getOperand(1), N1);
9016   }
9017 
9018   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
9019   // Note: Commutes FADD operands.
9020   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
9021     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9022                        N1.getOperand(0), N1.getOperand(1), N0);
9023   }
9024 
9025   // Look through FP_EXTEND nodes to do more combining.
9026   if (LookThroughFPExt) {
9027     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
9028     if (N0.getOpcode() == ISD::FP_EXTEND) {
9029       SDValue N00 = N0.getOperand(0);
9030       if (isContractableFMUL(N00))
9031         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9032                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9033                                        N00.getOperand(0)),
9034                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9035                                        N00.getOperand(1)), N1);
9036     }
9037 
9038     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
9039     // Note: Commutes FADD operands.
9040     if (N1.getOpcode() == ISD::FP_EXTEND) {
9041       SDValue N10 = N1.getOperand(0);
9042       if (isContractableFMUL(N10))
9043         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9044                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9045                                        N10.getOperand(0)),
9046                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9047                                        N10.getOperand(1)), N0);
9048     }
9049   }
9050 
9051   // More folding opportunities when target permits.
9052   if (Aggressive) {
9053     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9054     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9055     // are currently only supported on binary nodes.
9056     if (Options.UnsafeFPMath &&
9057         N0.getOpcode() == PreferredFusedOpcode &&
9058         N0.getOperand(2).getOpcode() == ISD::FMUL &&
9059         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9060       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9061                          N0.getOperand(0), N0.getOperand(1),
9062                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9063                                      N0.getOperand(2).getOperand(0),
9064                                      N0.getOperand(2).getOperand(1),
9065                                      N1));
9066     }
9067 
9068     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9069     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9070     // are currently only supported on binary nodes.
9071     if (Options.UnsafeFPMath &&
9072         N1->getOpcode() == PreferredFusedOpcode &&
9073         N1.getOperand(2).getOpcode() == ISD::FMUL &&
9074         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9075       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9076                          N1.getOperand(0), N1.getOperand(1),
9077                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9078                                      N1.getOperand(2).getOperand(0),
9079                                      N1.getOperand(2).getOperand(1),
9080                                      N0));
9081     }
9082 
9083     if (LookThroughFPExt) {
9084       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9085       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
9086       auto FoldFAddFMAFPExtFMul = [&] (
9087           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9088         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9089                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9090                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9091                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9092                                        Z));
9093       };
9094       if (N0.getOpcode() == PreferredFusedOpcode) {
9095         SDValue N02 = N0.getOperand(2);
9096         if (N02.getOpcode() == ISD::FP_EXTEND) {
9097           SDValue N020 = N02.getOperand(0);
9098           if (isContractableFMUL(N020))
9099             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9100                                         N020.getOperand(0), N020.getOperand(1),
9101                                         N1);
9102         }
9103       }
9104 
9105       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9106       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9107       // FIXME: This turns two single-precision and one double-precision
9108       // operation into two double-precision operations, which might not be
9109       // interesting for all targets, especially GPUs.
9110       auto FoldFAddFPExtFMAFMul = [&] (
9111           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9112         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9113                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9114                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9115                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9116                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9117                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9118                                        Z));
9119       };
9120       if (N0.getOpcode() == ISD::FP_EXTEND) {
9121         SDValue N00 = N0.getOperand(0);
9122         if (N00.getOpcode() == PreferredFusedOpcode) {
9123           SDValue N002 = N00.getOperand(2);
9124           if (isContractableFMUL(N002))
9125             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9126                                         N002.getOperand(0), N002.getOperand(1),
9127                                         N1);
9128         }
9129       }
9130 
9131       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9132       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9133       if (N1.getOpcode() == PreferredFusedOpcode) {
9134         SDValue N12 = N1.getOperand(2);
9135         if (N12.getOpcode() == ISD::FP_EXTEND) {
9136           SDValue N120 = N12.getOperand(0);
9137           if (isContractableFMUL(N120))
9138             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9139                                         N120.getOperand(0), N120.getOperand(1),
9140                                         N0);
9141         }
9142       }
9143 
9144       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9145       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9146       // FIXME: This turns two single-precision and one double-precision
9147       // operation into two double-precision operations, which might not be
9148       // interesting for all targets, especially GPUs.
9149       if (N1.getOpcode() == ISD::FP_EXTEND) {
9150         SDValue N10 = N1.getOperand(0);
9151         if (N10.getOpcode() == PreferredFusedOpcode) {
9152           SDValue N102 = N10.getOperand(2);
9153           if (isContractableFMUL(N102))
9154             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9155                                         N102.getOperand(0), N102.getOperand(1),
9156                                         N0);
9157         }
9158       }
9159     }
9160   }
9161 
9162   return SDValue();
9163 }
9164 
9165 /// Try to perform FMA combining on a given FSUB node.
9166 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9167   SDValue N0 = N->getOperand(0);
9168   SDValue N1 = N->getOperand(1);
9169   EVT VT = N->getValueType(0);
9170   SDLoc SL(N);
9171 
9172   const TargetOptions &Options = DAG.getTarget().Options;
9173   // Floating-point multiply-add with intermediate rounding.
9174   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9175 
9176   // Floating-point multiply-add without intermediate rounding.
9177   bool HasFMA =
9178       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9179       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9180 
9181   // No valid opcode, do not combine.
9182   if (!HasFMAD && !HasFMA)
9183     return SDValue();
9184 
9185   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9186                               Options.UnsafeFPMath || HasFMAD);
9187   // If the subtraction is not contractable, do not combine.
9188   if (!AllowFusionGlobally && !isContractable(N))
9189     return SDValue();
9190 
9191   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9192   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9193     return SDValue();
9194 
9195   // Always prefer FMAD to FMA for precision.
9196   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9197   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9198   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9199 
9200   // Is the node an FMUL and contractable either due to global flags or
9201   // SDNodeFlags.
9202   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9203     if (N.getOpcode() != ISD::FMUL)
9204       return false;
9205     return AllowFusionGlobally || isContractable(N.getNode());
9206   };
9207 
9208   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9209   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9210     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9211                        N0.getOperand(0), N0.getOperand(1),
9212                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9213   }
9214 
9215   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9216   // Note: Commutes FSUB operands.
9217   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9218     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9219                        DAG.getNode(ISD::FNEG, SL, VT,
9220                                    N1.getOperand(0)),
9221                        N1.getOperand(1), N0);
9222 
9223   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9224   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9225       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9226     SDValue N00 = N0.getOperand(0).getOperand(0);
9227     SDValue N01 = N0.getOperand(0).getOperand(1);
9228     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9229                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9230                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9231   }
9232 
9233   // Look through FP_EXTEND nodes to do more combining.
9234   if (LookThroughFPExt) {
9235     // fold (fsub (fpext (fmul x, y)), z)
9236     //   -> (fma (fpext x), (fpext y), (fneg z))
9237     if (N0.getOpcode() == ISD::FP_EXTEND) {
9238       SDValue N00 = N0.getOperand(0);
9239       if (isContractableFMUL(N00))
9240         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9241                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9242                                        N00.getOperand(0)),
9243                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9244                                        N00.getOperand(1)),
9245                            DAG.getNode(ISD::FNEG, SL, VT, N1));
9246     }
9247 
9248     // fold (fsub x, (fpext (fmul y, z)))
9249     //   -> (fma (fneg (fpext y)), (fpext z), x)
9250     // Note: Commutes FSUB operands.
9251     if (N1.getOpcode() == ISD::FP_EXTEND) {
9252       SDValue N10 = N1.getOperand(0);
9253       if (isContractableFMUL(N10))
9254         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9255                            DAG.getNode(ISD::FNEG, SL, VT,
9256                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9257                                                    N10.getOperand(0))),
9258                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9259                                        N10.getOperand(1)),
9260                            N0);
9261     }
9262 
9263     // fold (fsub (fpext (fneg (fmul, x, y))), z)
9264     //   -> (fneg (fma (fpext x), (fpext y), z))
9265     // Note: This could be removed with appropriate canonicalization of the
9266     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9267     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9268     // from implementing the canonicalization in visitFSUB.
9269     if (N0.getOpcode() == ISD::FP_EXTEND) {
9270       SDValue N00 = N0.getOperand(0);
9271       if (N00.getOpcode() == ISD::FNEG) {
9272         SDValue N000 = N00.getOperand(0);
9273         if (isContractableFMUL(N000)) {
9274           return DAG.getNode(ISD::FNEG, SL, VT,
9275                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9276                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9277                                                      N000.getOperand(0)),
9278                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9279                                                      N000.getOperand(1)),
9280                                          N1));
9281         }
9282       }
9283     }
9284 
9285     // fold (fsub (fneg (fpext (fmul, x, y))), z)
9286     //   -> (fneg (fma (fpext x)), (fpext y), z)
9287     // Note: This could be removed with appropriate canonicalization of the
9288     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9289     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9290     // from implementing the canonicalization in visitFSUB.
9291     if (N0.getOpcode() == ISD::FNEG) {
9292       SDValue N00 = N0.getOperand(0);
9293       if (N00.getOpcode() == ISD::FP_EXTEND) {
9294         SDValue N000 = N00.getOperand(0);
9295         if (isContractableFMUL(N000)) {
9296           return DAG.getNode(ISD::FNEG, SL, VT,
9297                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9298                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9299                                                      N000.getOperand(0)),
9300                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9301                                                      N000.getOperand(1)),
9302                                          N1));
9303         }
9304       }
9305     }
9306 
9307   }
9308 
9309   // More folding opportunities when target permits.
9310   if (Aggressive) {
9311     // fold (fsub (fma x, y, (fmul u, v)), z)
9312     //   -> (fma x, y (fma u, v, (fneg z)))
9313     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9314     // are currently only supported on binary nodes.
9315     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9316         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9317         N0.getOperand(2)->hasOneUse()) {
9318       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9319                          N0.getOperand(0), N0.getOperand(1),
9320                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9321                                      N0.getOperand(2).getOperand(0),
9322                                      N0.getOperand(2).getOperand(1),
9323                                      DAG.getNode(ISD::FNEG, SL, VT,
9324                                                  N1)));
9325     }
9326 
9327     // fold (fsub x, (fma y, z, (fmul u, v)))
9328     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9329     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9330     // are currently only supported on binary nodes.
9331     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9332         isContractableFMUL(N1.getOperand(2))) {
9333       SDValue N20 = N1.getOperand(2).getOperand(0);
9334       SDValue N21 = N1.getOperand(2).getOperand(1);
9335       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9336                          DAG.getNode(ISD::FNEG, SL, VT,
9337                                      N1.getOperand(0)),
9338                          N1.getOperand(1),
9339                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9340                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9341 
9342                                      N21, N0));
9343     }
9344 
9345     if (LookThroughFPExt) {
9346       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9347       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9348       if (N0.getOpcode() == PreferredFusedOpcode) {
9349         SDValue N02 = N0.getOperand(2);
9350         if (N02.getOpcode() == ISD::FP_EXTEND) {
9351           SDValue N020 = N02.getOperand(0);
9352           if (isContractableFMUL(N020))
9353             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9354                                N0.getOperand(0), N0.getOperand(1),
9355                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9356                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9357                                                        N020.getOperand(0)),
9358                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9359                                                        N020.getOperand(1)),
9360                                            DAG.getNode(ISD::FNEG, SL, VT,
9361                                                        N1)));
9362         }
9363       }
9364 
9365       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9366       //   -> (fma (fpext x), (fpext y),
9367       //           (fma (fpext u), (fpext v), (fneg z)))
9368       // FIXME: This turns two single-precision and one double-precision
9369       // operation into two double-precision operations, which might not be
9370       // interesting for all targets, especially GPUs.
9371       if (N0.getOpcode() == ISD::FP_EXTEND) {
9372         SDValue N00 = N0.getOperand(0);
9373         if (N00.getOpcode() == PreferredFusedOpcode) {
9374           SDValue N002 = N00.getOperand(2);
9375           if (isContractableFMUL(N002))
9376             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9377                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9378                                            N00.getOperand(0)),
9379                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9380                                            N00.getOperand(1)),
9381                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9382                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9383                                                        N002.getOperand(0)),
9384                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9385                                                        N002.getOperand(1)),
9386                                            DAG.getNode(ISD::FNEG, SL, VT,
9387                                                        N1)));
9388         }
9389       }
9390 
9391       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9392       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9393       if (N1.getOpcode() == PreferredFusedOpcode &&
9394         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9395         SDValue N120 = N1.getOperand(2).getOperand(0);
9396         if (isContractableFMUL(N120)) {
9397           SDValue N1200 = N120.getOperand(0);
9398           SDValue N1201 = N120.getOperand(1);
9399           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9400                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9401                              N1.getOperand(1),
9402                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9403                                          DAG.getNode(ISD::FNEG, SL, VT,
9404                                              DAG.getNode(ISD::FP_EXTEND, SL,
9405                                                          VT, N1200)),
9406                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9407                                                      N1201),
9408                                          N0));
9409         }
9410       }
9411 
9412       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9413       //   -> (fma (fneg (fpext y)), (fpext z),
9414       //           (fma (fneg (fpext u)), (fpext v), x))
9415       // FIXME: This turns two single-precision and one double-precision
9416       // operation into two double-precision operations, which might not be
9417       // interesting for all targets, especially GPUs.
9418       if (N1.getOpcode() == ISD::FP_EXTEND &&
9419         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9420         SDValue N100 = N1.getOperand(0).getOperand(0);
9421         SDValue N101 = N1.getOperand(0).getOperand(1);
9422         SDValue N102 = N1.getOperand(0).getOperand(2);
9423         if (isContractableFMUL(N102)) {
9424           SDValue N1020 = N102.getOperand(0);
9425           SDValue N1021 = N102.getOperand(1);
9426           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9427                              DAG.getNode(ISD::FNEG, SL, VT,
9428                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9429                                                      N100)),
9430                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9431                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9432                                          DAG.getNode(ISD::FNEG, SL, VT,
9433                                              DAG.getNode(ISD::FP_EXTEND, SL,
9434                                                          VT, N1020)),
9435                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9436                                                      N1021),
9437                                          N0));
9438         }
9439       }
9440     }
9441   }
9442 
9443   return SDValue();
9444 }
9445 
9446 /// Try to perform FMA combining on a given FMUL node based on the distributive
9447 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9448 /// subtraction instead of addition).
9449 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9450   SDValue N0 = N->getOperand(0);
9451   SDValue N1 = N->getOperand(1);
9452   EVT VT = N->getValueType(0);
9453   SDLoc SL(N);
9454 
9455   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9456 
9457   const TargetOptions &Options = DAG.getTarget().Options;
9458 
9459   // The transforms below are incorrect when x == 0 and y == inf, because the
9460   // intermediate multiplication produces a nan.
9461   if (!Options.NoInfsFPMath)
9462     return SDValue();
9463 
9464   // Floating-point multiply-add without intermediate rounding.
9465   bool HasFMA =
9466       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9467       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9468       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9469 
9470   // Floating-point multiply-add with intermediate rounding. This can result
9471   // in a less precise result due to the changed rounding order.
9472   bool HasFMAD = Options.UnsafeFPMath &&
9473                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9474 
9475   // No valid opcode, do not combine.
9476   if (!HasFMAD && !HasFMA)
9477     return SDValue();
9478 
9479   // Always prefer FMAD to FMA for precision.
9480   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9481   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9482 
9483   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9484   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9485   auto FuseFADD = [&](SDValue X, SDValue Y) {
9486     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9487       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9488       if (XC1 && XC1->isExactlyValue(+1.0))
9489         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9490       if (XC1 && XC1->isExactlyValue(-1.0))
9491         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9492                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9493     }
9494     return SDValue();
9495   };
9496 
9497   if (SDValue FMA = FuseFADD(N0, N1))
9498     return FMA;
9499   if (SDValue FMA = FuseFADD(N1, N0))
9500     return FMA;
9501 
9502   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9503   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9504   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9505   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9506   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9507     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9508       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9509       if (XC0 && XC0->isExactlyValue(+1.0))
9510         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9511                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9512                            Y);
9513       if (XC0 && XC0->isExactlyValue(-1.0))
9514         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9515                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9516                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9517 
9518       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9519       if (XC1 && XC1->isExactlyValue(+1.0))
9520         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9521                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9522       if (XC1 && XC1->isExactlyValue(-1.0))
9523         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9524     }
9525     return SDValue();
9526   };
9527 
9528   if (SDValue FMA = FuseFSUB(N0, N1))
9529     return FMA;
9530   if (SDValue FMA = FuseFSUB(N1, N0))
9531     return FMA;
9532 
9533   return SDValue();
9534 }
9535 
9536 static bool isFMulNegTwo(SDValue &N) {
9537   if (N.getOpcode() != ISD::FMUL)
9538     return false;
9539   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9540     return CFP->isExactlyValue(-2.0);
9541   return false;
9542 }
9543 
9544 SDValue DAGCombiner::visitFADD(SDNode *N) {
9545   SDValue N0 = N->getOperand(0);
9546   SDValue N1 = N->getOperand(1);
9547   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9548   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9549   EVT VT = N->getValueType(0);
9550   SDLoc DL(N);
9551   const TargetOptions &Options = DAG.getTarget().Options;
9552   const SDNodeFlags Flags = N->getFlags();
9553 
9554   // fold vector ops
9555   if (VT.isVector())
9556     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9557       return FoldedVOp;
9558 
9559   // fold (fadd c1, c2) -> c1 + c2
9560   if (N0CFP && N1CFP)
9561     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9562 
9563   // canonicalize constant to RHS
9564   if (N0CFP && !N1CFP)
9565     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9566 
9567   if (SDValue NewSel = foldBinOpIntoSelect(N))
9568     return NewSel;
9569 
9570   // fold (fadd A, (fneg B)) -> (fsub A, B)
9571   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9572       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9573     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9574                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9575 
9576   // fold (fadd (fneg A), B) -> (fsub B, A)
9577   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9578       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9579     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9580                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9581 
9582   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9583   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9584   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9585       (isFMulNegTwo(N1) && N1.hasOneUse())) {
9586     bool N1IsFMul = isFMulNegTwo(N1);
9587     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9588     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9589     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9590   }
9591 
9592   // FIXME: Auto-upgrade the target/function-level option.
9593   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9594     // fold (fadd A, 0) -> A
9595     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9596       if (N1C->isZero())
9597         return N0;
9598   }
9599 
9600   // If 'unsafe math' is enabled, fold lots of things.
9601   if (Options.UnsafeFPMath) {
9602     // No FP constant should be created after legalization as Instruction
9603     // Selection pass has a hard time dealing with FP constants.
9604     bool AllowNewConst = (Level < AfterLegalizeDAG);
9605 
9606     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9607     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9608         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9609       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9610                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9611                                      Flags),
9612                          Flags);
9613 
9614     // If allowed, fold (fadd (fneg x), x) -> 0.0
9615     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9616       return DAG.getConstantFP(0.0, DL, VT);
9617 
9618     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9619     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9620       return DAG.getConstantFP(0.0, DL, VT);
9621 
9622     // We can fold chains of FADD's of the same value into multiplications.
9623     // This transform is not safe in general because we are reducing the number
9624     // of rounding steps.
9625     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9626       if (N0.getOpcode() == ISD::FMUL) {
9627         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9628         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9629 
9630         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9631         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9632           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9633                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9634           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9635         }
9636 
9637         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9638         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9639             N1.getOperand(0) == N1.getOperand(1) &&
9640             N0.getOperand(0) == N1.getOperand(0)) {
9641           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9642                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9643           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9644         }
9645       }
9646 
9647       if (N1.getOpcode() == ISD::FMUL) {
9648         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9649         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9650 
9651         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9652         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9653           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9654                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9655           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9656         }
9657 
9658         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9659         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9660             N0.getOperand(0) == N0.getOperand(1) &&
9661             N1.getOperand(0) == N0.getOperand(0)) {
9662           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9663                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9664           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9665         }
9666       }
9667 
9668       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9669         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9670         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9671         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9672             (N0.getOperand(0) == N1)) {
9673           return DAG.getNode(ISD::FMUL, DL, VT,
9674                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9675         }
9676       }
9677 
9678       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9679         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9680         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9681         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9682             N1.getOperand(0) == N0) {
9683           return DAG.getNode(ISD::FMUL, DL, VT,
9684                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9685         }
9686       }
9687 
9688       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9689       if (AllowNewConst &&
9690           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9691           N0.getOperand(0) == N0.getOperand(1) &&
9692           N1.getOperand(0) == N1.getOperand(1) &&
9693           N0.getOperand(0) == N1.getOperand(0)) {
9694         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9695                            DAG.getConstantFP(4.0, DL, VT), Flags);
9696       }
9697     }
9698   } // enable-unsafe-fp-math
9699 
9700   // FADD -> FMA combines:
9701   if (SDValue Fused = visitFADDForFMACombine(N)) {
9702     AddToWorklist(Fused.getNode());
9703     return Fused;
9704   }
9705   return SDValue();
9706 }
9707 
9708 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9709   SDValue N0 = N->getOperand(0);
9710   SDValue N1 = N->getOperand(1);
9711   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9712   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9713   EVT VT = N->getValueType(0);
9714   SDLoc DL(N);
9715   const TargetOptions &Options = DAG.getTarget().Options;
9716   const SDNodeFlags Flags = N->getFlags();
9717 
9718   // fold vector ops
9719   if (VT.isVector())
9720     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9721       return FoldedVOp;
9722 
9723   // fold (fsub c1, c2) -> c1-c2
9724   if (N0CFP && N1CFP)
9725     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9726 
9727   if (SDValue NewSel = foldBinOpIntoSelect(N))
9728     return NewSel;
9729 
9730   // fold (fsub A, (fneg B)) -> (fadd A, B)
9731   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9732     return DAG.getNode(ISD::FADD, DL, VT, N0,
9733                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9734 
9735   // FIXME: Auto-upgrade the target/function-level option.
9736   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
9737     // (fsub 0, B) -> -B
9738     if (N0CFP && N0CFP->isZero()) {
9739       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9740         return GetNegatedExpression(N1, DAG, LegalOperations);
9741       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9742         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9743     }
9744   }
9745 
9746   // If 'unsafe math' is enabled, fold lots of things.
9747   if (Options.UnsafeFPMath) {
9748     // (fsub A, 0) -> A
9749     if (N1CFP && N1CFP->isZero())
9750       return N0;
9751 
9752     // (fsub x, x) -> 0.0
9753     if (N0 == N1)
9754       return DAG.getConstantFP(0.0f, DL, VT);
9755 
9756     // (fsub x, (fadd x, y)) -> (fneg y)
9757     // (fsub x, (fadd y, x)) -> (fneg y)
9758     if (N1.getOpcode() == ISD::FADD) {
9759       SDValue N10 = N1->getOperand(0);
9760       SDValue N11 = N1->getOperand(1);
9761 
9762       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9763         return GetNegatedExpression(N11, DAG, LegalOperations);
9764 
9765       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9766         return GetNegatedExpression(N10, DAG, LegalOperations);
9767     }
9768   }
9769 
9770   // FSUB -> FMA combines:
9771   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9772     AddToWorklist(Fused.getNode());
9773     return Fused;
9774   }
9775 
9776   return SDValue();
9777 }
9778 
9779 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9780   SDValue N0 = N->getOperand(0);
9781   SDValue N1 = N->getOperand(1);
9782   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9783   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9784   EVT VT = N->getValueType(0);
9785   SDLoc DL(N);
9786   const TargetOptions &Options = DAG.getTarget().Options;
9787   const SDNodeFlags Flags = N->getFlags();
9788 
9789   // fold vector ops
9790   if (VT.isVector()) {
9791     // This just handles C1 * C2 for vectors. Other vector folds are below.
9792     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9793       return FoldedVOp;
9794   }
9795 
9796   // fold (fmul c1, c2) -> c1*c2
9797   if (N0CFP && N1CFP)
9798     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9799 
9800   // canonicalize constant to RHS
9801   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9802      !isConstantFPBuildVectorOrConstantFP(N1))
9803     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9804 
9805   // fold (fmul A, 1.0) -> A
9806   if (N1CFP && N1CFP->isExactlyValue(1.0))
9807     return N0;
9808 
9809   if (SDValue NewSel = foldBinOpIntoSelect(N))
9810     return NewSel;
9811 
9812   if (Options.UnsafeFPMath) {
9813     // fold (fmul A, 0) -> 0
9814     if (N1CFP && N1CFP->isZero())
9815       return N1;
9816 
9817     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9818     if (N0.getOpcode() == ISD::FMUL) {
9819       // Fold scalars or any vector constants (not just splats).
9820       // This fold is done in general by InstCombine, but extra fmul insts
9821       // may have been generated during lowering.
9822       SDValue N00 = N0.getOperand(0);
9823       SDValue N01 = N0.getOperand(1);
9824       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9825       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9826       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9827 
9828       // Check 1: Make sure that the first operand of the inner multiply is NOT
9829       // a constant. Otherwise, we may induce infinite looping.
9830       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9831         // Check 2: Make sure that the second operand of the inner multiply and
9832         // the second operand of the outer multiply are constants.
9833         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9834             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9835           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9836           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9837         }
9838       }
9839     }
9840 
9841     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9842     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9843     // during an early run of DAGCombiner can prevent folding with fmuls
9844     // inserted during lowering.
9845     if (N0.getOpcode() == ISD::FADD &&
9846         (N0.getOperand(0) == N0.getOperand(1)) &&
9847         N0.hasOneUse()) {
9848       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9849       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9850       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9851     }
9852   }
9853 
9854   // fold (fmul X, 2.0) -> (fadd X, X)
9855   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9856     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9857 
9858   // fold (fmul X, -1.0) -> (fneg X)
9859   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9860     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9861       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9862 
9863   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9864   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9865     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9866       // Both can be negated for free, check to see if at least one is cheaper
9867       // negated.
9868       if (LHSNeg == 2 || RHSNeg == 2)
9869         return DAG.getNode(ISD::FMUL, DL, VT,
9870                            GetNegatedExpression(N0, DAG, LegalOperations),
9871                            GetNegatedExpression(N1, DAG, LegalOperations),
9872                            Flags);
9873     }
9874   }
9875 
9876   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
9877   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
9878   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
9879       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
9880       TLI.isOperationLegal(ISD::FABS, VT)) {
9881     SDValue Select = N0, X = N1;
9882     if (Select.getOpcode() != ISD::SELECT)
9883       std::swap(Select, X);
9884 
9885     SDValue Cond = Select.getOperand(0);
9886     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
9887     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
9888 
9889     if (TrueOpnd && FalseOpnd &&
9890         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
9891         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
9892         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
9893       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9894       switch (CC) {
9895       default: break;
9896       case ISD::SETOLT:
9897       case ISD::SETULT:
9898       case ISD::SETOLE:
9899       case ISD::SETULE:
9900       case ISD::SETLT:
9901       case ISD::SETLE:
9902         std::swap(TrueOpnd, FalseOpnd);
9903         // Fall through
9904       case ISD::SETOGT:
9905       case ISD::SETUGT:
9906       case ISD::SETOGE:
9907       case ISD::SETUGE:
9908       case ISD::SETGT:
9909       case ISD::SETGE:
9910         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
9911             TLI.isOperationLegal(ISD::FNEG, VT))
9912           return DAG.getNode(ISD::FNEG, DL, VT,
9913                    DAG.getNode(ISD::FABS, DL, VT, X));
9914         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
9915           return DAG.getNode(ISD::FABS, DL, VT, X);
9916 
9917         break;
9918       }
9919     }
9920   }
9921 
9922   // FMUL -> FMA combines:
9923   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9924     AddToWorklist(Fused.getNode());
9925     return Fused;
9926   }
9927 
9928   return SDValue();
9929 }
9930 
9931 SDValue DAGCombiner::visitFMA(SDNode *N) {
9932   SDValue N0 = N->getOperand(0);
9933   SDValue N1 = N->getOperand(1);
9934   SDValue N2 = N->getOperand(2);
9935   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9936   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9937   EVT VT = N->getValueType(0);
9938   SDLoc DL(N);
9939   const TargetOptions &Options = DAG.getTarget().Options;
9940 
9941   // Constant fold FMA.
9942   if (isa<ConstantFPSDNode>(N0) &&
9943       isa<ConstantFPSDNode>(N1) &&
9944       isa<ConstantFPSDNode>(N2)) {
9945     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9946   }
9947 
9948   if (Options.UnsafeFPMath) {
9949     if (N0CFP && N0CFP->isZero())
9950       return N2;
9951     if (N1CFP && N1CFP->isZero())
9952       return N2;
9953   }
9954   // TODO: The FMA node should have flags that propagate to these nodes.
9955   if (N0CFP && N0CFP->isExactlyValue(1.0))
9956     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9957   if (N1CFP && N1CFP->isExactlyValue(1.0))
9958     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9959 
9960   // Canonicalize (fma c, x, y) -> (fma x, c, y)
9961   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9962      !isConstantFPBuildVectorOrConstantFP(N1))
9963     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9964 
9965   // TODO: FMA nodes should have flags that propagate to the created nodes.
9966   // For now, create a Flags object for use with all unsafe math transforms.
9967   SDNodeFlags Flags;
9968   Flags.setUnsafeAlgebra(true);
9969 
9970   if (Options.UnsafeFPMath) {
9971     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9972     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9973         isConstantFPBuildVectorOrConstantFP(N1) &&
9974         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9975       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9976                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9977                                      Flags), Flags);
9978     }
9979 
9980     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9981     if (N0.getOpcode() == ISD::FMUL &&
9982         isConstantFPBuildVectorOrConstantFP(N1) &&
9983         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9984       return DAG.getNode(ISD::FMA, DL, VT,
9985                          N0.getOperand(0),
9986                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9987                                      Flags),
9988                          N2);
9989     }
9990   }
9991 
9992   // (fma x, 1, y) -> (fadd x, y)
9993   // (fma x, -1, y) -> (fadd (fneg x), y)
9994   if (N1CFP) {
9995     if (N1CFP->isExactlyValue(1.0))
9996       // TODO: The FMA node should have flags that propagate to this node.
9997       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9998 
9999     if (N1CFP->isExactlyValue(-1.0) &&
10000         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
10001       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
10002       AddToWorklist(RHSNeg.getNode());
10003       // TODO: The FMA node should have flags that propagate to this node.
10004       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
10005     }
10006   }
10007 
10008   if (Options.UnsafeFPMath) {
10009     // (fma x, c, x) -> (fmul x, (c+1))
10010     if (N1CFP && N0 == N2) {
10011       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10012                          DAG.getNode(ISD::FADD, DL, VT, N1,
10013                                      DAG.getConstantFP(1.0, DL, VT), Flags),
10014                          Flags);
10015     }
10016 
10017     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
10018     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
10019       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10020                          DAG.getNode(ISD::FADD, DL, VT, N1,
10021                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
10022                          Flags);
10023     }
10024   }
10025 
10026   return SDValue();
10027 }
10028 
10029 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10030 // reciprocal.
10031 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
10032 // Notice that this is not always beneficial. One reason is different targets
10033 // may have different costs for FDIV and FMUL, so sometimes the cost of two
10034 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
10035 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
10036 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
10037   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
10038   const SDNodeFlags Flags = N->getFlags();
10039   if (!UnsafeMath && !Flags.hasAllowReciprocal())
10040     return SDValue();
10041 
10042   // Skip if current node is a reciprocal.
10043   SDValue N0 = N->getOperand(0);
10044   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10045   if (N0CFP && N0CFP->isExactlyValue(1.0))
10046     return SDValue();
10047 
10048   // Exit early if the target does not want this transform or if there can't
10049   // possibly be enough uses of the divisor to make the transform worthwhile.
10050   SDValue N1 = N->getOperand(1);
10051   unsigned MinUses = TLI.combineRepeatedFPDivisors();
10052   if (!MinUses || N1->use_size() < MinUses)
10053     return SDValue();
10054 
10055   // Find all FDIV users of the same divisor.
10056   // Use a set because duplicates may be present in the user list.
10057   SetVector<SDNode *> Users;
10058   for (auto *U : N1->uses()) {
10059     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10060       // This division is eligible for optimization only if global unsafe math
10061       // is enabled or if this division allows reciprocal formation.
10062       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10063         Users.insert(U);
10064     }
10065   }
10066 
10067   // Now that we have the actual number of divisor uses, make sure it meets
10068   // the minimum threshold specified by the target.
10069   if (Users.size() < MinUses)
10070     return SDValue();
10071 
10072   EVT VT = N->getValueType(0);
10073   SDLoc DL(N);
10074   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10075   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10076 
10077   // Dividend / Divisor -> Dividend * Reciprocal
10078   for (auto *U : Users) {
10079     SDValue Dividend = U->getOperand(0);
10080     if (Dividend != FPOne) {
10081       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10082                                     Reciprocal, Flags);
10083       CombineTo(U, NewNode);
10084     } else if (U != Reciprocal.getNode()) {
10085       // In the absence of fast-math-flags, this user node is always the
10086       // same node as Reciprocal, but with FMF they may be different nodes.
10087       CombineTo(U, Reciprocal);
10088     }
10089   }
10090   return SDValue(N, 0);  // N was replaced.
10091 }
10092 
10093 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10094   SDValue N0 = N->getOperand(0);
10095   SDValue N1 = N->getOperand(1);
10096   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10097   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10098   EVT VT = N->getValueType(0);
10099   SDLoc DL(N);
10100   const TargetOptions &Options = DAG.getTarget().Options;
10101   SDNodeFlags Flags = N->getFlags();
10102 
10103   // fold vector ops
10104   if (VT.isVector())
10105     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10106       return FoldedVOp;
10107 
10108   // fold (fdiv c1, c2) -> c1/c2
10109   if (N0CFP && N1CFP)
10110     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10111 
10112   if (SDValue NewSel = foldBinOpIntoSelect(N))
10113     return NewSel;
10114 
10115   if (Options.UnsafeFPMath) {
10116     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10117     if (N1CFP) {
10118       // Compute the reciprocal 1.0 / c2.
10119       const APFloat &N1APF = N1CFP->getValueAPF();
10120       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10121       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10122       // Only do the transform if the reciprocal is a legal fp immediate that
10123       // isn't too nasty (eg NaN, denormal, ...).
10124       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10125           (!LegalOperations ||
10126            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10127            // backend)... we should handle this gracefully after Legalize.
10128            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
10129            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
10130            TLI.isFPImmLegal(Recip, VT)))
10131         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10132                            DAG.getConstantFP(Recip, DL, VT), Flags);
10133     }
10134 
10135     // If this FDIV is part of a reciprocal square root, it may be folded
10136     // into a target-specific square root estimate instruction.
10137     if (N1.getOpcode() == ISD::FSQRT) {
10138       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10139         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10140       }
10141     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10142                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10143       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10144                                           Flags)) {
10145         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10146         AddToWorklist(RV.getNode());
10147         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10148       }
10149     } else if (N1.getOpcode() == ISD::FP_ROUND &&
10150                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10151       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10152                                           Flags)) {
10153         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10154         AddToWorklist(RV.getNode());
10155         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10156       }
10157     } else if (N1.getOpcode() == ISD::FMUL) {
10158       // Look through an FMUL. Even though this won't remove the FDIV directly,
10159       // it's still worthwhile to get rid of the FSQRT if possible.
10160       SDValue SqrtOp;
10161       SDValue OtherOp;
10162       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10163         SqrtOp = N1.getOperand(0);
10164         OtherOp = N1.getOperand(1);
10165       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10166         SqrtOp = N1.getOperand(1);
10167         OtherOp = N1.getOperand(0);
10168       }
10169       if (SqrtOp.getNode()) {
10170         // We found a FSQRT, so try to make this fold:
10171         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10172         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10173           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10174           AddToWorklist(RV.getNode());
10175           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10176         }
10177       }
10178     }
10179 
10180     // Fold into a reciprocal estimate and multiply instead of a real divide.
10181     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10182       AddToWorklist(RV.getNode());
10183       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10184     }
10185   }
10186 
10187   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10188   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10189     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10190       // Both can be negated for free, check to see if at least one is cheaper
10191       // negated.
10192       if (LHSNeg == 2 || RHSNeg == 2)
10193         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10194                            GetNegatedExpression(N0, DAG, LegalOperations),
10195                            GetNegatedExpression(N1, DAG, LegalOperations),
10196                            Flags);
10197     }
10198   }
10199 
10200   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10201     return CombineRepeatedDivisors;
10202 
10203   return SDValue();
10204 }
10205 
10206 SDValue DAGCombiner::visitFREM(SDNode *N) {
10207   SDValue N0 = N->getOperand(0);
10208   SDValue N1 = N->getOperand(1);
10209   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10210   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10211   EVT VT = N->getValueType(0);
10212 
10213   // fold (frem c1, c2) -> fmod(c1,c2)
10214   if (N0CFP && N1CFP)
10215     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10216 
10217   if (SDValue NewSel = foldBinOpIntoSelect(N))
10218     return NewSel;
10219 
10220   return SDValue();
10221 }
10222 
10223 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10224   if (!DAG.getTarget().Options.UnsafeFPMath)
10225     return SDValue();
10226 
10227   SDValue N0 = N->getOperand(0);
10228   if (TLI.isFsqrtCheap(N0, DAG))
10229     return SDValue();
10230 
10231   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10232   // For now, create a Flags object for use with all unsafe math transforms.
10233   SDNodeFlags Flags;
10234   Flags.setUnsafeAlgebra(true);
10235   return buildSqrtEstimate(N0, Flags);
10236 }
10237 
10238 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10239 /// copysign(x, fp_round(y)) -> copysign(x, y)
10240 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10241   SDValue N1 = N->getOperand(1);
10242   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10243        N1.getOpcode() == ISD::FP_ROUND)) {
10244     // Do not optimize out type conversion of f128 type yet.
10245     // For some targets like x86_64, configuration is changed to keep one f128
10246     // value in one SSE register, but instruction selection cannot handle
10247     // FCOPYSIGN on SSE registers yet.
10248     EVT N1VT = N1->getValueType(0);
10249     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10250     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10251   }
10252   return false;
10253 }
10254 
10255 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10256   SDValue N0 = N->getOperand(0);
10257   SDValue N1 = N->getOperand(1);
10258   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10259   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10260   EVT VT = N->getValueType(0);
10261 
10262   if (N0CFP && N1CFP) // Constant fold
10263     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10264 
10265   if (N1CFP) {
10266     const APFloat &V = N1CFP->getValueAPF();
10267     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10268     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10269     if (!V.isNegative()) {
10270       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10271         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10272     } else {
10273       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10274         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10275                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10276     }
10277   }
10278 
10279   // copysign(fabs(x), y) -> copysign(x, y)
10280   // copysign(fneg(x), y) -> copysign(x, y)
10281   // copysign(copysign(x,z), y) -> copysign(x, y)
10282   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10283       N0.getOpcode() == ISD::FCOPYSIGN)
10284     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10285 
10286   // copysign(x, abs(y)) -> abs(x)
10287   if (N1.getOpcode() == ISD::FABS)
10288     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10289 
10290   // copysign(x, copysign(y,z)) -> copysign(x, z)
10291   if (N1.getOpcode() == ISD::FCOPYSIGN)
10292     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10293 
10294   // copysign(x, fp_extend(y)) -> copysign(x, y)
10295   // copysign(x, fp_round(y)) -> copysign(x, y)
10296   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10297     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10298 
10299   return SDValue();
10300 }
10301 
10302 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10303   SDValue N0 = N->getOperand(0);
10304   EVT VT = N->getValueType(0);
10305   EVT OpVT = N0.getValueType();
10306 
10307   // fold (sint_to_fp c1) -> c1fp
10308   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10309       // ...but only if the target supports immediate floating-point values
10310       (!LegalOperations ||
10311        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10312     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10313 
10314   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10315   // but UINT_TO_FP is legal on this target, try to convert.
10316   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10317       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10318     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10319     if (DAG.SignBitIsZero(N0))
10320       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10321   }
10322 
10323   // The next optimizations are desirable only if SELECT_CC can be lowered.
10324   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10325     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10326     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10327         !VT.isVector() &&
10328         (!LegalOperations ||
10329          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10330       SDLoc DL(N);
10331       SDValue Ops[] =
10332         { N0.getOperand(0), N0.getOperand(1),
10333           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10334           N0.getOperand(2) };
10335       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10336     }
10337 
10338     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10339     //      (select_cc x, y, 1.0, 0.0,, cc)
10340     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10341         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10342         (!LegalOperations ||
10343          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10344       SDLoc DL(N);
10345       SDValue Ops[] =
10346         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10347           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10348           N0.getOperand(0).getOperand(2) };
10349       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10350     }
10351   }
10352 
10353   return SDValue();
10354 }
10355 
10356 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10357   SDValue N0 = N->getOperand(0);
10358   EVT VT = N->getValueType(0);
10359   EVT OpVT = N0.getValueType();
10360 
10361   // fold (uint_to_fp c1) -> c1fp
10362   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10363       // ...but only if the target supports immediate floating-point values
10364       (!LegalOperations ||
10365        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10366     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10367 
10368   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10369   // but SINT_TO_FP is legal on this target, try to convert.
10370   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10371       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10372     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10373     if (DAG.SignBitIsZero(N0))
10374       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10375   }
10376 
10377   // The next optimizations are desirable only if SELECT_CC can be lowered.
10378   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10379     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10380 
10381     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10382         (!LegalOperations ||
10383          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10384       SDLoc DL(N);
10385       SDValue Ops[] =
10386         { N0.getOperand(0), N0.getOperand(1),
10387           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10388           N0.getOperand(2) };
10389       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10390     }
10391   }
10392 
10393   return SDValue();
10394 }
10395 
10396 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10397 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10398   SDValue N0 = N->getOperand(0);
10399   EVT VT = N->getValueType(0);
10400 
10401   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10402     return SDValue();
10403 
10404   SDValue Src = N0.getOperand(0);
10405   EVT SrcVT = Src.getValueType();
10406   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10407   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10408 
10409   // We can safely assume the conversion won't overflow the output range,
10410   // because (for example) (uint8_t)18293.f is undefined behavior.
10411 
10412   // Since we can assume the conversion won't overflow, our decision as to
10413   // whether the input will fit in the float should depend on the minimum
10414   // of the input range and output range.
10415 
10416   // This means this is also safe for a signed input and unsigned output, since
10417   // a negative input would lead to undefined behavior.
10418   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10419   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10420   unsigned ActualSize = std::min(InputSize, OutputSize);
10421   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10422 
10423   // We can only fold away the float conversion if the input range can be
10424   // represented exactly in the float range.
10425   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10426     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10427       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10428                                                        : ISD::ZERO_EXTEND;
10429       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10430     }
10431     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10432       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10433     return DAG.getBitcast(VT, Src);
10434   }
10435   return SDValue();
10436 }
10437 
10438 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10439   SDValue N0 = N->getOperand(0);
10440   EVT VT = N->getValueType(0);
10441 
10442   // fold (fp_to_sint c1fp) -> c1
10443   if (isConstantFPBuildVectorOrConstantFP(N0))
10444     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10445 
10446   return FoldIntToFPToInt(N, DAG);
10447 }
10448 
10449 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10450   SDValue N0 = N->getOperand(0);
10451   EVT VT = N->getValueType(0);
10452 
10453   // fold (fp_to_uint c1fp) -> c1
10454   if (isConstantFPBuildVectorOrConstantFP(N0))
10455     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10456 
10457   return FoldIntToFPToInt(N, DAG);
10458 }
10459 
10460 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10461   SDValue N0 = N->getOperand(0);
10462   SDValue N1 = N->getOperand(1);
10463   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10464   EVT VT = N->getValueType(0);
10465 
10466   // fold (fp_round c1fp) -> c1fp
10467   if (N0CFP)
10468     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10469 
10470   // fold (fp_round (fp_extend x)) -> x
10471   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10472     return N0.getOperand(0);
10473 
10474   // fold (fp_round (fp_round x)) -> (fp_round x)
10475   if (N0.getOpcode() == ISD::FP_ROUND) {
10476     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10477     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10478 
10479     // Skip this folding if it results in an fp_round from f80 to f16.
10480     //
10481     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10482     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10483     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10484     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10485     // x86.
10486     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10487       return SDValue();
10488 
10489     // If the first fp_round isn't a value preserving truncation, it might
10490     // introduce a tie in the second fp_round, that wouldn't occur in the
10491     // single-step fp_round we want to fold to.
10492     // In other words, double rounding isn't the same as rounding.
10493     // Also, this is a value preserving truncation iff both fp_round's are.
10494     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10495       SDLoc DL(N);
10496       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10497                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10498     }
10499   }
10500 
10501   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10502   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10503     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10504                               N0.getOperand(0), N1);
10505     AddToWorklist(Tmp.getNode());
10506     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10507                        Tmp, N0.getOperand(1));
10508   }
10509 
10510   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10511     return NewVSel;
10512 
10513   return SDValue();
10514 }
10515 
10516 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10517   SDValue N0 = N->getOperand(0);
10518   EVT VT = N->getValueType(0);
10519   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10520   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10521 
10522   // fold (fp_round_inreg c1fp) -> c1fp
10523   if (N0CFP && isTypeLegal(EVT)) {
10524     SDLoc DL(N);
10525     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10526     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10527   }
10528 
10529   return SDValue();
10530 }
10531 
10532 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10533   SDValue N0 = N->getOperand(0);
10534   EVT VT = N->getValueType(0);
10535 
10536   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10537   if (N->hasOneUse() &&
10538       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10539     return SDValue();
10540 
10541   // fold (fp_extend c1fp) -> c1fp
10542   if (isConstantFPBuildVectorOrConstantFP(N0))
10543     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10544 
10545   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10546   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10547       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10548     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10549 
10550   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10551   // value of X.
10552   if (N0.getOpcode() == ISD::FP_ROUND
10553       && N0.getConstantOperandVal(1) == 1) {
10554     SDValue In = N0.getOperand(0);
10555     if (In.getValueType() == VT) return In;
10556     if (VT.bitsLT(In.getValueType()))
10557       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10558                          In, N0.getOperand(1));
10559     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10560   }
10561 
10562   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10563   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10564        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10565     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10566     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10567                                      LN0->getChain(),
10568                                      LN0->getBasePtr(), N0.getValueType(),
10569                                      LN0->getMemOperand());
10570     CombineTo(N, ExtLoad);
10571     CombineTo(N0.getNode(),
10572               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10573                           N0.getValueType(), ExtLoad,
10574                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10575               ExtLoad.getValue(1));
10576     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10577   }
10578 
10579   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10580     return NewVSel;
10581 
10582   return SDValue();
10583 }
10584 
10585 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10586   SDValue N0 = N->getOperand(0);
10587   EVT VT = N->getValueType(0);
10588 
10589   // fold (fceil c1) -> fceil(c1)
10590   if (isConstantFPBuildVectorOrConstantFP(N0))
10591     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10592 
10593   return SDValue();
10594 }
10595 
10596 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10597   SDValue N0 = N->getOperand(0);
10598   EVT VT = N->getValueType(0);
10599 
10600   // fold (ftrunc c1) -> ftrunc(c1)
10601   if (isConstantFPBuildVectorOrConstantFP(N0))
10602     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10603 
10604   return SDValue();
10605 }
10606 
10607 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10608   SDValue N0 = N->getOperand(0);
10609   EVT VT = N->getValueType(0);
10610 
10611   // fold (ffloor c1) -> ffloor(c1)
10612   if (isConstantFPBuildVectorOrConstantFP(N0))
10613     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10614 
10615   return SDValue();
10616 }
10617 
10618 // FIXME: FNEG and FABS have a lot in common; refactor.
10619 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10620   SDValue N0 = N->getOperand(0);
10621   EVT VT = N->getValueType(0);
10622 
10623   // Constant fold FNEG.
10624   if (isConstantFPBuildVectorOrConstantFP(N0))
10625     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10626 
10627   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10628                          &DAG.getTarget().Options))
10629     return GetNegatedExpression(N0, DAG, LegalOperations);
10630 
10631   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10632   // constant pool values.
10633   if (!TLI.isFNegFree(VT) &&
10634       N0.getOpcode() == ISD::BITCAST &&
10635       N0.getNode()->hasOneUse()) {
10636     SDValue Int = N0.getOperand(0);
10637     EVT IntVT = Int.getValueType();
10638     if (IntVT.isInteger() && !IntVT.isVector()) {
10639       APInt SignMask;
10640       if (N0.getValueType().isVector()) {
10641         // For a vector, get a mask such as 0x80... per scalar element
10642         // and splat it.
10643         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10644         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10645       } else {
10646         // For a scalar, just generate 0x80...
10647         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10648       }
10649       SDLoc DL0(N0);
10650       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10651                         DAG.getConstant(SignMask, DL0, IntVT));
10652       AddToWorklist(Int.getNode());
10653       return DAG.getBitcast(VT, Int);
10654     }
10655   }
10656 
10657   // (fneg (fmul c, x)) -> (fmul -c, x)
10658   if (N0.getOpcode() == ISD::FMUL &&
10659       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10660     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10661     if (CFP1) {
10662       APFloat CVal = CFP1->getValueAPF();
10663       CVal.changeSign();
10664       if (Level >= AfterLegalizeDAG &&
10665           (TLI.isFPImmLegal(CVal, VT) ||
10666            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10667         return DAG.getNode(
10668             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10669             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10670             N0->getFlags());
10671     }
10672   }
10673 
10674   return SDValue();
10675 }
10676 
10677 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10678   SDValue N0 = N->getOperand(0);
10679   SDValue N1 = N->getOperand(1);
10680   EVT VT = N->getValueType(0);
10681   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10682   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10683 
10684   if (N0CFP && N1CFP) {
10685     const APFloat &C0 = N0CFP->getValueAPF();
10686     const APFloat &C1 = N1CFP->getValueAPF();
10687     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10688   }
10689 
10690   // Canonicalize to constant on RHS.
10691   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10692      !isConstantFPBuildVectorOrConstantFP(N1))
10693     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10694 
10695   return SDValue();
10696 }
10697 
10698 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10699   SDValue N0 = N->getOperand(0);
10700   SDValue N1 = N->getOperand(1);
10701   EVT VT = N->getValueType(0);
10702   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10703   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10704 
10705   if (N0CFP && N1CFP) {
10706     const APFloat &C0 = N0CFP->getValueAPF();
10707     const APFloat &C1 = N1CFP->getValueAPF();
10708     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10709   }
10710 
10711   // Canonicalize to constant on RHS.
10712   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10713      !isConstantFPBuildVectorOrConstantFP(N1))
10714     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10715 
10716   return SDValue();
10717 }
10718 
10719 SDValue DAGCombiner::visitFABS(SDNode *N) {
10720   SDValue N0 = N->getOperand(0);
10721   EVT VT = N->getValueType(0);
10722 
10723   // fold (fabs c1) -> fabs(c1)
10724   if (isConstantFPBuildVectorOrConstantFP(N0))
10725     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10726 
10727   // fold (fabs (fabs x)) -> (fabs x)
10728   if (N0.getOpcode() == ISD::FABS)
10729     return N->getOperand(0);
10730 
10731   // fold (fabs (fneg x)) -> (fabs x)
10732   // fold (fabs (fcopysign x, y)) -> (fabs x)
10733   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10734     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10735 
10736   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10737   // constant pool values.
10738   if (!TLI.isFAbsFree(VT) &&
10739       N0.getOpcode() == ISD::BITCAST &&
10740       N0.getNode()->hasOneUse()) {
10741     SDValue Int = N0.getOperand(0);
10742     EVT IntVT = Int.getValueType();
10743     if (IntVT.isInteger() && !IntVT.isVector()) {
10744       APInt SignMask;
10745       if (N0.getValueType().isVector()) {
10746         // For a vector, get a mask such as 0x7f... per scalar element
10747         // and splat it.
10748         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10749         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10750       } else {
10751         // For a scalar, just generate 0x7f...
10752         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10753       }
10754       SDLoc DL(N0);
10755       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10756                         DAG.getConstant(SignMask, DL, IntVT));
10757       AddToWorklist(Int.getNode());
10758       return DAG.getBitcast(N->getValueType(0), Int);
10759     }
10760   }
10761 
10762   return SDValue();
10763 }
10764 
10765 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10766   SDValue Chain = N->getOperand(0);
10767   SDValue N1 = N->getOperand(1);
10768   SDValue N2 = N->getOperand(2);
10769 
10770   // If N is a constant we could fold this into a fallthrough or unconditional
10771   // branch. However that doesn't happen very often in normal code, because
10772   // Instcombine/SimplifyCFG should have handled the available opportunities.
10773   // If we did this folding here, it would be necessary to update the
10774   // MachineBasicBlock CFG, which is awkward.
10775 
10776   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10777   // on the target.
10778   if (N1.getOpcode() == ISD::SETCC &&
10779       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10780                                    N1.getOperand(0).getValueType())) {
10781     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10782                        Chain, N1.getOperand(2),
10783                        N1.getOperand(0), N1.getOperand(1), N2);
10784   }
10785 
10786   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10787       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10788        (N1.getOperand(0).hasOneUse() &&
10789         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10790     SDNode *Trunc = nullptr;
10791     if (N1.getOpcode() == ISD::TRUNCATE) {
10792       // Look pass the truncate.
10793       Trunc = N1.getNode();
10794       N1 = N1.getOperand(0);
10795     }
10796 
10797     // Match this pattern so that we can generate simpler code:
10798     //
10799     //   %a = ...
10800     //   %b = and i32 %a, 2
10801     //   %c = srl i32 %b, 1
10802     //   brcond i32 %c ...
10803     //
10804     // into
10805     //
10806     //   %a = ...
10807     //   %b = and i32 %a, 2
10808     //   %c = setcc eq %b, 0
10809     //   brcond %c ...
10810     //
10811     // This applies only when the AND constant value has one bit set and the
10812     // SRL constant is equal to the log2 of the AND constant. The back-end is
10813     // smart enough to convert the result into a TEST/JMP sequence.
10814     SDValue Op0 = N1.getOperand(0);
10815     SDValue Op1 = N1.getOperand(1);
10816 
10817     if (Op0.getOpcode() == ISD::AND &&
10818         Op1.getOpcode() == ISD::Constant) {
10819       SDValue AndOp1 = Op0.getOperand(1);
10820 
10821       if (AndOp1.getOpcode() == ISD::Constant) {
10822         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10823 
10824         if (AndConst.isPowerOf2() &&
10825             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10826           SDLoc DL(N);
10827           SDValue SetCC =
10828             DAG.getSetCC(DL,
10829                          getSetCCResultType(Op0.getValueType()),
10830                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10831                          ISD::SETNE);
10832 
10833           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10834                                           MVT::Other, Chain, SetCC, N2);
10835           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10836           // will convert it back to (X & C1) >> C2.
10837           CombineTo(N, NewBRCond, false);
10838           // Truncate is dead.
10839           if (Trunc)
10840             deleteAndRecombine(Trunc);
10841           // Replace the uses of SRL with SETCC
10842           WorklistRemover DeadNodes(*this);
10843           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10844           deleteAndRecombine(N1.getNode());
10845           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10846         }
10847       }
10848     }
10849 
10850     if (Trunc)
10851       // Restore N1 if the above transformation doesn't match.
10852       N1 = N->getOperand(1);
10853   }
10854 
10855   // Transform br(xor(x, y)) -> br(x != y)
10856   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10857   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10858     SDNode *TheXor = N1.getNode();
10859     SDValue Op0 = TheXor->getOperand(0);
10860     SDValue Op1 = TheXor->getOperand(1);
10861     if (Op0.getOpcode() == Op1.getOpcode()) {
10862       // Avoid missing important xor optimizations.
10863       if (SDValue Tmp = visitXOR(TheXor)) {
10864         if (Tmp.getNode() != TheXor) {
10865           DEBUG(dbgs() << "\nReplacing.8 ";
10866                 TheXor->dump(&DAG);
10867                 dbgs() << "\nWith: ";
10868                 Tmp.getNode()->dump(&DAG);
10869                 dbgs() << '\n');
10870           WorklistRemover DeadNodes(*this);
10871           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10872           deleteAndRecombine(TheXor);
10873           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10874                              MVT::Other, Chain, Tmp, N2);
10875         }
10876 
10877         // visitXOR has changed XOR's operands or replaced the XOR completely,
10878         // bail out.
10879         return SDValue(N, 0);
10880       }
10881     }
10882 
10883     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10884       bool Equal = false;
10885       if (isOneConstant(Op0) && Op0.hasOneUse() &&
10886           Op0.getOpcode() == ISD::XOR) {
10887         TheXor = Op0.getNode();
10888         Equal = true;
10889       }
10890 
10891       EVT SetCCVT = N1.getValueType();
10892       if (LegalTypes)
10893         SetCCVT = getSetCCResultType(SetCCVT);
10894       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10895                                    SetCCVT,
10896                                    Op0, Op1,
10897                                    Equal ? ISD::SETEQ : ISD::SETNE);
10898       // Replace the uses of XOR with SETCC
10899       WorklistRemover DeadNodes(*this);
10900       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10901       deleteAndRecombine(N1.getNode());
10902       return DAG.getNode(ISD::BRCOND, SDLoc(N),
10903                          MVT::Other, Chain, SetCC, N2);
10904     }
10905   }
10906 
10907   return SDValue();
10908 }
10909 
10910 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10911 //
10912 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10913   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10914   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10915 
10916   // If N is a constant we could fold this into a fallthrough or unconditional
10917   // branch. However that doesn't happen very often in normal code, because
10918   // Instcombine/SimplifyCFG should have handled the available opportunities.
10919   // If we did this folding here, it would be necessary to update the
10920   // MachineBasicBlock CFG, which is awkward.
10921 
10922   // Use SimplifySetCC to simplify SETCC's.
10923   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10924                                CondLHS, CondRHS, CC->get(), SDLoc(N),
10925                                false);
10926   if (Simp.getNode()) AddToWorklist(Simp.getNode());
10927 
10928   // fold to a simpler setcc
10929   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10930     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10931                        N->getOperand(0), Simp.getOperand(2),
10932                        Simp.getOperand(0), Simp.getOperand(1),
10933                        N->getOperand(4));
10934 
10935   return SDValue();
10936 }
10937 
10938 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10939 /// and that N may be folded in the load / store addressing mode.
10940 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10941                                     SelectionDAG &DAG,
10942                                     const TargetLowering &TLI) {
10943   EVT VT;
10944   unsigned AS;
10945 
10946   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
10947     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10948       return false;
10949     VT = LD->getMemoryVT();
10950     AS = LD->getAddressSpace();
10951   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
10952     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10953       return false;
10954     VT = ST->getMemoryVT();
10955     AS = ST->getAddressSpace();
10956   } else
10957     return false;
10958 
10959   TargetLowering::AddrMode AM;
10960   if (N->getOpcode() == ISD::ADD) {
10961     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10962     if (Offset)
10963       // [reg +/- imm]
10964       AM.BaseOffs = Offset->getSExtValue();
10965     else
10966       // [reg +/- reg]
10967       AM.Scale = 1;
10968   } else if (N->getOpcode() == ISD::SUB) {
10969     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10970     if (Offset)
10971       // [reg +/- imm]
10972       AM.BaseOffs = -Offset->getSExtValue();
10973     else
10974       // [reg +/- reg]
10975       AM.Scale = 1;
10976   } else
10977     return false;
10978 
10979   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10980                                    VT.getTypeForEVT(*DAG.getContext()), AS);
10981 }
10982 
10983 /// Try turning a load/store into a pre-indexed load/store when the base
10984 /// pointer is an add or subtract and it has other uses besides the load/store.
10985 /// After the transformation, the new indexed load/store has effectively folded
10986 /// the add/subtract in and all of its other uses are redirected to the
10987 /// new load/store.
10988 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10989   if (Level < AfterLegalizeDAG)
10990     return false;
10991 
10992   bool isLoad = true;
10993   SDValue Ptr;
10994   EVT VT;
10995   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10996     if (LD->isIndexed())
10997       return false;
10998     VT = LD->getMemoryVT();
10999     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
11000         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
11001       return false;
11002     Ptr = LD->getBasePtr();
11003   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11004     if (ST->isIndexed())
11005       return false;
11006     VT = ST->getMemoryVT();
11007     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
11008         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
11009       return false;
11010     Ptr = ST->getBasePtr();
11011     isLoad = false;
11012   } else {
11013     return false;
11014   }
11015 
11016   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
11017   // out.  There is no reason to make this a preinc/predec.
11018   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
11019       Ptr.getNode()->hasOneUse())
11020     return false;
11021 
11022   // Ask the target to do addressing mode selection.
11023   SDValue BasePtr;
11024   SDValue Offset;
11025   ISD::MemIndexedMode AM = ISD::UNINDEXED;
11026   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
11027     return false;
11028 
11029   // Backends without true r+i pre-indexed forms may need to pass a
11030   // constant base with a variable offset so that constant coercion
11031   // will work with the patterns in canonical form.
11032   bool Swapped = false;
11033   if (isa<ConstantSDNode>(BasePtr)) {
11034     std::swap(BasePtr, Offset);
11035     Swapped = true;
11036   }
11037 
11038   // Don't create a indexed load / store with zero offset.
11039   if (isNullConstant(Offset))
11040     return false;
11041 
11042   // Try turning it into a pre-indexed load / store except when:
11043   // 1) The new base ptr is a frame index.
11044   // 2) If N is a store and the new base ptr is either the same as or is a
11045   //    predecessor of the value being stored.
11046   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
11047   //    that would create a cycle.
11048   // 4) All uses are load / store ops that use it as old base ptr.
11049 
11050   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
11051   // (plus the implicit offset) to a register to preinc anyway.
11052   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11053     return false;
11054 
11055   // Check #2.
11056   if (!isLoad) {
11057     SDValue Val = cast<StoreSDNode>(N)->getValue();
11058     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11059       return false;
11060   }
11061 
11062   // Caches for hasPredecessorHelper.
11063   SmallPtrSet<const SDNode *, 32> Visited;
11064   SmallVector<const SDNode *, 16> Worklist;
11065   Worklist.push_back(N);
11066 
11067   // If the offset is a constant, there may be other adds of constants that
11068   // can be folded with this one. We should do this to avoid having to keep
11069   // a copy of the original base pointer.
11070   SmallVector<SDNode *, 16> OtherUses;
11071   if (isa<ConstantSDNode>(Offset))
11072     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11073                               UE = BasePtr.getNode()->use_end();
11074          UI != UE; ++UI) {
11075       SDUse &Use = UI.getUse();
11076       // Skip the use that is Ptr and uses of other results from BasePtr's
11077       // node (important for nodes that return multiple results).
11078       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11079         continue;
11080 
11081       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11082         continue;
11083 
11084       if (Use.getUser()->getOpcode() != ISD::ADD &&
11085           Use.getUser()->getOpcode() != ISD::SUB) {
11086         OtherUses.clear();
11087         break;
11088       }
11089 
11090       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11091       if (!isa<ConstantSDNode>(Op1)) {
11092         OtherUses.clear();
11093         break;
11094       }
11095 
11096       // FIXME: In some cases, we can be smarter about this.
11097       if (Op1.getValueType() != Offset.getValueType()) {
11098         OtherUses.clear();
11099         break;
11100       }
11101 
11102       OtherUses.push_back(Use.getUser());
11103     }
11104 
11105   if (Swapped)
11106     std::swap(BasePtr, Offset);
11107 
11108   // Now check for #3 and #4.
11109   bool RealUse = false;
11110 
11111   for (SDNode *Use : Ptr.getNode()->uses()) {
11112     if (Use == N)
11113       continue;
11114     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11115       return false;
11116 
11117     // If Ptr may be folded in addressing mode of other use, then it's
11118     // not profitable to do this transformation.
11119     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11120       RealUse = true;
11121   }
11122 
11123   if (!RealUse)
11124     return false;
11125 
11126   SDValue Result;
11127   if (isLoad)
11128     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11129                                 BasePtr, Offset, AM);
11130   else
11131     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11132                                  BasePtr, Offset, AM);
11133   ++PreIndexedNodes;
11134   ++NodesCombined;
11135   DEBUG(dbgs() << "\nReplacing.4 ";
11136         N->dump(&DAG);
11137         dbgs() << "\nWith: ";
11138         Result.getNode()->dump(&DAG);
11139         dbgs() << '\n');
11140   WorklistRemover DeadNodes(*this);
11141   if (isLoad) {
11142     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11143     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11144   } else {
11145     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11146   }
11147 
11148   // Finally, since the node is now dead, remove it from the graph.
11149   deleteAndRecombine(N);
11150 
11151   if (Swapped)
11152     std::swap(BasePtr, Offset);
11153 
11154   // Replace other uses of BasePtr that can be updated to use Ptr
11155   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11156     unsigned OffsetIdx = 1;
11157     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11158       OffsetIdx = 0;
11159     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11160            BasePtr.getNode() && "Expected BasePtr operand");
11161 
11162     // We need to replace ptr0 in the following expression:
11163     //   x0 * offset0 + y0 * ptr0 = t0
11164     // knowing that
11165     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11166     //
11167     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11168     // indexed load/store and the expression that needs to be re-written.
11169     //
11170     // Therefore, we have:
11171     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11172 
11173     ConstantSDNode *CN =
11174       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11175     int X0, X1, Y0, Y1;
11176     const APInt &Offset0 = CN->getAPIntValue();
11177     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11178 
11179     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11180     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11181     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11182     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11183 
11184     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11185 
11186     APInt CNV = Offset0;
11187     if (X0 < 0) CNV = -CNV;
11188     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11189     else CNV = CNV - Offset1;
11190 
11191     SDLoc DL(OtherUses[i]);
11192 
11193     // We can now generate the new expression.
11194     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11195     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11196 
11197     SDValue NewUse = DAG.getNode(Opcode,
11198                                  DL,
11199                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11200     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11201     deleteAndRecombine(OtherUses[i]);
11202   }
11203 
11204   // Replace the uses of Ptr with uses of the updated base value.
11205   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11206   deleteAndRecombine(Ptr.getNode());
11207 
11208   return true;
11209 }
11210 
11211 /// Try to combine a load/store with a add/sub of the base pointer node into a
11212 /// post-indexed load/store. The transformation folded the add/subtract into the
11213 /// new indexed load/store effectively and all of its uses are redirected to the
11214 /// new load/store.
11215 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11216   if (Level < AfterLegalizeDAG)
11217     return false;
11218 
11219   bool isLoad = true;
11220   SDValue Ptr;
11221   EVT VT;
11222   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11223     if (LD->isIndexed())
11224       return false;
11225     VT = LD->getMemoryVT();
11226     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11227         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11228       return false;
11229     Ptr = LD->getBasePtr();
11230   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11231     if (ST->isIndexed())
11232       return false;
11233     VT = ST->getMemoryVT();
11234     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11235         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11236       return false;
11237     Ptr = ST->getBasePtr();
11238     isLoad = false;
11239   } else {
11240     return false;
11241   }
11242 
11243   if (Ptr.getNode()->hasOneUse())
11244     return false;
11245 
11246   for (SDNode *Op : Ptr.getNode()->uses()) {
11247     if (Op == N ||
11248         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11249       continue;
11250 
11251     SDValue BasePtr;
11252     SDValue Offset;
11253     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11254     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11255       // Don't create a indexed load / store with zero offset.
11256       if (isNullConstant(Offset))
11257         continue;
11258 
11259       // Try turning it into a post-indexed load / store except when
11260       // 1) All uses are load / store ops that use it as base ptr (and
11261       //    it may be folded as addressing mmode).
11262       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11263       //    nor a successor of N. Otherwise, if Op is folded that would
11264       //    create a cycle.
11265 
11266       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11267         continue;
11268 
11269       // Check for #1.
11270       bool TryNext = false;
11271       for (SDNode *Use : BasePtr.getNode()->uses()) {
11272         if (Use == Ptr.getNode())
11273           continue;
11274 
11275         // If all the uses are load / store addresses, then don't do the
11276         // transformation.
11277         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11278           bool RealUse = false;
11279           for (SDNode *UseUse : Use->uses()) {
11280             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11281               RealUse = true;
11282           }
11283 
11284           if (!RealUse) {
11285             TryNext = true;
11286             break;
11287           }
11288         }
11289       }
11290 
11291       if (TryNext)
11292         continue;
11293 
11294       // Check for #2
11295       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11296         SDValue Result = isLoad
11297           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11298                                BasePtr, Offset, AM)
11299           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11300                                 BasePtr, Offset, AM);
11301         ++PostIndexedNodes;
11302         ++NodesCombined;
11303         DEBUG(dbgs() << "\nReplacing.5 ";
11304               N->dump(&DAG);
11305               dbgs() << "\nWith: ";
11306               Result.getNode()->dump(&DAG);
11307               dbgs() << '\n');
11308         WorklistRemover DeadNodes(*this);
11309         if (isLoad) {
11310           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11311           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11312         } else {
11313           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11314         }
11315 
11316         // Finally, since the node is now dead, remove it from the graph.
11317         deleteAndRecombine(N);
11318 
11319         // Replace the uses of Use with uses of the updated base value.
11320         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11321                                       Result.getValue(isLoad ? 1 : 0));
11322         deleteAndRecombine(Op);
11323         return true;
11324       }
11325     }
11326   }
11327 
11328   return false;
11329 }
11330 
11331 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11332 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11333   ISD::MemIndexedMode AM = LD->getAddressingMode();
11334   assert(AM != ISD::UNINDEXED);
11335   SDValue BP = LD->getOperand(1);
11336   SDValue Inc = LD->getOperand(2);
11337 
11338   // Some backends use TargetConstants for load offsets, but don't expect
11339   // TargetConstants in general ADD nodes. We can convert these constants into
11340   // regular Constants (if the constant is not opaque).
11341   assert((Inc.getOpcode() != ISD::TargetConstant ||
11342           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11343          "Cannot split out indexing using opaque target constants");
11344   if (Inc.getOpcode() == ISD::TargetConstant) {
11345     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11346     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11347                           ConstInc->getValueType(0));
11348   }
11349 
11350   unsigned Opc =
11351       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11352   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11353 }
11354 
11355 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11356   LoadSDNode *LD  = cast<LoadSDNode>(N);
11357   SDValue Chain = LD->getChain();
11358   SDValue Ptr   = LD->getBasePtr();
11359 
11360   // If load is not volatile and there are no uses of the loaded value (and
11361   // the updated indexed value in case of indexed loads), change uses of the
11362   // chain value into uses of the chain input (i.e. delete the dead load).
11363   if (!LD->isVolatile()) {
11364     if (N->getValueType(1) == MVT::Other) {
11365       // Unindexed loads.
11366       if (!N->hasAnyUseOfValue(0)) {
11367         // It's not safe to use the two value CombineTo variant here. e.g.
11368         // v1, chain2 = load chain1, loc
11369         // v2, chain3 = load chain2, loc
11370         // v3         = add v2, c
11371         // Now we replace use of chain2 with chain1.  This makes the second load
11372         // isomorphic to the one we are deleting, and thus makes this load live.
11373         DEBUG(dbgs() << "\nReplacing.6 ";
11374               N->dump(&DAG);
11375               dbgs() << "\nWith chain: ";
11376               Chain.getNode()->dump(&DAG);
11377               dbgs() << "\n");
11378         WorklistRemover DeadNodes(*this);
11379         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11380         AddUsersToWorklist(Chain.getNode());
11381         if (N->use_empty())
11382           deleteAndRecombine(N);
11383 
11384         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11385       }
11386     } else {
11387       // Indexed loads.
11388       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11389 
11390       // If this load has an opaque TargetConstant offset, then we cannot split
11391       // the indexing into an add/sub directly (that TargetConstant may not be
11392       // valid for a different type of node, and we cannot convert an opaque
11393       // target constant into a regular constant).
11394       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11395                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11396 
11397       if (!N->hasAnyUseOfValue(0) &&
11398           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11399         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11400         SDValue Index;
11401         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11402           Index = SplitIndexingFromLoad(LD);
11403           // Try to fold the base pointer arithmetic into subsequent loads and
11404           // stores.
11405           AddUsersToWorklist(N);
11406         } else
11407           Index = DAG.getUNDEF(N->getValueType(1));
11408         DEBUG(dbgs() << "\nReplacing.7 ";
11409               N->dump(&DAG);
11410               dbgs() << "\nWith: ";
11411               Undef.getNode()->dump(&DAG);
11412               dbgs() << " and 2 other values\n");
11413         WorklistRemover DeadNodes(*this);
11414         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11415         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11416         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11417         deleteAndRecombine(N);
11418         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11419       }
11420     }
11421   }
11422 
11423   // If this load is directly stored, replace the load value with the stored
11424   // value.
11425   // TODO: Handle store large -> read small portion.
11426   // TODO: Handle TRUNCSTORE/LOADEXT
11427   if (OptLevel != CodeGenOpt::None &&
11428       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11429     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11430       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11431       if (PrevST->getBasePtr() == Ptr &&
11432           PrevST->getValue().getValueType() == N->getValueType(0))
11433         return CombineTo(N, PrevST->getOperand(1), Chain);
11434     }
11435   }
11436 
11437   // Try to infer better alignment information than the load already has.
11438   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11439     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11440       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11441         SDValue NewLoad = DAG.getExtLoad(
11442             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11443             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11444             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11445         if (NewLoad.getNode() != N)
11446           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11447       }
11448     }
11449   }
11450 
11451   if (LD->isUnindexed()) {
11452     // Walk up chain skipping non-aliasing memory nodes.
11453     SDValue BetterChain = FindBetterChain(N, Chain);
11454 
11455     // If there is a better chain.
11456     if (Chain != BetterChain) {
11457       SDValue ReplLoad;
11458 
11459       // Replace the chain to void dependency.
11460       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11461         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11462                                BetterChain, Ptr, LD->getMemOperand());
11463       } else {
11464         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11465                                   LD->getValueType(0),
11466                                   BetterChain, Ptr, LD->getMemoryVT(),
11467                                   LD->getMemOperand());
11468       }
11469 
11470       // Create token factor to keep old chain connected.
11471       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11472                                   MVT::Other, Chain, ReplLoad.getValue(1));
11473 
11474       // Replace uses with load result and token factor
11475       return CombineTo(N, ReplLoad.getValue(0), Token);
11476     }
11477   }
11478 
11479   // Try transforming N to an indexed load.
11480   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11481     return SDValue(N, 0);
11482 
11483   // Try to slice up N to more direct loads if the slices are mapped to
11484   // different register banks or pairing can take place.
11485   if (SliceUpLoad(N))
11486     return SDValue(N, 0);
11487 
11488   return SDValue();
11489 }
11490 
11491 namespace {
11492 /// \brief Helper structure used to slice a load in smaller loads.
11493 /// Basically a slice is obtained from the following sequence:
11494 /// Origin = load Ty1, Base
11495 /// Shift = srl Ty1 Origin, CstTy Amount
11496 /// Inst = trunc Shift to Ty2
11497 ///
11498 /// Then, it will be rewritten into:
11499 /// Slice = load SliceTy, Base + SliceOffset
11500 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11501 ///
11502 /// SliceTy is deduced from the number of bits that are actually used to
11503 /// build Inst.
11504 struct LoadedSlice {
11505   /// \brief Helper structure used to compute the cost of a slice.
11506   struct Cost {
11507     /// Are we optimizing for code size.
11508     bool ForCodeSize;
11509     /// Various cost.
11510     unsigned Loads;
11511     unsigned Truncates;
11512     unsigned CrossRegisterBanksCopies;
11513     unsigned ZExts;
11514     unsigned Shift;
11515 
11516     Cost(bool ForCodeSize = false)
11517         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11518           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11519 
11520     /// \brief Get the cost of one isolated slice.
11521     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11522         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11523           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11524       EVT TruncType = LS.Inst->getValueType(0);
11525       EVT LoadedType = LS.getLoadedType();
11526       if (TruncType != LoadedType &&
11527           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11528         ZExts = 1;
11529     }
11530 
11531     /// \brief Account for slicing gain in the current cost.
11532     /// Slicing provide a few gains like removing a shift or a
11533     /// truncate. This method allows to grow the cost of the original
11534     /// load with the gain from this slice.
11535     void addSliceGain(const LoadedSlice &LS) {
11536       // Each slice saves a truncate.
11537       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11538       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11539                               LS.Inst->getValueType(0)))
11540         ++Truncates;
11541       // If there is a shift amount, this slice gets rid of it.
11542       if (LS.Shift)
11543         ++Shift;
11544       // If this slice can merge a cross register bank copy, account for it.
11545       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11546         ++CrossRegisterBanksCopies;
11547     }
11548 
11549     Cost &operator+=(const Cost &RHS) {
11550       Loads += RHS.Loads;
11551       Truncates += RHS.Truncates;
11552       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11553       ZExts += RHS.ZExts;
11554       Shift += RHS.Shift;
11555       return *this;
11556     }
11557 
11558     bool operator==(const Cost &RHS) const {
11559       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11560              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11561              ZExts == RHS.ZExts && Shift == RHS.Shift;
11562     }
11563 
11564     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11565 
11566     bool operator<(const Cost &RHS) const {
11567       // Assume cross register banks copies are as expensive as loads.
11568       // FIXME: Do we want some more target hooks?
11569       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11570       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11571       // Unless we are optimizing for code size, consider the
11572       // expensive operation first.
11573       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11574         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11575       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11576              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11577     }
11578 
11579     bool operator>(const Cost &RHS) const { return RHS < *this; }
11580 
11581     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11582 
11583     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11584   };
11585   // The last instruction that represent the slice. This should be a
11586   // truncate instruction.
11587   SDNode *Inst;
11588   // The original load instruction.
11589   LoadSDNode *Origin;
11590   // The right shift amount in bits from the original load.
11591   unsigned Shift;
11592   // The DAG from which Origin came from.
11593   // This is used to get some contextual information about legal types, etc.
11594   SelectionDAG *DAG;
11595 
11596   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11597               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11598       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11599 
11600   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11601   /// \return Result is \p BitWidth and has used bits set to 1 and
11602   ///         not used bits set to 0.
11603   APInt getUsedBits() const {
11604     // Reproduce the trunc(lshr) sequence:
11605     // - Start from the truncated value.
11606     // - Zero extend to the desired bit width.
11607     // - Shift left.
11608     assert(Origin && "No original load to compare against.");
11609     unsigned BitWidth = Origin->getValueSizeInBits(0);
11610     assert(Inst && "This slice is not bound to an instruction");
11611     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11612            "Extracted slice is bigger than the whole type!");
11613     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11614     UsedBits.setAllBits();
11615     UsedBits = UsedBits.zext(BitWidth);
11616     UsedBits <<= Shift;
11617     return UsedBits;
11618   }
11619 
11620   /// \brief Get the size of the slice to be loaded in bytes.
11621   unsigned getLoadedSize() const {
11622     unsigned SliceSize = getUsedBits().countPopulation();
11623     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11624     return SliceSize / 8;
11625   }
11626 
11627   /// \brief Get the type that will be loaded for this slice.
11628   /// Note: This may not be the final type for the slice.
11629   EVT getLoadedType() const {
11630     assert(DAG && "Missing context");
11631     LLVMContext &Ctxt = *DAG->getContext();
11632     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11633   }
11634 
11635   /// \brief Get the alignment of the load used for this slice.
11636   unsigned getAlignment() const {
11637     unsigned Alignment = Origin->getAlignment();
11638     unsigned Offset = getOffsetFromBase();
11639     if (Offset != 0)
11640       Alignment = MinAlign(Alignment, Alignment + Offset);
11641     return Alignment;
11642   }
11643 
11644   /// \brief Check if this slice can be rewritten with legal operations.
11645   bool isLegal() const {
11646     // An invalid slice is not legal.
11647     if (!Origin || !Inst || !DAG)
11648       return false;
11649 
11650     // Offsets are for indexed load only, we do not handle that.
11651     if (!Origin->getOffset().isUndef())
11652       return false;
11653 
11654     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11655 
11656     // Check that the type is legal.
11657     EVT SliceType = getLoadedType();
11658     if (!TLI.isTypeLegal(SliceType))
11659       return false;
11660 
11661     // Check that the load is legal for this type.
11662     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11663       return false;
11664 
11665     // Check that the offset can be computed.
11666     // 1. Check its type.
11667     EVT PtrType = Origin->getBasePtr().getValueType();
11668     if (PtrType == MVT::Untyped || PtrType.isExtended())
11669       return false;
11670 
11671     // 2. Check that it fits in the immediate.
11672     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11673       return false;
11674 
11675     // 3. Check that the computation is legal.
11676     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11677       return false;
11678 
11679     // Check that the zext is legal if it needs one.
11680     EVT TruncateType = Inst->getValueType(0);
11681     if (TruncateType != SliceType &&
11682         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11683       return false;
11684 
11685     return true;
11686   }
11687 
11688   /// \brief Get the offset in bytes of this slice in the original chunk of
11689   /// bits.
11690   /// \pre DAG != nullptr.
11691   uint64_t getOffsetFromBase() const {
11692     assert(DAG && "Missing context.");
11693     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11694     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11695     uint64_t Offset = Shift / 8;
11696     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11697     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11698            "The size of the original loaded type is not a multiple of a"
11699            " byte.");
11700     // If Offset is bigger than TySizeInBytes, it means we are loading all
11701     // zeros. This should have been optimized before in the process.
11702     assert(TySizeInBytes > Offset &&
11703            "Invalid shift amount for given loaded size");
11704     if (IsBigEndian)
11705       Offset = TySizeInBytes - Offset - getLoadedSize();
11706     return Offset;
11707   }
11708 
11709   /// \brief Generate the sequence of instructions to load the slice
11710   /// represented by this object and redirect the uses of this slice to
11711   /// this new sequence of instructions.
11712   /// \pre this->Inst && this->Origin are valid Instructions and this
11713   /// object passed the legal check: LoadedSlice::isLegal returned true.
11714   /// \return The last instruction of the sequence used to load the slice.
11715   SDValue loadSlice() const {
11716     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11717     const SDValue &OldBaseAddr = Origin->getBasePtr();
11718     SDValue BaseAddr = OldBaseAddr;
11719     // Get the offset in that chunk of bytes w.r.t. the endianness.
11720     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11721     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11722     if (Offset) {
11723       // BaseAddr = BaseAddr + Offset.
11724       EVT ArithType = BaseAddr.getValueType();
11725       SDLoc DL(Origin);
11726       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11727                               DAG->getConstant(Offset, DL, ArithType));
11728     }
11729 
11730     // Create the type of the loaded slice according to its size.
11731     EVT SliceType = getLoadedType();
11732 
11733     // Create the load for the slice.
11734     SDValue LastInst =
11735         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11736                      Origin->getPointerInfo().getWithOffset(Offset),
11737                      getAlignment(), Origin->getMemOperand()->getFlags());
11738     // If the final type is not the same as the loaded type, this means that
11739     // we have to pad with zero. Create a zero extend for that.
11740     EVT FinalType = Inst->getValueType(0);
11741     if (SliceType != FinalType)
11742       LastInst =
11743           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11744     return LastInst;
11745   }
11746 
11747   /// \brief Check if this slice can be merged with an expensive cross register
11748   /// bank copy. E.g.,
11749   /// i = load i32
11750   /// f = bitcast i32 i to float
11751   bool canMergeExpensiveCrossRegisterBankCopy() const {
11752     if (!Inst || !Inst->hasOneUse())
11753       return false;
11754     SDNode *Use = *Inst->use_begin();
11755     if (Use->getOpcode() != ISD::BITCAST)
11756       return false;
11757     assert(DAG && "Missing context");
11758     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11759     EVT ResVT = Use->getValueType(0);
11760     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11761     const TargetRegisterClass *ArgRC =
11762         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11763     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11764       return false;
11765 
11766     // At this point, we know that we perform a cross-register-bank copy.
11767     // Check if it is expensive.
11768     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11769     // Assume bitcasts are cheap, unless both register classes do not
11770     // explicitly share a common sub class.
11771     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11772       return false;
11773 
11774     // Check if it will be merged with the load.
11775     // 1. Check the alignment constraint.
11776     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11777         ResVT.getTypeForEVT(*DAG->getContext()));
11778 
11779     if (RequiredAlignment > getAlignment())
11780       return false;
11781 
11782     // 2. Check that the load is a legal operation for that type.
11783     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11784       return false;
11785 
11786     // 3. Check that we do not have a zext in the way.
11787     if (Inst->getValueType(0) != getLoadedType())
11788       return false;
11789 
11790     return true;
11791   }
11792 };
11793 }
11794 
11795 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11796 /// \p UsedBits looks like 0..0 1..1 0..0.
11797 static bool areUsedBitsDense(const APInt &UsedBits) {
11798   // If all the bits are one, this is dense!
11799   if (UsedBits.isAllOnesValue())
11800     return true;
11801 
11802   // Get rid of the unused bits on the right.
11803   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11804   // Get rid of the unused bits on the left.
11805   if (NarrowedUsedBits.countLeadingZeros())
11806     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11807   // Check that the chunk of bits is completely used.
11808   return NarrowedUsedBits.isAllOnesValue();
11809 }
11810 
11811 /// \brief Check whether or not \p First and \p Second are next to each other
11812 /// in memory. This means that there is no hole between the bits loaded
11813 /// by \p First and the bits loaded by \p Second.
11814 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11815                                      const LoadedSlice &Second) {
11816   assert(First.Origin == Second.Origin && First.Origin &&
11817          "Unable to match different memory origins.");
11818   APInt UsedBits = First.getUsedBits();
11819   assert((UsedBits & Second.getUsedBits()) == 0 &&
11820          "Slices are not supposed to overlap.");
11821   UsedBits |= Second.getUsedBits();
11822   return areUsedBitsDense(UsedBits);
11823 }
11824 
11825 /// \brief Adjust the \p GlobalLSCost according to the target
11826 /// paring capabilities and the layout of the slices.
11827 /// \pre \p GlobalLSCost should account for at least as many loads as
11828 /// there is in the slices in \p LoadedSlices.
11829 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11830                                  LoadedSlice::Cost &GlobalLSCost) {
11831   unsigned NumberOfSlices = LoadedSlices.size();
11832   // If there is less than 2 elements, no pairing is possible.
11833   if (NumberOfSlices < 2)
11834     return;
11835 
11836   // Sort the slices so that elements that are likely to be next to each
11837   // other in memory are next to each other in the list.
11838   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11839             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11840     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11841     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11842   });
11843   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11844   // First (resp. Second) is the first (resp. Second) potentially candidate
11845   // to be placed in a paired load.
11846   const LoadedSlice *First = nullptr;
11847   const LoadedSlice *Second = nullptr;
11848   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11849                 // Set the beginning of the pair.
11850                                                            First = Second) {
11851 
11852     Second = &LoadedSlices[CurrSlice];
11853 
11854     // If First is NULL, it means we start a new pair.
11855     // Get to the next slice.
11856     if (!First)
11857       continue;
11858 
11859     EVT LoadedType = First->getLoadedType();
11860 
11861     // If the types of the slices are different, we cannot pair them.
11862     if (LoadedType != Second->getLoadedType())
11863       continue;
11864 
11865     // Check if the target supplies paired loads for this type.
11866     unsigned RequiredAlignment = 0;
11867     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11868       // move to the next pair, this type is hopeless.
11869       Second = nullptr;
11870       continue;
11871     }
11872     // Check if we meet the alignment requirement.
11873     if (RequiredAlignment > First->getAlignment())
11874       continue;
11875 
11876     // Check that both loads are next to each other in memory.
11877     if (!areSlicesNextToEachOther(*First, *Second))
11878       continue;
11879 
11880     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11881     --GlobalLSCost.Loads;
11882     // Move to the next pair.
11883     Second = nullptr;
11884   }
11885 }
11886 
11887 /// \brief Check the profitability of all involved LoadedSlice.
11888 /// Currently, it is considered profitable if there is exactly two
11889 /// involved slices (1) which are (2) next to each other in memory, and
11890 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11891 ///
11892 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11893 /// the elements themselves.
11894 ///
11895 /// FIXME: When the cost model will be mature enough, we can relax
11896 /// constraints (1) and (2).
11897 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11898                                 const APInt &UsedBits, bool ForCodeSize) {
11899   unsigned NumberOfSlices = LoadedSlices.size();
11900   if (StressLoadSlicing)
11901     return NumberOfSlices > 1;
11902 
11903   // Check (1).
11904   if (NumberOfSlices != 2)
11905     return false;
11906 
11907   // Check (2).
11908   if (!areUsedBitsDense(UsedBits))
11909     return false;
11910 
11911   // Check (3).
11912   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11913   // The original code has one big load.
11914   OrigCost.Loads = 1;
11915   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11916     const LoadedSlice &LS = LoadedSlices[CurrSlice];
11917     // Accumulate the cost of all the slices.
11918     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11919     GlobalSlicingCost += SliceCost;
11920 
11921     // Account as cost in the original configuration the gain obtained
11922     // with the current slices.
11923     OrigCost.addSliceGain(LS);
11924   }
11925 
11926   // If the target supports paired load, adjust the cost accordingly.
11927   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11928   return OrigCost > GlobalSlicingCost;
11929 }
11930 
11931 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11932 /// operations, split it in the various pieces being extracted.
11933 ///
11934 /// This sort of thing is introduced by SROA.
11935 /// This slicing takes care not to insert overlapping loads.
11936 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11937 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11938   if (Level < AfterLegalizeDAG)
11939     return false;
11940 
11941   LoadSDNode *LD = cast<LoadSDNode>(N);
11942   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11943       !LD->getValueType(0).isInteger())
11944     return false;
11945 
11946   // Keep track of already used bits to detect overlapping values.
11947   // In that case, we will just abort the transformation.
11948   APInt UsedBits(LD->getValueSizeInBits(0), 0);
11949 
11950   SmallVector<LoadedSlice, 4> LoadedSlices;
11951 
11952   // Check if this load is used as several smaller chunks of bits.
11953   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11954   // of computation for each trunc.
11955   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11956        UI != UIEnd; ++UI) {
11957     // Skip the uses of the chain.
11958     if (UI.getUse().getResNo() != 0)
11959       continue;
11960 
11961     SDNode *User = *UI;
11962     unsigned Shift = 0;
11963 
11964     // Check if this is a trunc(lshr).
11965     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11966         isa<ConstantSDNode>(User->getOperand(1))) {
11967       Shift = User->getConstantOperandVal(1);
11968       User = *User->use_begin();
11969     }
11970 
11971     // At this point, User is a Truncate, iff we encountered, trunc or
11972     // trunc(lshr).
11973     if (User->getOpcode() != ISD::TRUNCATE)
11974       return false;
11975 
11976     // The width of the type must be a power of 2 and greater than 8-bits.
11977     // Otherwise the load cannot be represented in LLVM IR.
11978     // Moreover, if we shifted with a non-8-bits multiple, the slice
11979     // will be across several bytes. We do not support that.
11980     unsigned Width = User->getValueSizeInBits(0);
11981     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11982       return 0;
11983 
11984     // Build the slice for this chain of computations.
11985     LoadedSlice LS(User, LD, Shift, &DAG);
11986     APInt CurrentUsedBits = LS.getUsedBits();
11987 
11988     // Check if this slice overlaps with another.
11989     if ((CurrentUsedBits & UsedBits) != 0)
11990       return false;
11991     // Update the bits used globally.
11992     UsedBits |= CurrentUsedBits;
11993 
11994     // Check if the new slice would be legal.
11995     if (!LS.isLegal())
11996       return false;
11997 
11998     // Record the slice.
11999     LoadedSlices.push_back(LS);
12000   }
12001 
12002   // Abort slicing if it does not seem to be profitable.
12003   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
12004     return false;
12005 
12006   ++SlicedLoads;
12007 
12008   // Rewrite each chain to use an independent load.
12009   // By construction, each chain can be represented by a unique load.
12010 
12011   // Prepare the argument for the new token factor for all the slices.
12012   SmallVector<SDValue, 8> ArgChains;
12013   for (SmallVectorImpl<LoadedSlice>::const_iterator
12014            LSIt = LoadedSlices.begin(),
12015            LSItEnd = LoadedSlices.end();
12016        LSIt != LSItEnd; ++LSIt) {
12017     SDValue SliceInst = LSIt->loadSlice();
12018     CombineTo(LSIt->Inst, SliceInst, true);
12019     if (SliceInst.getOpcode() != ISD::LOAD)
12020       SliceInst = SliceInst.getOperand(0);
12021     assert(SliceInst->getOpcode() == ISD::LOAD &&
12022            "It takes more than a zext to get to the loaded slice!!");
12023     ArgChains.push_back(SliceInst.getValue(1));
12024   }
12025 
12026   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
12027                               ArgChains);
12028   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
12029   AddToWorklist(Chain.getNode());
12030   return true;
12031 }
12032 
12033 /// Check to see if V is (and load (ptr), imm), where the load is having
12034 /// specific bytes cleared out.  If so, return the byte size being masked out
12035 /// and the shift amount.
12036 static std::pair<unsigned, unsigned>
12037 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
12038   std::pair<unsigned, unsigned> Result(0, 0);
12039 
12040   // Check for the structure we're looking for.
12041   if (V->getOpcode() != ISD::AND ||
12042       !isa<ConstantSDNode>(V->getOperand(1)) ||
12043       !ISD::isNormalLoad(V->getOperand(0).getNode()))
12044     return Result;
12045 
12046   // Check the chain and pointer.
12047   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
12048   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
12049 
12050   // The store should be chained directly to the load or be an operand of a
12051   // tokenfactor.
12052   if (LD == Chain.getNode())
12053     ; // ok.
12054   else if (Chain->getOpcode() != ISD::TokenFactor)
12055     return Result; // Fail.
12056   else {
12057     bool isOk = false;
12058     for (const SDValue &ChainOp : Chain->op_values())
12059       if (ChainOp.getNode() == LD) {
12060         isOk = true;
12061         break;
12062       }
12063     if (!isOk) return Result;
12064   }
12065 
12066   // This only handles simple types.
12067   if (V.getValueType() != MVT::i16 &&
12068       V.getValueType() != MVT::i32 &&
12069       V.getValueType() != MVT::i64)
12070     return Result;
12071 
12072   // Check the constant mask.  Invert it so that the bits being masked out are
12073   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
12074   // follow the sign bit for uniformity.
12075   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12076   unsigned NotMaskLZ = countLeadingZeros(NotMask);
12077   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
12078   unsigned NotMaskTZ = countTrailingZeros(NotMask);
12079   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
12080   if (NotMaskLZ == 64) return Result;  // All zero mask.
12081 
12082   // See if we have a continuous run of bits.  If so, we have 0*1+0*
12083   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12084     return Result;
12085 
12086   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12087   if (V.getValueType() != MVT::i64 && NotMaskLZ)
12088     NotMaskLZ -= 64-V.getValueSizeInBits();
12089 
12090   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12091   switch (MaskedBytes) {
12092   case 1:
12093   case 2:
12094   case 4: break;
12095   default: return Result; // All one mask, or 5-byte mask.
12096   }
12097 
12098   // Verify that the first bit starts at a multiple of mask so that the access
12099   // is aligned the same as the access width.
12100   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12101 
12102   Result.first = MaskedBytes;
12103   Result.second = NotMaskTZ/8;
12104   return Result;
12105 }
12106 
12107 
12108 /// Check to see if IVal is something that provides a value as specified by
12109 /// MaskInfo. If so, replace the specified store with a narrower store of
12110 /// truncated IVal.
12111 static SDNode *
12112 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12113                                 SDValue IVal, StoreSDNode *St,
12114                                 DAGCombiner *DC) {
12115   unsigned NumBytes = MaskInfo.first;
12116   unsigned ByteShift = MaskInfo.second;
12117   SelectionDAG &DAG = DC->getDAG();
12118 
12119   // Check to see if IVal is all zeros in the part being masked in by the 'or'
12120   // that uses this.  If not, this is not a replacement.
12121   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12122                                   ByteShift*8, (ByteShift+NumBytes)*8);
12123   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12124 
12125   // Check that it is legal on the target to do this.  It is legal if the new
12126   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12127   // legalization.
12128   MVT VT = MVT::getIntegerVT(NumBytes*8);
12129   if (!DC->isTypeLegal(VT))
12130     return nullptr;
12131 
12132   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12133   // shifted by ByteShift and truncated down to NumBytes.
12134   if (ByteShift) {
12135     SDLoc DL(IVal);
12136     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12137                        DAG.getConstant(ByteShift*8, DL,
12138                                     DC->getShiftAmountTy(IVal.getValueType())));
12139   }
12140 
12141   // Figure out the offset for the store and the alignment of the access.
12142   unsigned StOffset;
12143   unsigned NewAlign = St->getAlignment();
12144 
12145   if (DAG.getDataLayout().isLittleEndian())
12146     StOffset = ByteShift;
12147   else
12148     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12149 
12150   SDValue Ptr = St->getBasePtr();
12151   if (StOffset) {
12152     SDLoc DL(IVal);
12153     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12154                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12155     NewAlign = MinAlign(NewAlign, StOffset);
12156   }
12157 
12158   // Truncate down to the new size.
12159   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12160 
12161   ++OpsNarrowed;
12162   return DAG
12163       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12164                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12165       .getNode();
12166 }
12167 
12168 
12169 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12170 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12171 /// narrowing the load and store if it would end up being a win for performance
12172 /// or code size.
12173 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12174   StoreSDNode *ST  = cast<StoreSDNode>(N);
12175   if (ST->isVolatile())
12176     return SDValue();
12177 
12178   SDValue Chain = ST->getChain();
12179   SDValue Value = ST->getValue();
12180   SDValue Ptr   = ST->getBasePtr();
12181   EVT VT = Value.getValueType();
12182 
12183   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12184     return SDValue();
12185 
12186   unsigned Opc = Value.getOpcode();
12187 
12188   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12189   // is a byte mask indicating a consecutive number of bytes, check to see if
12190   // Y is known to provide just those bytes.  If so, we try to replace the
12191   // load + replace + store sequence with a single (narrower) store, which makes
12192   // the load dead.
12193   if (Opc == ISD::OR) {
12194     std::pair<unsigned, unsigned> MaskedLoad;
12195     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12196     if (MaskedLoad.first)
12197       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12198                                                   Value.getOperand(1), ST,this))
12199         return SDValue(NewST, 0);
12200 
12201     // Or is commutative, so try swapping X and Y.
12202     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12203     if (MaskedLoad.first)
12204       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12205                                                   Value.getOperand(0), ST,this))
12206         return SDValue(NewST, 0);
12207   }
12208 
12209   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12210       Value.getOperand(1).getOpcode() != ISD::Constant)
12211     return SDValue();
12212 
12213   SDValue N0 = Value.getOperand(0);
12214   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12215       Chain == SDValue(N0.getNode(), 1)) {
12216     LoadSDNode *LD = cast<LoadSDNode>(N0);
12217     if (LD->getBasePtr() != Ptr ||
12218         LD->getPointerInfo().getAddrSpace() !=
12219         ST->getPointerInfo().getAddrSpace())
12220       return SDValue();
12221 
12222     // Find the type to narrow it the load / op / store to.
12223     SDValue N1 = Value.getOperand(1);
12224     unsigned BitWidth = N1.getValueSizeInBits();
12225     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12226     if (Opc == ISD::AND)
12227       Imm ^= APInt::getAllOnesValue(BitWidth);
12228     if (Imm == 0 || Imm.isAllOnesValue())
12229       return SDValue();
12230     unsigned ShAmt = Imm.countTrailingZeros();
12231     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12232     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12233     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12234     // The narrowing should be profitable, the load/store operation should be
12235     // legal (or custom) and the store size should be equal to the NewVT width.
12236     while (NewBW < BitWidth &&
12237            (NewVT.getStoreSizeInBits() != NewBW ||
12238             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12239             !TLI.isNarrowingProfitable(VT, NewVT))) {
12240       NewBW = NextPowerOf2(NewBW);
12241       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12242     }
12243     if (NewBW >= BitWidth)
12244       return SDValue();
12245 
12246     // If the lsb changed does not start at the type bitwidth boundary,
12247     // start at the previous one.
12248     if (ShAmt % NewBW)
12249       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12250     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12251                                    std::min(BitWidth, ShAmt + NewBW));
12252     if ((Imm & Mask) == Imm) {
12253       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12254       if (Opc == ISD::AND)
12255         NewImm ^= APInt::getAllOnesValue(NewBW);
12256       uint64_t PtrOff = ShAmt / 8;
12257       // For big endian targets, we need to adjust the offset to the pointer to
12258       // load the correct bytes.
12259       if (DAG.getDataLayout().isBigEndian())
12260         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12261 
12262       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12263       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12264       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12265         return SDValue();
12266 
12267       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12268                                    Ptr.getValueType(), Ptr,
12269                                    DAG.getConstant(PtrOff, SDLoc(LD),
12270                                                    Ptr.getValueType()));
12271       SDValue NewLD =
12272           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12273                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12274                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12275       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12276                                    DAG.getConstant(NewImm, SDLoc(Value),
12277                                                    NewVT));
12278       SDValue NewST =
12279           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12280                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12281 
12282       AddToWorklist(NewPtr.getNode());
12283       AddToWorklist(NewLD.getNode());
12284       AddToWorklist(NewVal.getNode());
12285       WorklistRemover DeadNodes(*this);
12286       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12287       ++OpsNarrowed;
12288       return NewST;
12289     }
12290   }
12291 
12292   return SDValue();
12293 }
12294 
12295 /// For a given floating point load / store pair, if the load value isn't used
12296 /// by any other operations, then consider transforming the pair to integer
12297 /// load / store operations if the target deems the transformation profitable.
12298 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12299   StoreSDNode *ST  = cast<StoreSDNode>(N);
12300   SDValue Chain = ST->getChain();
12301   SDValue Value = ST->getValue();
12302   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12303       Value.hasOneUse() &&
12304       Chain == SDValue(Value.getNode(), 1)) {
12305     LoadSDNode *LD = cast<LoadSDNode>(Value);
12306     EVT VT = LD->getMemoryVT();
12307     if (!VT.isFloatingPoint() ||
12308         VT != ST->getMemoryVT() ||
12309         LD->isNonTemporal() ||
12310         ST->isNonTemporal() ||
12311         LD->getPointerInfo().getAddrSpace() != 0 ||
12312         ST->getPointerInfo().getAddrSpace() != 0)
12313       return SDValue();
12314 
12315     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12316     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12317         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12318         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12319         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12320       return SDValue();
12321 
12322     unsigned LDAlign = LD->getAlignment();
12323     unsigned STAlign = ST->getAlignment();
12324     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12325     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12326     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12327       return SDValue();
12328 
12329     SDValue NewLD =
12330         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12331                     LD->getPointerInfo(), LDAlign);
12332 
12333     SDValue NewST =
12334         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12335                      ST->getPointerInfo(), STAlign);
12336 
12337     AddToWorklist(NewLD.getNode());
12338     AddToWorklist(NewST.getNode());
12339     WorklistRemover DeadNodes(*this);
12340     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12341     ++LdStFP2Int;
12342     return NewST;
12343   }
12344 
12345   return SDValue();
12346 }
12347 
12348 // This is a helper function for visitMUL to check the profitability
12349 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12350 // MulNode is the original multiply, AddNode is (add x, c1),
12351 // and ConstNode is c2.
12352 //
12353 // If the (add x, c1) has multiple uses, we could increase
12354 // the number of adds if we make this transformation.
12355 // It would only be worth doing this if we can remove a
12356 // multiply in the process. Check for that here.
12357 // To illustrate:
12358 //     (A + c1) * c3
12359 //     (A + c2) * c3
12360 // We're checking for cases where we have common "c3 * A" expressions.
12361 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12362                                               SDValue &AddNode,
12363                                               SDValue &ConstNode) {
12364   APInt Val;
12365 
12366   // If the add only has one use, this would be OK to do.
12367   if (AddNode.getNode()->hasOneUse())
12368     return true;
12369 
12370   // Walk all the users of the constant with which we're multiplying.
12371   for (SDNode *Use : ConstNode->uses()) {
12372 
12373     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12374       continue;
12375 
12376     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12377       SDNode *OtherOp;
12378       SDNode *MulVar = AddNode.getOperand(0).getNode();
12379 
12380       // OtherOp is what we're multiplying against the constant.
12381       if (Use->getOperand(0) == ConstNode)
12382         OtherOp = Use->getOperand(1).getNode();
12383       else
12384         OtherOp = Use->getOperand(0).getNode();
12385 
12386       // Check to see if multiply is with the same operand of our "add".
12387       //
12388       //     ConstNode  = CONST
12389       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12390       //     ...
12391       //     AddNode  = (A + c1)  <-- MulVar is A.
12392       //         = AddNode * ConstNode   <-- current visiting instruction.
12393       //
12394       // If we make this transformation, we will have a common
12395       // multiply (ConstNode * A) that we can save.
12396       if (OtherOp == MulVar)
12397         return true;
12398 
12399       // Now check to see if a future expansion will give us a common
12400       // multiply.
12401       //
12402       //     ConstNode  = CONST
12403       //     AddNode    = (A + c1)
12404       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12405       //     ...
12406       //     OtherOp = (A + c2)
12407       //     Use     = OtherOp * ConstNode <-- visiting Use.
12408       //
12409       // If we make this transformation, we will have a common
12410       // multiply (CONST * A) after we also do the same transformation
12411       // to the "t2" instruction.
12412       if (OtherOp->getOpcode() == ISD::ADD &&
12413           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12414           OtherOp->getOperand(0).getNode() == MulVar)
12415         return true;
12416     }
12417   }
12418 
12419   // Didn't find a case where this would be profitable.
12420   return false;
12421 }
12422 
12423 static SDValue peekThroughBitcast(SDValue V) {
12424   while (V.getOpcode() == ISD::BITCAST)
12425     V = V.getOperand(0);
12426   return V;
12427 }
12428 
12429 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12430                                          unsigned NumStores) {
12431   SmallVector<SDValue, 8> Chains;
12432   SmallPtrSet<const SDNode *, 8> Visited;
12433   SDLoc StoreDL(StoreNodes[0].MemNode);
12434 
12435   for (unsigned i = 0; i < NumStores; ++i) {
12436     Visited.insert(StoreNodes[i].MemNode);
12437   }
12438 
12439   // don't include nodes that are children
12440   for (unsigned i = 0; i < NumStores; ++i) {
12441     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12442       Chains.push_back(StoreNodes[i].MemNode->getChain());
12443   }
12444 
12445   assert(Chains.size() > 0 && "Chain should have generated a chain");
12446   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12447 }
12448 
12449 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12450     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12451     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12452   // Make sure we have something to merge.
12453   if (NumStores < 2)
12454     return false;
12455 
12456   // The latest Node in the DAG.
12457   SDLoc DL(StoreNodes[0].MemNode);
12458 
12459   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12460   unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12461   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
12462 
12463   EVT StoreTy;
12464   if (UseVector) {
12465     unsigned Elts = NumStores * NumMemElts;
12466     // Get the type for the merged vector store.
12467     StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12468   } else
12469     StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12470 
12471   SDValue StoredVal;
12472   if (UseVector) {
12473     if (IsConstantSrc) {
12474       SmallVector<SDValue, 8> BuildVector;
12475       for (unsigned I = 0; I != NumStores; ++I) {
12476         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12477         SDValue Val = St->getValue();
12478         // If constant is of the wrong type, convert it now.
12479         if (MemVT != Val.getValueType()) {
12480           Val = peekThroughBitcast(Val);
12481           // Deal with constants of wrong size.
12482           if (ElementSizeBytes * 8 != Val.getValueSizeInBits()) {
12483             EVT IntMemVT =
12484                 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
12485             if (auto *CFP = dyn_cast<ConstantFPSDNode>(Val))
12486               Val = DAG.getConstant(
12487                   CFP->getValueAPF().bitcastToAPInt().zextOrTrunc(
12488                       8 * ElementSizeBytes),
12489                   SDLoc(CFP), IntMemVT);
12490             else if (auto *C = dyn_cast<ConstantSDNode>(Val))
12491               Val = DAG.getConstant(
12492                   C->getAPIntValue().zextOrTrunc(8 * ElementSizeBytes),
12493                   SDLoc(C), IntMemVT);
12494           }
12495           // Make sure correctly size type is the correct type.
12496           Val = DAG.getBitcast(MemVT, Val);
12497         }
12498         BuildVector.push_back(Val);
12499       }
12500       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12501                                                : ISD::BUILD_VECTOR,
12502                               DL, StoreTy, BuildVector);
12503     } else {
12504       SmallVector<SDValue, 8> Ops;
12505       for (unsigned i = 0; i < NumStores; ++i) {
12506         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12507         SDValue Val = peekThroughBitcast(St->getValue());
12508         // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
12509         // type MemVT. If the underlying value is not the correct
12510         // type, but it is an extraction of an appropriate vector we
12511         // can recast Val to be of the correct type. This may require
12512         // converting between EXTRACT_VECTOR_ELT and
12513         // EXTRACT_SUBVECTOR.
12514         if ((MemVT != Val.getValueType()) &&
12515             (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12516              Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
12517           SDValue Vec = Val.getOperand(0);
12518           EVT MemVTScalarTy = MemVT.getScalarType();
12519           // We may need to add a bitcast here to get types to line up.
12520           if (MemVTScalarTy != Vec.getValueType()) {
12521             unsigned Elts = Vec.getValueType().getSizeInBits() /
12522                             MemVTScalarTy.getSizeInBits();
12523             EVT NewVecTy =
12524                 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts);
12525             Vec = DAG.getBitcast(NewVecTy, Vec);
12526           }
12527           auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR
12528                                         : ISD::EXTRACT_VECTOR_ELT;
12529           Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1));
12530         }
12531         Ops.push_back(Val);
12532       }
12533 
12534       // Build the extracted vector elements back into a vector.
12535       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12536                                                : ISD::BUILD_VECTOR,
12537                               DL, StoreTy, Ops);
12538     }
12539   } else {
12540     // We should always use a vector store when merging extracted vector
12541     // elements, so this path implies a store of constants.
12542     assert(IsConstantSrc && "Merged vector elements should use vector store");
12543 
12544     APInt StoreInt(SizeInBits, 0);
12545 
12546     // Construct a single integer constant which is made of the smaller
12547     // constant inputs.
12548     bool IsLE = DAG.getDataLayout().isLittleEndian();
12549     for (unsigned i = 0; i < NumStores; ++i) {
12550       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12551       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12552 
12553       SDValue Val = St->getValue();
12554       StoreInt <<= ElementSizeBytes * 8;
12555       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12556         StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits);
12557       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12558         StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits);
12559       } else {
12560         llvm_unreachable("Invalid constant element type");
12561       }
12562     }
12563 
12564     // Create the new Load and Store operations.
12565     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12566   }
12567 
12568   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12569   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12570 
12571   // make sure we use trunc store if it's necessary to be legal.
12572   SDValue NewStore;
12573   if (!UseTrunc) {
12574     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
12575                             FirstInChain->getPointerInfo(),
12576                             FirstInChain->getAlignment());
12577   } else { // Must be realized as a trunc store
12578     EVT LegalizedStoredValueTy =
12579         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
12580     unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
12581     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
12582     SDValue ExtendedStoreVal =
12583         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
12584                         LegalizedStoredValueTy);
12585     NewStore = DAG.getTruncStore(
12586         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
12587         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
12588         FirstInChain->getAlignment(),
12589         FirstInChain->getMemOperand()->getFlags());
12590   }
12591 
12592   // Replace all merged stores with the new store.
12593   for (unsigned i = 0; i < NumStores; ++i)
12594     CombineTo(StoreNodes[i].MemNode, NewStore);
12595 
12596   AddToWorklist(NewChain.getNode());
12597   return true;
12598 }
12599 
12600 void DAGCombiner::getStoreMergeCandidates(
12601     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12602   // This holds the base pointer, index, and the offset in bytes from the base
12603   // pointer.
12604   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12605   EVT MemVT = St->getMemoryVT();
12606 
12607   SDValue Val = peekThroughBitcast(St->getValue());
12608   // We must have a base and an offset.
12609   if (!BasePtr.getBase().getNode())
12610     return;
12611 
12612   // Do not handle stores to undef base pointers.
12613   if (BasePtr.getBase().isUndef())
12614     return;
12615 
12616   bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
12617   bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12618                           Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12619   bool IsLoadSrc = isa<LoadSDNode>(Val);
12620   BaseIndexOffset LBasePtr;
12621   // Match on loadbaseptr if relevant.
12622   EVT LoadVT;
12623   if (IsLoadSrc) {
12624     auto *Ld = cast<LoadSDNode>(Val);
12625     LBasePtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12626     LoadVT = Ld->getMemoryVT();
12627     // Load and store should be the same type.
12628     if (MemVT != LoadVT)
12629       return;
12630   }
12631   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
12632                             int64_t &Offset) -> bool {
12633     if (Other->isVolatile() || Other->isIndexed())
12634       return false;
12635     SDValue Val = peekThroughBitcast(Other->getValue());
12636     // Allow merging constants of different types as integers.
12637     bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
12638                                            : Other->getMemoryVT() != MemVT;
12639     if (IsLoadSrc) {
12640       if (NoTypeMatch)
12641         return false;
12642       // The Load's Base Ptr must also match
12643       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) {
12644         auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG);
12645         if (LoadVT != OtherLd->getMemoryVT())
12646           return false;
12647         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
12648           return false;
12649       } else
12650         return false;
12651     }
12652     if (IsConstantSrc) {
12653       if (NoTypeMatch)
12654         return false;
12655       if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val)))
12656         return false;
12657     }
12658     if (IsExtractVecSrc) {
12659       // Do not merge truncated stores here.
12660       if (Other->isTruncatingStore())
12661         return false;
12662       if (!MemVT.bitsEq(Val.getValueType()))
12663         return false;
12664       if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
12665           Val.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12666         return false;
12667     }
12668     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12669     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
12670   };
12671   // We looking for a root node which is an ancestor to all mergable
12672   // stores. We search up through a load, to our root and then down
12673   // through all children. For instance we will find Store{1,2,3} if
12674   // St is Store1, Store2. or Store3 where the root is not a load
12675   // which always true for nonvolatile ops. TODO: Expand
12676   // the search to find all valid candidates through multiple layers of loads.
12677   //
12678   // Root
12679   // |-------|-------|
12680   // Load    Load    Store3
12681   // |       |
12682   // Store1   Store2
12683   //
12684   // FIXME: We should be able to climb and
12685   // descend TokenFactors to find candidates as well.
12686 
12687   SDNode *RootNode = (St->getChain()).getNode();
12688 
12689   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12690     RootNode = Ldn->getChain().getNode();
12691     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12692       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12693         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12694           if (I2.getOperandNo() == 0)
12695             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12696               BaseIndexOffset Ptr;
12697               int64_t PtrDiff;
12698               if (CandidateMatch(OtherST, Ptr, PtrDiff))
12699                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12700             }
12701   } else
12702     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12703       if (I.getOperandNo() == 0)
12704         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12705           BaseIndexOffset Ptr;
12706           int64_t PtrDiff;
12707           if (CandidateMatch(OtherST, Ptr, PtrDiff))
12708             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12709         }
12710 }
12711 
12712 // We need to check that merging these stores does not cause a loop
12713 // in the DAG. Any store candidate may depend on another candidate
12714 // indirectly through its operand (we already consider dependencies
12715 // through the chain). Check in parallel by searching up from
12716 // non-chain operands of candidates.
12717 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12718     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12719   SmallPtrSet<const SDNode *, 16> Visited;
12720   SmallVector<const SDNode *, 8> Worklist;
12721   // search ops of store candidates
12722   for (unsigned i = 0; i < NumStores; ++i) {
12723     SDNode *n = StoreNodes[i].MemNode;
12724     // Potential loops may happen only through non-chain operands
12725     for (unsigned j = 1; j < n->getNumOperands(); ++j)
12726       Worklist.push_back(n->getOperand(j).getNode());
12727   }
12728   // search through DAG. We can stop early if we find a storenode
12729   for (unsigned i = 0; i < NumStores; ++i) {
12730     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12731       return false;
12732   }
12733   return true;
12734 }
12735 
12736 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12737   if (OptLevel == CodeGenOpt::None)
12738     return false;
12739 
12740   EVT MemVT = St->getMemoryVT();
12741   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12742   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
12743 
12744   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12745     return false;
12746 
12747   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12748       Attribute::NoImplicitFloat);
12749 
12750   // This function cannot currently deal with non-byte-sized memory sizes.
12751   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12752     return false;
12753 
12754   if (!MemVT.isSimple())
12755     return false;
12756 
12757   // Perform an early exit check. Do not bother looking at stored values that
12758   // are not constants, loads, or extracted vector elements.
12759   SDValue StoredVal = peekThroughBitcast(St->getValue());
12760   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12761   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12762                        isa<ConstantFPSDNode>(StoredVal);
12763   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12764                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12765 
12766   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12767     return false;
12768 
12769   SmallVector<MemOpLink, 8> StoreNodes;
12770   // Find potential store merge candidates by searching through chain sub-DAG
12771   getStoreMergeCandidates(St, StoreNodes);
12772 
12773   // Check if there is anything to merge.
12774   if (StoreNodes.size() < 2)
12775     return false;
12776 
12777   // Sort the memory operands according to their distance from the
12778   // base pointer.
12779   std::sort(StoreNodes.begin(), StoreNodes.end(),
12780             [](MemOpLink LHS, MemOpLink RHS) {
12781               return LHS.OffsetFromBase < RHS.OffsetFromBase;
12782             });
12783 
12784   // Store Merge attempts to merge the lowest stores. This generally
12785   // works out as if successful, as the remaining stores are checked
12786   // after the first collection of stores is merged. However, in the
12787   // case that a non-mergeable store is found first, e.g., {p[-2],
12788   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12789   // mergeable cases. To prevent this, we prune such stores from the
12790   // front of StoreNodes here.
12791 
12792   bool RV = false;
12793   while (StoreNodes.size() > 1) {
12794     unsigned StartIdx = 0;
12795     while ((StartIdx + 1 < StoreNodes.size()) &&
12796            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12797                StoreNodes[StartIdx + 1].OffsetFromBase)
12798       ++StartIdx;
12799 
12800     // Bail if we don't have enough candidates to merge.
12801     if (StartIdx + 1 >= StoreNodes.size())
12802       return RV;
12803 
12804     if (StartIdx)
12805       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12806 
12807     // Scan the memory operations on the chain and find the first
12808     // non-consecutive store memory address.
12809     unsigned NumConsecutiveStores = 1;
12810     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12811     // Check that the addresses are consecutive starting from the second
12812     // element in the list of stores.
12813     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12814       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12815       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12816         break;
12817       NumConsecutiveStores = i + 1;
12818     }
12819 
12820     if (NumConsecutiveStores < 2) {
12821       StoreNodes.erase(StoreNodes.begin(),
12822                        StoreNodes.begin() + NumConsecutiveStores);
12823       continue;
12824     }
12825 
12826     // Check that we can merge these candidates without causing a cycle
12827     if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
12828                                                   NumConsecutiveStores)) {
12829       StoreNodes.erase(StoreNodes.begin(),
12830                        StoreNodes.begin() + NumConsecutiveStores);
12831       continue;
12832     }
12833 
12834     // The node with the lowest store address.
12835     LLVMContext &Context = *DAG.getContext();
12836     const DataLayout &DL = DAG.getDataLayout();
12837 
12838     // Store the constants into memory as one consecutive store.
12839     if (IsConstantSrc) {
12840       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12841       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12842       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12843       unsigned LastLegalType = 1;
12844       unsigned LastLegalVectorType = 1;
12845       bool LastIntegerTrunc = false;
12846       bool NonZero = false;
12847       unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
12848       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12849         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12850         SDValue StoredVal = ST->getValue();
12851         bool IsElementZero = false;
12852         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
12853           IsElementZero = C->isNullValue();
12854         else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
12855           IsElementZero = C->getConstantFPValue()->isNullValue();
12856         if (IsElementZero) {
12857           if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
12858             FirstZeroAfterNonZero = i;
12859         }
12860         NonZero |= !IsElementZero;
12861 
12862         // Find a legal type for the constant store.
12863         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12864         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12865         bool IsFast = false;
12866         if (TLI.isTypeLegal(StoreTy) &&
12867             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
12868             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12869                                    FirstStoreAlign, &IsFast) &&
12870             IsFast) {
12871           LastIntegerTrunc = false;
12872           LastLegalType = i + 1;
12873           // Or check whether a truncstore is legal.
12874         } else if (TLI.getTypeAction(Context, StoreTy) ==
12875                    TargetLowering::TypePromoteInteger) {
12876           EVT LegalizedStoredValueTy =
12877               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12878           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12879               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
12880               TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12881                                      FirstStoreAlign, &IsFast) &&
12882               IsFast) {
12883             LastIntegerTrunc = true;
12884             LastLegalType = i + 1;
12885           }
12886         }
12887 
12888         // We only use vectors if the constant is known to be zero or the target
12889         // allows it and the function is not marked with the noimplicitfloat
12890         // attribute.
12891         if ((!NonZero ||
12892              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12893             !NoVectors) {
12894           // Find a legal type for the vector store.
12895           unsigned Elts = (i + 1) * NumMemElts;
12896           EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
12897           if (TLI.isTypeLegal(Ty) &&
12898               TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
12899               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12900                                      FirstStoreAlign, &IsFast) &&
12901               IsFast)
12902             LastLegalVectorType = i + 1;
12903         }
12904       }
12905 
12906       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12907       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12908 
12909       // Check if we found a legal integer type that creates a meaningful merge.
12910       if (NumElem < 2) {
12911         // We know that candidate stores are in order and of correct
12912         // shape. While there is no mergeable sequence from the
12913         // beginning one may start later in the sequence. The only
12914         // reason a merge of size N could have failed where another of
12915         // the same size would not have, is if the alignment has
12916         // improved or we've dropped a non-zero value. Drop as many
12917         // candidates as we can here.
12918         unsigned NumSkip = 1;
12919         while (
12920             (NumSkip < NumConsecutiveStores) &&
12921             (NumSkip < FirstZeroAfterNonZero) &&
12922             (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) {
12923           NumSkip++;
12924         }
12925         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
12926         continue;
12927       }
12928 
12929       bool Merged = MergeStoresOfConstantsOrVecElts(
12930           StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
12931       RV |= Merged;
12932 
12933       // Remove merged stores for next iteration.
12934       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12935       continue;
12936     }
12937 
12938     // When extracting multiple vector elements, try to store them
12939     // in one vector store rather than a sequence of scalar stores.
12940     if (IsExtractVecSrc) {
12941       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12942       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12943       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12944       unsigned NumStoresToMerge = 1;
12945       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12946         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12947         SDValue StVal = peekThroughBitcast(St->getValue());
12948         // This restriction could be loosened.
12949         // Bail out if any stored values are not elements extracted from a
12950         // vector. It should be possible to handle mixed sources, but load
12951         // sources need more careful handling (see the block of code below that
12952         // handles consecutive loads).
12953         if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
12954             StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12955           return RV;
12956 
12957         // Find a legal type for the vector store.
12958         unsigned Elts = (i + 1) * NumMemElts;
12959         EVT Ty =
12960             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12961         bool IsFast;
12962         if (TLI.isTypeLegal(Ty) &&
12963             TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
12964             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12965                                    FirstStoreAlign, &IsFast) &&
12966             IsFast)
12967           NumStoresToMerge = i + 1;
12968       }
12969 
12970       // Check if we found a legal integer type that creates a meaningful merge.
12971       if (NumStoresToMerge < 2) {
12972         // We know that candidate stores are in order and of correct
12973         // shape. While there is no mergeable sequence from the
12974         // beginning one may start later in the sequence. The only
12975         // reason a merge of size N could have failed where another of
12976         // the same size would not have, is if the alignment has
12977         // improved. Drop as many candidates as we can here.
12978         unsigned NumSkip = 1;
12979         while ((NumSkip < NumConsecutiveStores) &&
12980                (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
12981           NumSkip++;
12982 
12983         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
12984         continue;
12985       }
12986 
12987       bool Merged = MergeStoresOfConstantsOrVecElts(
12988           StoreNodes, MemVT, NumStoresToMerge, false, true, false);
12989       if (!Merged) {
12990         StoreNodes.erase(StoreNodes.begin(),
12991                          StoreNodes.begin() + NumStoresToMerge);
12992         continue;
12993       }
12994       // Remove merged stores for next iteration.
12995       StoreNodes.erase(StoreNodes.begin(),
12996                        StoreNodes.begin() + NumStoresToMerge);
12997       RV = true;
12998       continue;
12999     }
13000 
13001     // Below we handle the case of multiple consecutive stores that
13002     // come from multiple consecutive loads. We merge them into a single
13003     // wide load and a single wide store.
13004 
13005     // Look for load nodes which are used by the stored values.
13006     SmallVector<MemOpLink, 8> LoadNodes;
13007 
13008     // Find acceptable loads. Loads need to have the same chain (token factor),
13009     // must not be zext, volatile, indexed, and they must be consecutive.
13010     BaseIndexOffset LdBasePtr;
13011     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13012       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13013       SDValue Val = peekThroughBitcast(St->getValue());
13014       LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val);
13015       if (!Ld)
13016         break;
13017 
13018       // Loads must only have one use.
13019       if (!Ld->hasNUsesOfValue(1, 0))
13020         break;
13021 
13022       // The memory operands must not be volatile.
13023       if (Ld->isVolatile() || Ld->isIndexed())
13024         break;
13025 
13026       // The stored memory type must be the same.
13027       if (Ld->getMemoryVT() != MemVT)
13028         break;
13029 
13030       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
13031       // If this is not the first ptr that we check.
13032       int64_t LdOffset = 0;
13033       if (LdBasePtr.getBase().getNode()) {
13034         // The base ptr must be the same.
13035         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
13036           break;
13037       } else {
13038         // Check that all other base pointers are the same as this one.
13039         LdBasePtr = LdPtr;
13040       }
13041 
13042       // We found a potential memory operand to merge.
13043       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
13044     }
13045 
13046     if (LoadNodes.size() < 2) {
13047       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13048       continue;
13049     }
13050 
13051     // If we have load/store pair instructions and we only have two values,
13052     // don't bother merging.
13053     unsigned RequiredAlignment;
13054     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
13055         StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
13056       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
13057       continue;
13058     }
13059     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13060     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13061     unsigned FirstStoreAlign = FirstInChain->getAlignment();
13062     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
13063     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
13064     unsigned FirstLoadAlign = FirstLoad->getAlignment();
13065 
13066     // Scan the memory operations on the chain and find the first
13067     // non-consecutive load memory address. These variables hold the index in
13068     // the store node array.
13069     unsigned LastConsecutiveLoad = 1;
13070     // This variable refers to the size and not index in the array.
13071     unsigned LastLegalVectorType = 1;
13072     unsigned LastLegalIntegerType = 1;
13073     bool isDereferenceable = true;
13074     bool DoIntegerTruncate = false;
13075     StartAddress = LoadNodes[0].OffsetFromBase;
13076     SDValue FirstChain = FirstLoad->getChain();
13077     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
13078       // All loads must share the same chain.
13079       if (LoadNodes[i].MemNode->getChain() != FirstChain)
13080         break;
13081 
13082       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
13083       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13084         break;
13085       LastConsecutiveLoad = i;
13086 
13087       if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
13088         isDereferenceable = false;
13089 
13090       // Find a legal type for the vector store.
13091       unsigned Elts = (i + 1) * NumMemElts;
13092       EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13093 
13094       bool IsFastSt, IsFastLd;
13095       if (TLI.isTypeLegal(StoreTy) &&
13096           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13097           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13098                                  FirstStoreAlign, &IsFastSt) &&
13099           IsFastSt &&
13100           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13101                                  FirstLoadAlign, &IsFastLd) &&
13102           IsFastLd) {
13103         LastLegalVectorType = i + 1;
13104       }
13105 
13106       // Find a legal type for the integer store.
13107       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13108       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13109       if (TLI.isTypeLegal(StoreTy) &&
13110           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13111           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13112                                  FirstStoreAlign, &IsFastSt) &&
13113           IsFastSt &&
13114           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13115                                  FirstLoadAlign, &IsFastLd) &&
13116           IsFastLd) {
13117         LastLegalIntegerType = i + 1;
13118         DoIntegerTruncate = false;
13119         // Or check whether a truncstore and extload is legal.
13120       } else if (TLI.getTypeAction(Context, StoreTy) ==
13121                  TargetLowering::TypePromoteInteger) {
13122         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
13123         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13124             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13125             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13126                                StoreTy) &&
13127             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13128                                StoreTy) &&
13129             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13130             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13131                                    FirstStoreAlign, &IsFastSt) &&
13132             IsFastSt &&
13133             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13134                                    FirstLoadAlign, &IsFastLd) &&
13135             IsFastLd) {
13136           LastLegalIntegerType = i + 1;
13137           DoIntegerTruncate = true;
13138         }
13139       }
13140     }
13141 
13142     // Only use vector types if the vector type is larger than the integer type.
13143     // If they are the same, use integers.
13144     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13145     unsigned LastLegalType =
13146         std::max(LastLegalVectorType, LastLegalIntegerType);
13147 
13148     // We add +1 here because the LastXXX variables refer to location while
13149     // the NumElem refers to array/index size.
13150     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13151     NumElem = std::min(LastLegalType, NumElem);
13152 
13153     if (NumElem < 2) {
13154       // We know that candidate stores are in order and of correct
13155       // shape. While there is no mergeable sequence from the
13156       // beginning one may start later in the sequence. The only
13157       // reason a merge of size N could have failed where another of
13158       // the same size would not have is if the alignment or either
13159       // the load or store has improved. Drop as many candidates as we
13160       // can here.
13161       unsigned NumSkip = 1;
13162       while ((NumSkip < LoadNodes.size()) &&
13163              (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
13164              (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13165         NumSkip++;
13166       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13167       continue;
13168     }
13169 
13170     // Find if it is better to use vectors or integers to load and store
13171     // to memory.
13172     EVT JointMemOpVT;
13173     if (UseVectorTy) {
13174       // Find a legal type for the vector store.
13175       unsigned Elts = NumElem * NumMemElts;
13176       JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13177     } else {
13178       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13179       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13180     }
13181 
13182     SDLoc LoadDL(LoadNodes[0].MemNode);
13183     SDLoc StoreDL(StoreNodes[0].MemNode);
13184 
13185     // The merged loads are required to have the same incoming chain, so
13186     // using the first's chain is acceptable.
13187 
13188     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13189     AddToWorklist(NewStoreChain.getNode());
13190 
13191     MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13192                                           MachineMemOperand::MODereferenceable:
13193                                           MachineMemOperand::MONone;
13194 
13195     SDValue NewLoad, NewStore;
13196     if (UseVectorTy || !DoIntegerTruncate) {
13197       NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13198                             FirstLoad->getBasePtr(),
13199                             FirstLoad->getPointerInfo(), FirstLoadAlign,
13200                             MMOFlags);
13201       NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13202                               FirstInChain->getBasePtr(),
13203                               FirstInChain->getPointerInfo(), FirstStoreAlign);
13204     } else { // This must be the truncstore/extload case
13205       EVT ExtendedTy =
13206           TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13207       NewLoad =
13208           DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13209                          FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13210                          JointMemOpVT, FirstLoadAlign, MMOFlags);
13211       NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13212                                    FirstInChain->getBasePtr(),
13213                                    FirstInChain->getPointerInfo(), JointMemOpVT,
13214                                    FirstInChain->getAlignment(),
13215                                    FirstInChain->getMemOperand()->getFlags());
13216     }
13217 
13218     // Transfer chain users from old loads to the new load.
13219     for (unsigned i = 0; i < NumElem; ++i) {
13220       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13221       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13222                                     SDValue(NewLoad.getNode(), 1));
13223     }
13224 
13225     // Replace the all stores with the new store. Recursively remove
13226     // corresponding value if its no longer used.
13227     for (unsigned i = 0; i < NumElem; ++i) {
13228       SDValue Val = StoreNodes[i].MemNode->getOperand(1);
13229       CombineTo(StoreNodes[i].MemNode, NewStore);
13230       if (Val.getNode()->use_empty())
13231         recursivelyDeleteUnusedNodes(Val.getNode());
13232     }
13233 
13234     RV = true;
13235     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13236     continue;
13237   }
13238   return RV;
13239 }
13240 
13241 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13242   SDLoc SL(ST);
13243   SDValue ReplStore;
13244 
13245   // Replace the chain to avoid dependency.
13246   if (ST->isTruncatingStore()) {
13247     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13248                                   ST->getBasePtr(), ST->getMemoryVT(),
13249                                   ST->getMemOperand());
13250   } else {
13251     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13252                              ST->getMemOperand());
13253   }
13254 
13255   // Create token to keep both nodes around.
13256   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13257                               MVT::Other, ST->getChain(), ReplStore);
13258 
13259   // Make sure the new and old chains are cleaned up.
13260   AddToWorklist(Token.getNode());
13261 
13262   // Don't add users to work list.
13263   return CombineTo(ST, Token, false);
13264 }
13265 
13266 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13267   SDValue Value = ST->getValue();
13268   if (Value.getOpcode() == ISD::TargetConstantFP)
13269     return SDValue();
13270 
13271   SDLoc DL(ST);
13272 
13273   SDValue Chain = ST->getChain();
13274   SDValue Ptr = ST->getBasePtr();
13275 
13276   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13277 
13278   // NOTE: If the original store is volatile, this transform must not increase
13279   // the number of stores.  For example, on x86-32 an f64 can be stored in one
13280   // processor operation but an i64 (which is not legal) requires two.  So the
13281   // transform should not be done in this case.
13282 
13283   SDValue Tmp;
13284   switch (CFP->getSimpleValueType(0).SimpleTy) {
13285   default:
13286     llvm_unreachable("Unknown FP type");
13287   case MVT::f16:    // We don't do this for these yet.
13288   case MVT::f80:
13289   case MVT::f128:
13290   case MVT::ppcf128:
13291     return SDValue();
13292   case MVT::f32:
13293     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13294         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13295       ;
13296       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13297                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13298                             MVT::i32);
13299       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13300     }
13301 
13302     return SDValue();
13303   case MVT::f64:
13304     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13305          !ST->isVolatile()) ||
13306         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13307       ;
13308       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13309                             getZExtValue(), SDLoc(CFP), MVT::i64);
13310       return DAG.getStore(Chain, DL, Tmp,
13311                           Ptr, ST->getMemOperand());
13312     }
13313 
13314     if (!ST->isVolatile() &&
13315         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13316       // Many FP stores are not made apparent until after legalize, e.g. for
13317       // argument passing.  Since this is so common, custom legalize the
13318       // 64-bit integer store into two 32-bit stores.
13319       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13320       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13321       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13322       if (DAG.getDataLayout().isBigEndian())
13323         std::swap(Lo, Hi);
13324 
13325       unsigned Alignment = ST->getAlignment();
13326       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13327       AAMDNodes AAInfo = ST->getAAInfo();
13328 
13329       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13330                                  ST->getAlignment(), MMOFlags, AAInfo);
13331       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13332                         DAG.getConstant(4, DL, Ptr.getValueType()));
13333       Alignment = MinAlign(Alignment, 4U);
13334       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13335                                  ST->getPointerInfo().getWithOffset(4),
13336                                  Alignment, MMOFlags, AAInfo);
13337       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13338                          St0, St1);
13339     }
13340 
13341     return SDValue();
13342   }
13343 }
13344 
13345 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13346   StoreSDNode *ST  = cast<StoreSDNode>(N);
13347   SDValue Chain = ST->getChain();
13348   SDValue Value = ST->getValue();
13349   SDValue Ptr   = ST->getBasePtr();
13350 
13351   // If this is a store of a bit convert, store the input value if the
13352   // resultant store does not need a higher alignment than the original.
13353   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13354       ST->isUnindexed()) {
13355     EVT SVT = Value.getOperand(0).getValueType();
13356     if (((!LegalOperations && !ST->isVolatile()) ||
13357          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13358         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13359       unsigned OrigAlign = ST->getAlignment();
13360       bool Fast = false;
13361       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13362                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13363           Fast) {
13364         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13365                             ST->getPointerInfo(), OrigAlign,
13366                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13367       }
13368     }
13369   }
13370 
13371   // Turn 'store undef, Ptr' -> nothing.
13372   if (Value.isUndef() && ST->isUnindexed())
13373     return Chain;
13374 
13375   // Try to infer better alignment information than the store already has.
13376   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13377     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13378       if (Align > ST->getAlignment()) {
13379         SDValue NewStore =
13380             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13381                               ST->getMemoryVT(), Align,
13382                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13383         if (NewStore.getNode() != N)
13384           return CombineTo(ST, NewStore, true);
13385       }
13386     }
13387   }
13388 
13389   // Try transforming a pair floating point load / store ops to integer
13390   // load / store ops.
13391   if (SDValue NewST = TransformFPLoadStorePair(N))
13392     return NewST;
13393 
13394   if (ST->isUnindexed()) {
13395     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13396     // adjacent stores.
13397     if (findBetterNeighborChains(ST)) {
13398       // replaceStoreChain uses CombineTo, which handled all of the worklist
13399       // manipulation. Return the original node to not do anything else.
13400       return SDValue(ST, 0);
13401     }
13402     Chain = ST->getChain();
13403   }
13404 
13405   // FIXME: is there such a thing as a truncating indexed store?
13406   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13407       Value.getValueType().isInteger()) {
13408     // See if we can simplify the input to this truncstore with knowledge that
13409     // only the low bits are being used.  For example:
13410     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13411     SDValue Shorter = DAG.GetDemandedBits(
13412         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13413                                     ST->getMemoryVT().getScalarSizeInBits()));
13414     AddToWorklist(Value.getNode());
13415     if (Shorter.getNode())
13416       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13417                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13418 
13419     // Otherwise, see if we can simplify the operation with
13420     // SimplifyDemandedBits, which only works if the value has a single use.
13421     if (SimplifyDemandedBits(
13422             Value,
13423             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13424                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13425       // Re-visit the store if anything changed and the store hasn't been merged
13426       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13427       // node back to the worklist if necessary, but we also need to re-visit
13428       // the Store node itself.
13429       if (N->getOpcode() != ISD::DELETED_NODE)
13430         AddToWorklist(N);
13431       return SDValue(N, 0);
13432     }
13433   }
13434 
13435   // If this is a load followed by a store to the same location, then the store
13436   // is dead/noop.
13437   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13438     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13439         ST->isUnindexed() && !ST->isVolatile() &&
13440         // There can't be any side effects between the load and store, such as
13441         // a call or store.
13442         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13443       // The store is dead, remove it.
13444       return Chain;
13445     }
13446   }
13447 
13448   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13449     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13450         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13451         ST->getMemoryVT() == ST1->getMemoryVT()) {
13452       // If this is a store followed by a store with the same value to the same
13453       // location, then the store is dead/noop.
13454       if (ST1->getValue() == Value) {
13455         // The store is dead, remove it.
13456         return Chain;
13457       }
13458 
13459       // If this is a store who's preceeding store to the same location
13460       // and no one other node is chained to that store we can effectively
13461       // drop the store. Do not remove stores to undef as they may be used as
13462       // data sinks.
13463       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13464           !ST1->getBasePtr().isUndef()) {
13465         // ST1 is fully overwritten and can be elided. Combine with it's chain
13466         // value.
13467         CombineTo(ST1, ST1->getChain());
13468         return SDValue();
13469       }
13470     }
13471   }
13472 
13473   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13474   // truncating store.  We can do this even if this is already a truncstore.
13475   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13476       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13477       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13478                             ST->getMemoryVT())) {
13479     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13480                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13481   }
13482 
13483   // Only perform this optimization before the types are legal, because we
13484   // don't want to perform this optimization on every DAGCombine invocation.
13485   if ((TLI.mergeStoresAfterLegalization()) ? Level == AfterLegalizeDAG
13486                                            : !LegalTypes) {
13487     for (;;) {
13488       // There can be multiple store sequences on the same chain.
13489       // Keep trying to merge store sequences until we are unable to do so
13490       // or until we merge the last store on the chain.
13491       bool Changed = MergeConsecutiveStores(ST);
13492       if (!Changed) break;
13493       // Return N as merge only uses CombineTo and no worklist clean
13494       // up is necessary.
13495       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13496         return SDValue(N, 0);
13497     }
13498   }
13499 
13500   // Try transforming N to an indexed store.
13501   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13502     return SDValue(N, 0);
13503 
13504   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13505   //
13506   // Make sure to do this only after attempting to merge stores in order to
13507   //  avoid changing the types of some subset of stores due to visit order,
13508   //  preventing their merging.
13509   if (isa<ConstantFPSDNode>(ST->getValue())) {
13510     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13511       return NewSt;
13512   }
13513 
13514   if (SDValue NewSt = splitMergedValStore(ST))
13515     return NewSt;
13516 
13517   return ReduceLoadOpStoreWidth(N);
13518 }
13519 
13520 /// For the instruction sequence of store below, F and I values
13521 /// are bundled together as an i64 value before being stored into memory.
13522 /// Sometimes it is more efficent to generate separate stores for F and I,
13523 /// which can remove the bitwise instructions or sink them to colder places.
13524 ///
13525 ///   (store (or (zext (bitcast F to i32) to i64),
13526 ///              (shl (zext I to i64), 32)), addr)  -->
13527 ///   (store F, addr) and (store I, addr+4)
13528 ///
13529 /// Similarly, splitting for other merged store can also be beneficial, like:
13530 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13531 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13532 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13533 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13534 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13535 ///
13536 /// We allow each target to determine specifically which kind of splitting is
13537 /// supported.
13538 ///
13539 /// The store patterns are commonly seen from the simple code snippet below
13540 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13541 ///   void goo(const std::pair<int, float> &);
13542 ///   hoo() {
13543 ///     ...
13544 ///     goo(std::make_pair(tmp, ftmp));
13545 ///     ...
13546 ///   }
13547 ///
13548 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13549   if (OptLevel == CodeGenOpt::None)
13550     return SDValue();
13551 
13552   SDValue Val = ST->getValue();
13553   SDLoc DL(ST);
13554 
13555   // Match OR operand.
13556   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13557     return SDValue();
13558 
13559   // Match SHL operand and get Lower and Higher parts of Val.
13560   SDValue Op1 = Val.getOperand(0);
13561   SDValue Op2 = Val.getOperand(1);
13562   SDValue Lo, Hi;
13563   if (Op1.getOpcode() != ISD::SHL) {
13564     std::swap(Op1, Op2);
13565     if (Op1.getOpcode() != ISD::SHL)
13566       return SDValue();
13567   }
13568   Lo = Op2;
13569   Hi = Op1.getOperand(0);
13570   if (!Op1.hasOneUse())
13571     return SDValue();
13572 
13573   // Match shift amount to HalfValBitSize.
13574   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13575   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13576   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13577     return SDValue();
13578 
13579   // Lo and Hi are zero-extended from int with size less equal than 32
13580   // to i64.
13581   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13582       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13583       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13584       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13585       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13586       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13587     return SDValue();
13588 
13589   // Use the EVT of low and high parts before bitcast as the input
13590   // of target query.
13591   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13592                   ? Lo.getOperand(0).getValueType()
13593                   : Lo.getValueType();
13594   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13595                    ? Hi.getOperand(0).getValueType()
13596                    : Hi.getValueType();
13597   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13598     return SDValue();
13599 
13600   // Start to split store.
13601   unsigned Alignment = ST->getAlignment();
13602   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13603   AAMDNodes AAInfo = ST->getAAInfo();
13604 
13605   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13606   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13607   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13608   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13609 
13610   SDValue Chain = ST->getChain();
13611   SDValue Ptr = ST->getBasePtr();
13612   // Lower value store.
13613   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13614                              ST->getAlignment(), MMOFlags, AAInfo);
13615   Ptr =
13616       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13617                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13618   // Higher value store.
13619   SDValue St1 =
13620       DAG.getStore(St0, DL, Hi, Ptr,
13621                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13622                    Alignment / 2, MMOFlags, AAInfo);
13623   return St1;
13624 }
13625 
13626 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13627   SDValue InVec = N->getOperand(0);
13628   SDValue InVal = N->getOperand(1);
13629   SDValue EltNo = N->getOperand(2);
13630   SDLoc DL(N);
13631 
13632   // If the inserted element is an UNDEF, just use the input vector.
13633   if (InVal.isUndef())
13634     return InVec;
13635 
13636   EVT VT = InVec.getValueType();
13637 
13638   // Remove redundant insertions:
13639   // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
13640   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
13641       InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
13642     return InVec;
13643 
13644   // Check that we know which element is being inserted
13645   if (!isa<ConstantSDNode>(EltNo))
13646     return SDValue();
13647   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13648 
13649   // Canonicalize insert_vector_elt dag nodes.
13650   // Example:
13651   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13652   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13653   //
13654   // Do this only if the child insert_vector node has one use; also
13655   // do this only if indices are both constants and Idx1 < Idx0.
13656   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13657       && isa<ConstantSDNode>(InVec.getOperand(2))) {
13658     unsigned OtherElt = InVec.getConstantOperandVal(2);
13659     if (Elt < OtherElt) {
13660       // Swap nodes.
13661       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13662                                   InVec.getOperand(0), InVal, EltNo);
13663       AddToWorklist(NewOp.getNode());
13664       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13665                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13666     }
13667   }
13668 
13669   // If we can't generate a legal BUILD_VECTOR, exit
13670   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13671     return SDValue();
13672 
13673   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13674   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
13675   // vector elements.
13676   SmallVector<SDValue, 8> Ops;
13677   // Do not combine these two vectors if the output vector will not replace
13678   // the input vector.
13679   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13680     Ops.append(InVec.getNode()->op_begin(),
13681                InVec.getNode()->op_end());
13682   } else if (InVec.isUndef()) {
13683     unsigned NElts = VT.getVectorNumElements();
13684     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13685   } else {
13686     return SDValue();
13687   }
13688 
13689   // Insert the element
13690   if (Elt < Ops.size()) {
13691     // All the operands of BUILD_VECTOR must have the same type;
13692     // we enforce that here.
13693     EVT OpVT = Ops[0].getValueType();
13694     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13695   }
13696 
13697   // Return the new vector
13698   return DAG.getBuildVector(VT, DL, Ops);
13699 }
13700 
13701 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13702     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13703   assert(!OriginalLoad->isVolatile());
13704 
13705   EVT ResultVT = EVE->getValueType(0);
13706   EVT VecEltVT = InVecVT.getVectorElementType();
13707   unsigned Align = OriginalLoad->getAlignment();
13708   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13709       VecEltVT.getTypeForEVT(*DAG.getContext()));
13710 
13711   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13712     return SDValue();
13713 
13714   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13715     ISD::NON_EXTLOAD : ISD::EXTLOAD;
13716   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13717     return SDValue();
13718 
13719   Align = NewAlign;
13720 
13721   SDValue NewPtr = OriginalLoad->getBasePtr();
13722   SDValue Offset;
13723   EVT PtrType = NewPtr.getValueType();
13724   MachinePointerInfo MPI;
13725   SDLoc DL(EVE);
13726   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13727     int Elt = ConstEltNo->getZExtValue();
13728     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13729     Offset = DAG.getConstant(PtrOff, DL, PtrType);
13730     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13731   } else {
13732     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13733     Offset = DAG.getNode(
13734         ISD::MUL, DL, PtrType, Offset,
13735         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13736     MPI = OriginalLoad->getPointerInfo();
13737   }
13738   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13739 
13740   // The replacement we need to do here is a little tricky: we need to
13741   // replace an extractelement of a load with a load.
13742   // Use ReplaceAllUsesOfValuesWith to do the replacement.
13743   // Note that this replacement assumes that the extractvalue is the only
13744   // use of the load; that's okay because we don't want to perform this
13745   // transformation in other cases anyway.
13746   SDValue Load;
13747   SDValue Chain;
13748   if (ResultVT.bitsGT(VecEltVT)) {
13749     // If the result type of vextract is wider than the load, then issue an
13750     // extending load instead.
13751     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13752                                                   VecEltVT)
13753                                    ? ISD::ZEXTLOAD
13754                                    : ISD::EXTLOAD;
13755     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13756                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13757                           Align, OriginalLoad->getMemOperand()->getFlags(),
13758                           OriginalLoad->getAAInfo());
13759     Chain = Load.getValue(1);
13760   } else {
13761     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13762                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13763                        OriginalLoad->getAAInfo());
13764     Chain = Load.getValue(1);
13765     if (ResultVT.bitsLT(VecEltVT))
13766       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13767     else
13768       Load = DAG.getBitcast(ResultVT, Load);
13769   }
13770   WorklistRemover DeadNodes(*this);
13771   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13772   SDValue To[] = { Load, Chain };
13773   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13774   // Since we're explicitly calling ReplaceAllUses, add the new node to the
13775   // worklist explicitly as well.
13776   AddToWorklist(Load.getNode());
13777   AddUsersToWorklist(Load.getNode()); // Add users too
13778   // Make sure to revisit this node to clean it up; it will usually be dead.
13779   AddToWorklist(EVE);
13780   ++OpsNarrowed;
13781   return SDValue(EVE, 0);
13782 }
13783 
13784 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13785   // (vextract (scalar_to_vector val, 0) -> val
13786   SDValue InVec = N->getOperand(0);
13787   EVT VT = InVec.getValueType();
13788   EVT NVT = N->getValueType(0);
13789 
13790   if (InVec.isUndef())
13791     return DAG.getUNDEF(NVT);
13792 
13793   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13794     // Check if the result type doesn't match the inserted element type. A
13795     // SCALAR_TO_VECTOR may truncate the inserted element and the
13796     // EXTRACT_VECTOR_ELT may widen the extracted vector.
13797     SDValue InOp = InVec.getOperand(0);
13798     if (InOp.getValueType() != NVT) {
13799       assert(InOp.getValueType().isInteger() && NVT.isInteger());
13800       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13801     }
13802     return InOp;
13803   }
13804 
13805   SDValue EltNo = N->getOperand(1);
13806   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13807 
13808   // extract_vector_elt (build_vector x, y), 1 -> y
13809   if (ConstEltNo &&
13810       InVec.getOpcode() == ISD::BUILD_VECTOR &&
13811       TLI.isTypeLegal(VT) &&
13812       (InVec.hasOneUse() ||
13813        TLI.aggressivelyPreferBuildVectorSources(VT))) {
13814     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13815     EVT InEltVT = Elt.getValueType();
13816 
13817     // Sometimes build_vector's scalar input types do not match result type.
13818     if (NVT == InEltVT)
13819       return Elt;
13820 
13821     // TODO: It may be useful to truncate if free if the build_vector implicitly
13822     // converts.
13823   }
13824 
13825   // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x)
13826   bool isLE = DAG.getDataLayout().isLittleEndian();
13827   unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1;
13828   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13829       ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) {
13830     SDValue BCSrc = InVec.getOperand(0);
13831     if (BCSrc.getValueType().isScalarInteger())
13832       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13833   }
13834 
13835   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13836   //
13837   // This only really matters if the index is non-constant since other combines
13838   // on the constant elements already work.
13839   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13840       EltNo == InVec.getOperand(2)) {
13841     SDValue Elt = InVec.getOperand(1);
13842     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13843   }
13844 
13845   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13846   // We only perform this optimization before the op legalization phase because
13847   // we may introduce new vector instructions which are not backed by TD
13848   // patterns. For example on AVX, extracting elements from a wide vector
13849   // without using extract_subvector. However, if we can find an underlying
13850   // scalar value, then we can always use that.
13851   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13852     int NumElem = VT.getVectorNumElements();
13853     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13854     // Find the new index to extract from.
13855     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13856 
13857     // Extracting an undef index is undef.
13858     if (OrigElt == -1)
13859       return DAG.getUNDEF(NVT);
13860 
13861     // Select the right vector half to extract from.
13862     SDValue SVInVec;
13863     if (OrigElt < NumElem) {
13864       SVInVec = InVec->getOperand(0);
13865     } else {
13866       SVInVec = InVec->getOperand(1);
13867       OrigElt -= NumElem;
13868     }
13869 
13870     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13871       SDValue InOp = SVInVec.getOperand(OrigElt);
13872       if (InOp.getValueType() != NVT) {
13873         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13874         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13875       }
13876 
13877       return InOp;
13878     }
13879 
13880     // FIXME: We should handle recursing on other vector shuffles and
13881     // scalar_to_vector here as well.
13882 
13883     if (!LegalOperations) {
13884       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13885       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13886                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13887     }
13888   }
13889 
13890   bool BCNumEltsChanged = false;
13891   EVT ExtVT = VT.getVectorElementType();
13892   EVT LVT = ExtVT;
13893 
13894   // If the result of load has to be truncated, then it's not necessarily
13895   // profitable.
13896   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13897     return SDValue();
13898 
13899   if (InVec.getOpcode() == ISD::BITCAST) {
13900     // Don't duplicate a load with other uses.
13901     if (!InVec.hasOneUse())
13902       return SDValue();
13903 
13904     EVT BCVT = InVec.getOperand(0).getValueType();
13905     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13906       return SDValue();
13907     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13908       BCNumEltsChanged = true;
13909     InVec = InVec.getOperand(0);
13910     ExtVT = BCVT.getVectorElementType();
13911   }
13912 
13913   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13914   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13915       ISD::isNormalLoad(InVec.getNode()) &&
13916       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13917     SDValue Index = N->getOperand(1);
13918     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13919       if (!OrigLoad->isVolatile()) {
13920         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13921                                                              OrigLoad);
13922       }
13923     }
13924   }
13925 
13926   // Perform only after legalization to ensure build_vector / vector_shuffle
13927   // optimizations have already been done.
13928   if (!LegalOperations) return SDValue();
13929 
13930   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13931   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13932   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13933 
13934   if (ConstEltNo) {
13935     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13936 
13937     LoadSDNode *LN0 = nullptr;
13938     const ShuffleVectorSDNode *SVN = nullptr;
13939     if (ISD::isNormalLoad(InVec.getNode())) {
13940       LN0 = cast<LoadSDNode>(InVec);
13941     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13942                InVec.getOperand(0).getValueType() == ExtVT &&
13943                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13944       // Don't duplicate a load with other uses.
13945       if (!InVec.hasOneUse())
13946         return SDValue();
13947 
13948       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13949     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13950       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13951       // =>
13952       // (load $addr+1*size)
13953 
13954       // Don't duplicate a load with other uses.
13955       if (!InVec.hasOneUse())
13956         return SDValue();
13957 
13958       // If the bit convert changed the number of elements, it is unsafe
13959       // to examine the mask.
13960       if (BCNumEltsChanged)
13961         return SDValue();
13962 
13963       // Select the input vector, guarding against out of range extract vector.
13964       unsigned NumElems = VT.getVectorNumElements();
13965       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13966       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13967 
13968       if (InVec.getOpcode() == ISD::BITCAST) {
13969         // Don't duplicate a load with other uses.
13970         if (!InVec.hasOneUse())
13971           return SDValue();
13972 
13973         InVec = InVec.getOperand(0);
13974       }
13975       if (ISD::isNormalLoad(InVec.getNode())) {
13976         LN0 = cast<LoadSDNode>(InVec);
13977         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13978         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13979       }
13980     }
13981 
13982     // Make sure we found a non-volatile load and the extractelement is
13983     // the only use.
13984     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13985       return SDValue();
13986 
13987     // If Idx was -1 above, Elt is going to be -1, so just return undef.
13988     if (Elt == -1)
13989       return DAG.getUNDEF(LVT);
13990 
13991     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13992   }
13993 
13994   return SDValue();
13995 }
13996 
13997 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13998 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13999   // We perform this optimization post type-legalization because
14000   // the type-legalizer often scalarizes integer-promoted vectors.
14001   // Performing this optimization before may create bit-casts which
14002   // will be type-legalized to complex code sequences.
14003   // We perform this optimization only before the operation legalizer because we
14004   // may introduce illegal operations.
14005   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
14006     return SDValue();
14007 
14008   unsigned NumInScalars = N->getNumOperands();
14009   SDLoc DL(N);
14010   EVT VT = N->getValueType(0);
14011 
14012   // Check to see if this is a BUILD_VECTOR of a bunch of values
14013   // which come from any_extend or zero_extend nodes. If so, we can create
14014   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
14015   // optimizations. We do not handle sign-extend because we can't fill the sign
14016   // using shuffles.
14017   EVT SourceType = MVT::Other;
14018   bool AllAnyExt = true;
14019 
14020   for (unsigned i = 0; i != NumInScalars; ++i) {
14021     SDValue In = N->getOperand(i);
14022     // Ignore undef inputs.
14023     if (In.isUndef()) continue;
14024 
14025     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
14026     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
14027 
14028     // Abort if the element is not an extension.
14029     if (!ZeroExt && !AnyExt) {
14030       SourceType = MVT::Other;
14031       break;
14032     }
14033 
14034     // The input is a ZeroExt or AnyExt. Check the original type.
14035     EVT InTy = In.getOperand(0).getValueType();
14036 
14037     // Check that all of the widened source types are the same.
14038     if (SourceType == MVT::Other)
14039       // First time.
14040       SourceType = InTy;
14041     else if (InTy != SourceType) {
14042       // Multiple income types. Abort.
14043       SourceType = MVT::Other;
14044       break;
14045     }
14046 
14047     // Check if all of the extends are ANY_EXTENDs.
14048     AllAnyExt &= AnyExt;
14049   }
14050 
14051   // In order to have valid types, all of the inputs must be extended from the
14052   // same source type and all of the inputs must be any or zero extend.
14053   // Scalar sizes must be a power of two.
14054   EVT OutScalarTy = VT.getScalarType();
14055   bool ValidTypes = SourceType != MVT::Other &&
14056                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
14057                  isPowerOf2_32(SourceType.getSizeInBits());
14058 
14059   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
14060   // turn into a single shuffle instruction.
14061   if (!ValidTypes)
14062     return SDValue();
14063 
14064   bool isLE = DAG.getDataLayout().isLittleEndian();
14065   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
14066   assert(ElemRatio > 1 && "Invalid element size ratio");
14067   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
14068                                DAG.getConstant(0, DL, SourceType);
14069 
14070   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
14071   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
14072 
14073   // Populate the new build_vector
14074   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14075     SDValue Cast = N->getOperand(i);
14076     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
14077             Cast.getOpcode() == ISD::ZERO_EXTEND ||
14078             Cast.isUndef()) && "Invalid cast opcode");
14079     SDValue In;
14080     if (Cast.isUndef())
14081       In = DAG.getUNDEF(SourceType);
14082     else
14083       In = Cast->getOperand(0);
14084     unsigned Index = isLE ? (i * ElemRatio) :
14085                             (i * ElemRatio + (ElemRatio - 1));
14086 
14087     assert(Index < Ops.size() && "Invalid index");
14088     Ops[Index] = In;
14089   }
14090 
14091   // The type of the new BUILD_VECTOR node.
14092   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
14093   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
14094          "Invalid vector size");
14095   // Check if the new vector type is legal.
14096   if (!isTypeLegal(VecVT)) return SDValue();
14097 
14098   // Make the new BUILD_VECTOR.
14099   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
14100 
14101   // The new BUILD_VECTOR node has the potential to be further optimized.
14102   AddToWorklist(BV.getNode());
14103   // Bitcast to the desired type.
14104   return DAG.getBitcast(VT, BV);
14105 }
14106 
14107 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
14108   EVT VT = N->getValueType(0);
14109 
14110   unsigned NumInScalars = N->getNumOperands();
14111   SDLoc DL(N);
14112 
14113   EVT SrcVT = MVT::Other;
14114   unsigned Opcode = ISD::DELETED_NODE;
14115   unsigned NumDefs = 0;
14116 
14117   for (unsigned i = 0; i != NumInScalars; ++i) {
14118     SDValue In = N->getOperand(i);
14119     unsigned Opc = In.getOpcode();
14120 
14121     if (Opc == ISD::UNDEF)
14122       continue;
14123 
14124     // If all scalar values are floats and converted from integers.
14125     if (Opcode == ISD::DELETED_NODE &&
14126         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
14127       Opcode = Opc;
14128     }
14129 
14130     if (Opc != Opcode)
14131       return SDValue();
14132 
14133     EVT InVT = In.getOperand(0).getValueType();
14134 
14135     // If all scalar values are typed differently, bail out. It's chosen to
14136     // simplify BUILD_VECTOR of integer types.
14137     if (SrcVT == MVT::Other)
14138       SrcVT = InVT;
14139     if (SrcVT != InVT)
14140       return SDValue();
14141     NumDefs++;
14142   }
14143 
14144   // If the vector has just one element defined, it's not worth to fold it into
14145   // a vectorized one.
14146   if (NumDefs < 2)
14147     return SDValue();
14148 
14149   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
14150          && "Should only handle conversion from integer to float.");
14151   assert(SrcVT != MVT::Other && "Cannot determine source type!");
14152 
14153   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14154 
14155   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14156     return SDValue();
14157 
14158   // Just because the floating-point vector type is legal does not necessarily
14159   // mean that the corresponding integer vector type is.
14160   if (!isTypeLegal(NVT))
14161     return SDValue();
14162 
14163   SmallVector<SDValue, 8> Opnds;
14164   for (unsigned i = 0; i != NumInScalars; ++i) {
14165     SDValue In = N->getOperand(i);
14166 
14167     if (In.isUndef())
14168       Opnds.push_back(DAG.getUNDEF(SrcVT));
14169     else
14170       Opnds.push_back(In.getOperand(0));
14171   }
14172   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14173   AddToWorklist(BV.getNode());
14174 
14175   return DAG.getNode(Opcode, DL, VT, BV);
14176 }
14177 
14178 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14179                                            ArrayRef<int> VectorMask,
14180                                            SDValue VecIn1, SDValue VecIn2,
14181                                            unsigned LeftIdx) {
14182   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14183   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14184 
14185   EVT VT = N->getValueType(0);
14186   EVT InVT1 = VecIn1.getValueType();
14187   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14188 
14189   unsigned Vec2Offset = InVT1.getVectorNumElements();
14190   unsigned NumElems = VT.getVectorNumElements();
14191   unsigned ShuffleNumElems = NumElems;
14192 
14193   // We can't generate a shuffle node with mismatched input and output types.
14194   // Try to make the types match the type of the output.
14195   if (InVT1 != VT || InVT2 != VT) {
14196     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14197       // If the output vector length is a multiple of both input lengths,
14198       // we can concatenate them and pad the rest with undefs.
14199       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14200       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
14201       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14202       ConcatOps[0] = VecIn1;
14203       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14204       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14205       VecIn2 = SDValue();
14206     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14207       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
14208         return SDValue();
14209 
14210       if (!VecIn2.getNode()) {
14211         // If we only have one input vector, and it's twice the size of the
14212         // output, split it in two.
14213         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14214                              DAG.getConstant(NumElems, DL, IdxTy));
14215         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14216         // Since we now have shorter input vectors, adjust the offset of the
14217         // second vector's start.
14218         Vec2Offset = NumElems;
14219       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14220         // VecIn1 is wider than the output, and we have another, possibly
14221         // smaller input. Pad the smaller input with undefs, shuffle at the
14222         // input vector width, and extract the output.
14223         // The shuffle type is different than VT, so check legality again.
14224         if (LegalOperations &&
14225             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14226           return SDValue();
14227 
14228         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14229         // lower it back into a BUILD_VECTOR. So if the inserted type is
14230         // illegal, don't even try.
14231         if (InVT1 != InVT2) {
14232           if (!TLI.isTypeLegal(InVT2))
14233             return SDValue();
14234           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14235                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14236         }
14237         ShuffleNumElems = NumElems * 2;
14238       } else {
14239         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14240         // than VecIn1. We can't handle this for now - this case will disappear
14241         // when we start sorting the vectors by type.
14242         return SDValue();
14243       }
14244     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14245                InVT1.getSizeInBits() == VT.getSizeInBits()) {
14246       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14247       ConcatOps[0] = VecIn2;
14248       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14249     } else {
14250       // TODO: Support cases where the length mismatch isn't exactly by a
14251       // factor of 2.
14252       // TODO: Move this check upwards, so that if we have bad type
14253       // mismatches, we don't create any DAG nodes.
14254       return SDValue();
14255     }
14256   }
14257 
14258   // Initialize mask to undef.
14259   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14260 
14261   // Only need to run up to the number of elements actually used, not the
14262   // total number of elements in the shuffle - if we are shuffling a wider
14263   // vector, the high lanes should be set to undef.
14264   for (unsigned i = 0; i != NumElems; ++i) {
14265     if (VectorMask[i] <= 0)
14266       continue;
14267 
14268     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14269     if (VectorMask[i] == (int)LeftIdx) {
14270       Mask[i] = ExtIndex;
14271     } else if (VectorMask[i] == (int)LeftIdx + 1) {
14272       Mask[i] = Vec2Offset + ExtIndex;
14273     }
14274   }
14275 
14276   // The type the input vectors may have changed above.
14277   InVT1 = VecIn1.getValueType();
14278 
14279   // If we already have a VecIn2, it should have the same type as VecIn1.
14280   // If we don't, get an undef/zero vector of the appropriate type.
14281   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14282   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14283 
14284   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14285   if (ShuffleNumElems > NumElems)
14286     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14287 
14288   return Shuffle;
14289 }
14290 
14291 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14292 // operations. If the types of the vectors we're extracting from allow it,
14293 // turn this into a vector_shuffle node.
14294 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14295   SDLoc DL(N);
14296   EVT VT = N->getValueType(0);
14297 
14298   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14299   if (!isTypeLegal(VT))
14300     return SDValue();
14301 
14302   // May only combine to shuffle after legalize if shuffle is legal.
14303   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14304     return SDValue();
14305 
14306   bool UsesZeroVector = false;
14307   unsigned NumElems = N->getNumOperands();
14308 
14309   // Record, for each element of the newly built vector, which input vector
14310   // that element comes from. -1 stands for undef, 0 for the zero vector,
14311   // and positive values for the input vectors.
14312   // VectorMask maps each element to its vector number, and VecIn maps vector
14313   // numbers to their initial SDValues.
14314 
14315   SmallVector<int, 8> VectorMask(NumElems, -1);
14316   SmallVector<SDValue, 8> VecIn;
14317   VecIn.push_back(SDValue());
14318 
14319   for (unsigned i = 0; i != NumElems; ++i) {
14320     SDValue Op = N->getOperand(i);
14321 
14322     if (Op.isUndef())
14323       continue;
14324 
14325     // See if we can use a blend with a zero vector.
14326     // TODO: Should we generalize this to a blend with an arbitrary constant
14327     // vector?
14328     if (isNullConstant(Op) || isNullFPConstant(Op)) {
14329       UsesZeroVector = true;
14330       VectorMask[i] = 0;
14331       continue;
14332     }
14333 
14334     // Not an undef or zero. If the input is something other than an
14335     // EXTRACT_VECTOR_ELT with a constant index, bail out.
14336     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14337         !isa<ConstantSDNode>(Op.getOperand(1)))
14338       return SDValue();
14339 
14340     SDValue ExtractedFromVec = Op.getOperand(0);
14341 
14342     // All inputs must have the same element type as the output.
14343     if (VT.getVectorElementType() !=
14344         ExtractedFromVec.getValueType().getVectorElementType())
14345       return SDValue();
14346 
14347     // Have we seen this input vector before?
14348     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14349     // a map back from SDValues to numbers isn't worth it.
14350     unsigned Idx = std::distance(
14351         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14352     if (Idx == VecIn.size())
14353       VecIn.push_back(ExtractedFromVec);
14354 
14355     VectorMask[i] = Idx;
14356   }
14357 
14358   // If we didn't find at least one input vector, bail out.
14359   if (VecIn.size() < 2)
14360     return SDValue();
14361 
14362   // TODO: We want to sort the vectors by descending length, so that adjacent
14363   // pairs have similar length, and the longer vector is always first in the
14364   // pair.
14365 
14366   // TODO: Should this fire if some of the input vectors has illegal type (like
14367   // it does now), or should we let legalization run its course first?
14368 
14369   // Shuffle phase:
14370   // Take pairs of vectors, and shuffle them so that the result has elements
14371   // from these vectors in the correct places.
14372   // For example, given:
14373   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14374   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14375   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14376   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14377   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14378   // We will generate:
14379   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14380   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14381   SmallVector<SDValue, 4> Shuffles;
14382   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14383     unsigned LeftIdx = 2 * In + 1;
14384     SDValue VecLeft = VecIn[LeftIdx];
14385     SDValue VecRight =
14386         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14387 
14388     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14389                                                 VecRight, LeftIdx))
14390       Shuffles.push_back(Shuffle);
14391     else
14392       return SDValue();
14393   }
14394 
14395   // If we need the zero vector as an "ingredient" in the blend tree, add it
14396   // to the list of shuffles.
14397   if (UsesZeroVector)
14398     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14399                                       : DAG.getConstantFP(0.0, DL, VT));
14400 
14401   // If we only have one shuffle, we're done.
14402   if (Shuffles.size() == 1)
14403     return Shuffles[0];
14404 
14405   // Update the vector mask to point to the post-shuffle vectors.
14406   for (int &Vec : VectorMask)
14407     if (Vec == 0)
14408       Vec = Shuffles.size() - 1;
14409     else
14410       Vec = (Vec - 1) / 2;
14411 
14412   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14413   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14414   // generate:
14415   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14416   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14417   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14418   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14419   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14420   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14421   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14422 
14423   // Make sure the initial size of the shuffle list is even.
14424   if (Shuffles.size() % 2)
14425     Shuffles.push_back(DAG.getUNDEF(VT));
14426 
14427   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14428     if (CurSize % 2) {
14429       Shuffles[CurSize] = DAG.getUNDEF(VT);
14430       CurSize++;
14431     }
14432     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14433       int Left = 2 * In;
14434       int Right = 2 * In + 1;
14435       SmallVector<int, 8> Mask(NumElems, -1);
14436       for (unsigned i = 0; i != NumElems; ++i) {
14437         if (VectorMask[i] == Left) {
14438           Mask[i] = i;
14439           VectorMask[i] = In;
14440         } else if (VectorMask[i] == Right) {
14441           Mask[i] = i + NumElems;
14442           VectorMask[i] = In;
14443         }
14444       }
14445 
14446       Shuffles[In] =
14447           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14448     }
14449   }
14450 
14451   return Shuffles[0];
14452 }
14453 
14454 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14455 // operations which can be matched to a truncate or to a shuffle-truncate.
14456 SDValue DAGCombiner::reduceBuildVecToTrunc(SDNode *N) {
14457   // TODO: Add support for big-endian.
14458   if (DAG.getDataLayout().isBigEndian())
14459     return SDValue();
14460   if (N->getNumOperands() < 2)
14461     return SDValue();
14462   SDLoc DL(N);
14463   EVT VT = N->getValueType(0);
14464   unsigned NumElems = N->getNumOperands();
14465 
14466   if (!isTypeLegal(VT))
14467     return SDValue();
14468 
14469   // If the input is something other than an EXTRACT_VECTOR_ELT with a constant
14470   // index, bail out.
14471   // TODO: Allow undef elements in some cases?
14472   if (any_of(N->ops(), [VT](SDValue Op) {
14473         return Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14474                !isa<ConstantSDNode>(Op.getOperand(1)) ||
14475                Op.getValueType() != VT.getVectorElementType();
14476       }))
14477     return SDValue();
14478 
14479   // Helper for obtaining an EXTRACT_VECTOR_ELT's constant index
14480   auto GetExtractIdx = [](SDValue Extract) {
14481     return cast<ConstantSDNode>(Extract.getOperand(1))->getSExtValue();
14482   };
14483 
14484   // The offset is defined to be the BUILD_VECTOR's first operand (assuming no
14485   // undef and little-endian).
14486   int Offset = GetExtractIdx(N->getOperand(0));
14487 
14488   // Compute the stride from the next operand.
14489   int Stride = GetExtractIdx(N->getOperand(1)) - Offset;
14490   SDValue ExtractedFromVec = N->getOperand(0).getOperand(0);
14491 
14492   // Proceed only if the stride and the types can be matched to a truncate.
14493   if ((Stride == 1 || !isPowerOf2_32(Stride)) ||
14494       (ExtractedFromVec.getValueType().getVectorNumElements() !=
14495        Stride * NumElems) ||
14496       (VT.getScalarSizeInBits() * Stride > 64))
14497     return SDValue();
14498 
14499   // Check remaining operands are consistent with the computed stride.
14500   for (unsigned i = 1; i != NumElems; ++i) {
14501     SDValue Op = N->getOperand(i);
14502 
14503     if ((Op.getOperand(0) != ExtractedFromVec) ||
14504         (GetExtractIdx(Op) != Stride * i + Offset))
14505       return SDValue();
14506   }
14507 
14508   SDValue Res = ExtractedFromVec;
14509   EVT TruncVT =
14510       VT.isFloatingPoint() ? VT.changeVectorElementTypeToInteger() : VT;
14511   if (Offset) {
14512     // If the first index is non-zero, need to shuffle elements of interest to
14513     // lower parts of the vector's elements the truncate will act upon.
14514     // TODO: Generalize to compute the permute-shuffle that will prepare any
14515     // element permutation for the truncate, and let the target decide if
14516     // profitable.
14517     EVT ExtractedVT = ExtractedFromVec.getValueType();
14518     SmallVector<int, 64> Mask;
14519     for (unsigned i = 0; i != NumElems; ++i) {
14520       Mask.push_back(Offset + i * Stride);
14521       // Pad the elements that will be lost after the truncate with undefs.
14522       Mask.append(Stride - 1, -1);
14523     }
14524     if (!TLI.isShuffleMaskLegal(Mask, ExtractedVT) ||
14525         !TLI.isDesirableToCombineBuildVectorToShuffleTruncate(Mask, ExtractedVT,
14526                                                               TruncVT))
14527       return SDValue();
14528     Res = DAG.getVectorShuffle(ExtractedVT, SDLoc(N), Res,
14529                                DAG.getUNDEF(ExtractedVT), Mask);
14530   }
14531   // Construct the truncate.
14532   LLVMContext &Ctx = *DAG.getContext();
14533   EVT NewVT = VT.getVectorVT(
14534       Ctx, EVT::getIntegerVT(Ctx, VT.getScalarSizeInBits() * Stride), NumElems);
14535 
14536   Res = DAG.getBitcast(NewVT, Res);
14537   Res = DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, Res);
14538   return DAG.getBitcast(VT, Res);
14539 }
14540 
14541 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14542   EVT VT = N->getValueType(0);
14543 
14544   // A vector built entirely of undefs is undef.
14545   if (ISD::allOperandsUndef(N))
14546     return DAG.getUNDEF(VT);
14547 
14548   // Check if we can express BUILD VECTOR via subvector extract.
14549   if (!LegalTypes && (N->getNumOperands() > 1)) {
14550     SDValue Op0 = N->getOperand(0);
14551     auto checkElem = [&](SDValue Op) -> uint64_t {
14552       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14553           (Op0.getOperand(0) == Op.getOperand(0)))
14554         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14555           return CNode->getZExtValue();
14556       return -1;
14557     };
14558 
14559     int Offset = checkElem(Op0);
14560     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14561       if (Offset + i != checkElem(N->getOperand(i))) {
14562         Offset = -1;
14563         break;
14564       }
14565     }
14566 
14567     if ((Offset == 0) &&
14568         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14569       return Op0.getOperand(0);
14570     if ((Offset != -1) &&
14571         ((Offset % N->getValueType(0).getVectorNumElements()) ==
14572          0)) // IDX must be multiple of output size.
14573       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14574                          Op0.getOperand(0), Op0.getOperand(1));
14575   }
14576 
14577   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14578     return V;
14579 
14580   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14581     return V;
14582 
14583   if (TLI.isDesirableToCombineBuildVectorToTruncate())
14584     if (SDValue V = reduceBuildVecToTrunc(N))
14585       return V;
14586 
14587   if (SDValue V = reduceBuildVecToShuffle(N))
14588     return V;
14589 
14590   return SDValue();
14591 }
14592 
14593 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14594   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14595   EVT OpVT = N->getOperand(0).getValueType();
14596 
14597   // If the operands are legal vectors, leave them alone.
14598   if (TLI.isTypeLegal(OpVT))
14599     return SDValue();
14600 
14601   SDLoc DL(N);
14602   EVT VT = N->getValueType(0);
14603   SmallVector<SDValue, 8> Ops;
14604 
14605   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14606   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14607 
14608   // Keep track of what we encounter.
14609   bool AnyInteger = false;
14610   bool AnyFP = false;
14611   for (const SDValue &Op : N->ops()) {
14612     if (ISD::BITCAST == Op.getOpcode() &&
14613         !Op.getOperand(0).getValueType().isVector())
14614       Ops.push_back(Op.getOperand(0));
14615     else if (ISD::UNDEF == Op.getOpcode())
14616       Ops.push_back(ScalarUndef);
14617     else
14618       return SDValue();
14619 
14620     // Note whether we encounter an integer or floating point scalar.
14621     // If it's neither, bail out, it could be something weird like x86mmx.
14622     EVT LastOpVT = Ops.back().getValueType();
14623     if (LastOpVT.isFloatingPoint())
14624       AnyFP = true;
14625     else if (LastOpVT.isInteger())
14626       AnyInteger = true;
14627     else
14628       return SDValue();
14629   }
14630 
14631   // If any of the operands is a floating point scalar bitcast to a vector,
14632   // use floating point types throughout, and bitcast everything.
14633   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14634   if (AnyFP) {
14635     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14636     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14637     if (AnyInteger) {
14638       for (SDValue &Op : Ops) {
14639         if (Op.getValueType() == SVT)
14640           continue;
14641         if (Op.isUndef())
14642           Op = ScalarUndef;
14643         else
14644           Op = DAG.getBitcast(SVT, Op);
14645       }
14646     }
14647   }
14648 
14649   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14650                                VT.getSizeInBits() / SVT.getSizeInBits());
14651   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14652 }
14653 
14654 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14655 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14656 // most two distinct vectors the same size as the result, attempt to turn this
14657 // into a legal shuffle.
14658 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14659   EVT VT = N->getValueType(0);
14660   EVT OpVT = N->getOperand(0).getValueType();
14661   int NumElts = VT.getVectorNumElements();
14662   int NumOpElts = OpVT.getVectorNumElements();
14663 
14664   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14665   SmallVector<int, 8> Mask;
14666 
14667   for (SDValue Op : N->ops()) {
14668     // Peek through any bitcast.
14669     Op = peekThroughBitcast(Op);
14670 
14671     // UNDEF nodes convert to UNDEF shuffle mask values.
14672     if (Op.isUndef()) {
14673       Mask.append((unsigned)NumOpElts, -1);
14674       continue;
14675     }
14676 
14677     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14678       return SDValue();
14679 
14680     // What vector are we extracting the subvector from and at what index?
14681     SDValue ExtVec = Op.getOperand(0);
14682 
14683     // We want the EVT of the original extraction to correctly scale the
14684     // extraction index.
14685     EVT ExtVT = ExtVec.getValueType();
14686 
14687     // Peek through any bitcast.
14688     ExtVec = peekThroughBitcast(ExtVec);
14689 
14690     // UNDEF nodes convert to UNDEF shuffle mask values.
14691     if (ExtVec.isUndef()) {
14692       Mask.append((unsigned)NumOpElts, -1);
14693       continue;
14694     }
14695 
14696     if (!isa<ConstantSDNode>(Op.getOperand(1)))
14697       return SDValue();
14698     int ExtIdx = Op.getConstantOperandVal(1);
14699 
14700     // Ensure that we are extracting a subvector from a vector the same
14701     // size as the result.
14702     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14703       return SDValue();
14704 
14705     // Scale the subvector index to account for any bitcast.
14706     int NumExtElts = ExtVT.getVectorNumElements();
14707     if (0 == (NumExtElts % NumElts))
14708       ExtIdx /= (NumExtElts / NumElts);
14709     else if (0 == (NumElts % NumExtElts))
14710       ExtIdx *= (NumElts / NumExtElts);
14711     else
14712       return SDValue();
14713 
14714     // At most we can reference 2 inputs in the final shuffle.
14715     if (SV0.isUndef() || SV0 == ExtVec) {
14716       SV0 = ExtVec;
14717       for (int i = 0; i != NumOpElts; ++i)
14718         Mask.push_back(i + ExtIdx);
14719     } else if (SV1.isUndef() || SV1 == ExtVec) {
14720       SV1 = ExtVec;
14721       for (int i = 0; i != NumOpElts; ++i)
14722         Mask.push_back(i + ExtIdx + NumElts);
14723     } else {
14724       return SDValue();
14725     }
14726   }
14727 
14728   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14729     return SDValue();
14730 
14731   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14732                               DAG.getBitcast(VT, SV1), Mask);
14733 }
14734 
14735 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14736   // If we only have one input vector, we don't need to do any concatenation.
14737   if (N->getNumOperands() == 1)
14738     return N->getOperand(0);
14739 
14740   // Check if all of the operands are undefs.
14741   EVT VT = N->getValueType(0);
14742   if (ISD::allOperandsUndef(N))
14743     return DAG.getUNDEF(VT);
14744 
14745   // Optimize concat_vectors where all but the first of the vectors are undef.
14746   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14747         return Op.isUndef();
14748       })) {
14749     SDValue In = N->getOperand(0);
14750     assert(In.getValueType().isVector() && "Must concat vectors");
14751 
14752     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14753     if (In->getOpcode() == ISD::BITCAST &&
14754         !In->getOperand(0)->getValueType(0).isVector()) {
14755       SDValue Scalar = In->getOperand(0);
14756 
14757       // If the bitcast type isn't legal, it might be a trunc of a legal type;
14758       // look through the trunc so we can still do the transform:
14759       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14760       if (Scalar->getOpcode() == ISD::TRUNCATE &&
14761           !TLI.isTypeLegal(Scalar.getValueType()) &&
14762           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14763         Scalar = Scalar->getOperand(0);
14764 
14765       EVT SclTy = Scalar->getValueType(0);
14766 
14767       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14768         return SDValue();
14769 
14770       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14771       if (VNTNumElms < 2)
14772         return SDValue();
14773 
14774       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14775       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14776         return SDValue();
14777 
14778       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14779       return DAG.getBitcast(VT, Res);
14780     }
14781   }
14782 
14783   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14784   // We have already tested above for an UNDEF only concatenation.
14785   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14786   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14787   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14788     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14789   };
14790   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14791     SmallVector<SDValue, 8> Opnds;
14792     EVT SVT = VT.getScalarType();
14793 
14794     EVT MinVT = SVT;
14795     if (!SVT.isFloatingPoint()) {
14796       // If BUILD_VECTOR are from built from integer, they may have different
14797       // operand types. Get the smallest type and truncate all operands to it.
14798       bool FoundMinVT = false;
14799       for (const SDValue &Op : N->ops())
14800         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14801           EVT OpSVT = Op.getOperand(0)->getValueType(0);
14802           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14803           FoundMinVT = true;
14804         }
14805       assert(FoundMinVT && "Concat vector type mismatch");
14806     }
14807 
14808     for (const SDValue &Op : N->ops()) {
14809       EVT OpVT = Op.getValueType();
14810       unsigned NumElts = OpVT.getVectorNumElements();
14811 
14812       if (ISD::UNDEF == Op.getOpcode())
14813         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14814 
14815       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14816         if (SVT.isFloatingPoint()) {
14817           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14818           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14819         } else {
14820           for (unsigned i = 0; i != NumElts; ++i)
14821             Opnds.push_back(
14822                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14823         }
14824       }
14825     }
14826 
14827     assert(VT.getVectorNumElements() == Opnds.size() &&
14828            "Concat vector type mismatch");
14829     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14830   }
14831 
14832   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14833   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14834     return V;
14835 
14836   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14837   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14838     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14839       return V;
14840 
14841   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14842   // nodes often generate nop CONCAT_VECTOR nodes.
14843   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14844   // place the incoming vectors at the exact same location.
14845   SDValue SingleSource = SDValue();
14846   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14847 
14848   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14849     SDValue Op = N->getOperand(i);
14850 
14851     if (Op.isUndef())
14852       continue;
14853 
14854     // Check if this is the identity extract:
14855     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14856       return SDValue();
14857 
14858     // Find the single incoming vector for the extract_subvector.
14859     if (SingleSource.getNode()) {
14860       if (Op.getOperand(0) != SingleSource)
14861         return SDValue();
14862     } else {
14863       SingleSource = Op.getOperand(0);
14864 
14865       // Check the source type is the same as the type of the result.
14866       // If not, this concat may extend the vector, so we can not
14867       // optimize it away.
14868       if (SingleSource.getValueType() != N->getValueType(0))
14869         return SDValue();
14870     }
14871 
14872     unsigned IdentityIndex = i * PartNumElem;
14873     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14874     // The extract index must be constant.
14875     if (!CS)
14876       return SDValue();
14877 
14878     // Check that we are reading from the identity index.
14879     if (CS->getZExtValue() != IdentityIndex)
14880       return SDValue();
14881   }
14882 
14883   if (SingleSource.getNode())
14884     return SingleSource;
14885 
14886   return SDValue();
14887 }
14888 
14889 /// If we are extracting a subvector produced by a wide binary operator with at
14890 /// at least one operand that was the result of a vector concatenation, then try
14891 /// to use the narrow vector operands directly to avoid the concatenation and
14892 /// extraction.
14893 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
14894   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
14895   // some of these bailouts with other transforms.
14896 
14897   // The extract index must be a constant, so we can map it to a concat operand.
14898   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14899   if (!ExtractIndex)
14900     return SDValue();
14901 
14902   // Only handle the case where we are doubling and then halving. A larger ratio
14903   // may require more than two narrow binops to replace the wide binop.
14904   EVT VT = Extract->getValueType(0);
14905   unsigned NumElems = VT.getVectorNumElements();
14906   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
14907          "Extract index is not a multiple of the vector length.");
14908   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
14909     return SDValue();
14910 
14911   // We are looking for an optionally bitcasted wide vector binary operator
14912   // feeding an extract subvector.
14913   SDValue BinOp = peekThroughBitcast(Extract->getOperand(0));
14914 
14915   // TODO: The motivating case for this transform is an x86 AVX1 target. That
14916   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
14917   // flavors, but no other 256-bit integer support. This could be extended to
14918   // handle any binop, but that may require fixing/adding other folds to avoid
14919   // codegen regressions.
14920   unsigned BOpcode = BinOp.getOpcode();
14921   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
14922     return SDValue();
14923 
14924   // The binop must be a vector type, so we can chop it in half.
14925   EVT WideBVT = BinOp.getValueType();
14926   if (!WideBVT.isVector())
14927     return SDValue();
14928 
14929   // Bail out if the target does not support a narrower version of the binop.
14930   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
14931                                    WideBVT.getVectorNumElements() / 2);
14932   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14933   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
14934     return SDValue();
14935 
14936   // Peek through bitcasts of the binary operator operands if needed.
14937   SDValue LHS = peekThroughBitcast(BinOp.getOperand(0));
14938   SDValue RHS = peekThroughBitcast(BinOp.getOperand(1));
14939 
14940   // We need at least one concatenation operation of a binop operand to make
14941   // this transform worthwhile. The concat must double the input vector sizes.
14942   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
14943   bool ConcatL =
14944       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
14945   bool ConcatR =
14946       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
14947   if (!ConcatL && !ConcatR)
14948     return SDValue();
14949 
14950   // If one of the binop operands was not the result of a concat, we must
14951   // extract a half-sized operand for our new narrow binop. We can't just reuse
14952   // the original extract index operand because we may have bitcasted.
14953   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
14954   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
14955   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
14956   SDLoc DL(Extract);
14957 
14958   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
14959   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
14960   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
14961   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
14962                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14963                                     BinOp.getOperand(0),
14964                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14965 
14966   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
14967                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14968                                     BinOp.getOperand(1),
14969                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14970 
14971   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
14972   return DAG.getBitcast(VT, NarrowBinOp);
14973 }
14974 
14975 /// If we are extracting a subvector from a wide vector load, convert to a
14976 /// narrow load to eliminate the extraction:
14977 /// (extract_subvector (load wide vector)) --> (load narrow vector)
14978 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
14979   // TODO: Add support for big-endian. The offset calculation must be adjusted.
14980   if (DAG.getDataLayout().isBigEndian())
14981     return SDValue();
14982 
14983   // TODO: The one-use check is overly conservative. Check the cost of the
14984   // extract instead or remove that condition entirely.
14985   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
14986   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14987   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
14988       !ExtIdx)
14989     return SDValue();
14990 
14991   // The narrow load will be offset from the base address of the old load if
14992   // we are extracting from something besides index 0 (little-endian).
14993   EVT VT = Extract->getValueType(0);
14994   SDLoc DL(Extract);
14995   SDValue BaseAddr = Ld->getOperand(1);
14996   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
14997 
14998   // TODO: Use "BaseIndexOffset" to make this more effective.
14999   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
15000   MachineFunction &MF = DAG.getMachineFunction();
15001   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
15002                                                    VT.getStoreSize());
15003   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
15004   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
15005   return NewLd;
15006 }
15007 
15008 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
15009   EVT NVT = N->getValueType(0);
15010   SDValue V = N->getOperand(0);
15011 
15012   // Extract from UNDEF is UNDEF.
15013   if (V.isUndef())
15014     return DAG.getUNDEF(NVT);
15015 
15016   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
15017     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
15018       return NarrowLoad;
15019 
15020   // Combine:
15021   //    (extract_subvec (concat V1, V2, ...), i)
15022   // Into:
15023   //    Vi if possible
15024   // Only operand 0 is checked as 'concat' assumes all inputs of the same
15025   // type.
15026   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
15027       isa<ConstantSDNode>(N->getOperand(1)) &&
15028       V->getOperand(0).getValueType() == NVT) {
15029     unsigned Idx = N->getConstantOperandVal(1);
15030     unsigned NumElems = NVT.getVectorNumElements();
15031     assert((Idx % NumElems) == 0 &&
15032            "IDX in concat is not a multiple of the result vector length.");
15033     return V->getOperand(Idx / NumElems);
15034   }
15035 
15036   // Skip bitcasting
15037   V = peekThroughBitcast(V);
15038 
15039   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
15040     // Handle only simple case where vector being inserted and vector
15041     // being extracted are of same size.
15042     EVT SmallVT = V->getOperand(1).getValueType();
15043     if (!NVT.bitsEq(SmallVT))
15044       return SDValue();
15045 
15046     // Only handle cases where both indexes are constants.
15047     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
15048     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
15049 
15050     if (InsIdx && ExtIdx) {
15051       // Combine:
15052       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
15053       // Into:
15054       //    indices are equal or bit offsets are equal => V1
15055       //    otherwise => (extract_subvec V1, ExtIdx)
15056       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
15057           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
15058         return DAG.getBitcast(NVT, V->getOperand(1));
15059       return DAG.getNode(
15060           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
15061           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
15062           N->getOperand(1));
15063     }
15064   }
15065 
15066   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
15067     return NarrowBOp;
15068 
15069   return SDValue();
15070 }
15071 
15072 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
15073                                                  SDValue V, SelectionDAG &DAG) {
15074   SDLoc DL(V);
15075   EVT VT = V.getValueType();
15076 
15077   switch (V.getOpcode()) {
15078   default:
15079     return V;
15080 
15081   case ISD::CONCAT_VECTORS: {
15082     EVT OpVT = V->getOperand(0).getValueType();
15083     int OpSize = OpVT.getVectorNumElements();
15084     SmallBitVector OpUsedElements(OpSize, false);
15085     bool FoundSimplification = false;
15086     SmallVector<SDValue, 4> NewOps;
15087     NewOps.reserve(V->getNumOperands());
15088     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
15089       SDValue Op = V->getOperand(i);
15090       bool OpUsed = false;
15091       for (int j = 0; j < OpSize; ++j)
15092         if (UsedElements[i * OpSize + j]) {
15093           OpUsedElements[j] = true;
15094           OpUsed = true;
15095         }
15096       NewOps.push_back(
15097           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
15098                  : DAG.getUNDEF(OpVT));
15099       FoundSimplification |= Op == NewOps.back();
15100       OpUsedElements.reset();
15101     }
15102     if (FoundSimplification)
15103       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
15104     return V;
15105   }
15106 
15107   case ISD::INSERT_SUBVECTOR: {
15108     SDValue BaseV = V->getOperand(0);
15109     SDValue SubV = V->getOperand(1);
15110     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
15111     if (!IdxN)
15112       return V;
15113 
15114     int SubSize = SubV.getValueType().getVectorNumElements();
15115     int Idx = IdxN->getZExtValue();
15116     bool SubVectorUsed = false;
15117     SmallBitVector SubUsedElements(SubSize, false);
15118     for (int i = 0; i < SubSize; ++i)
15119       if (UsedElements[i + Idx]) {
15120         SubVectorUsed = true;
15121         SubUsedElements[i] = true;
15122         UsedElements[i + Idx] = false;
15123       }
15124 
15125     // Now recurse on both the base and sub vectors.
15126     SDValue SimplifiedSubV =
15127         SubVectorUsed
15128             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
15129             : DAG.getUNDEF(SubV.getValueType());
15130     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
15131     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
15132       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15133                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
15134     return V;
15135   }
15136   }
15137 }
15138 
15139 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
15140                                        SDValue N1, SelectionDAG &DAG) {
15141   EVT VT = SVN->getValueType(0);
15142   int NumElts = VT.getVectorNumElements();
15143   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
15144   for (int M : SVN->getMask())
15145     if (M >= 0 && M < NumElts)
15146       N0UsedElements[M] = true;
15147     else if (M >= NumElts)
15148       N1UsedElements[M - NumElts] = true;
15149 
15150   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
15151   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
15152   if (S0 == N0 && S1 == N1)
15153     return SDValue();
15154 
15155   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
15156 }
15157 
15158 static SDValue simplifyShuffleMask(ShuffleVectorSDNode *SVN, SDValue N0,
15159                                    SDValue N1, SelectionDAG &DAG) {
15160   auto isUndefElt = [](SDValue V, int Idx) {
15161     // TODO - handle more cases as required.
15162     if (V.getOpcode() == ISD::BUILD_VECTOR)
15163       return V.getOperand(Idx).isUndef();
15164     return false;
15165   };
15166 
15167   EVT VT = SVN->getValueType(0);
15168   unsigned NumElts = VT.getVectorNumElements();
15169 
15170   bool Changed = false;
15171   SmallVector<int, 8> NewMask;
15172   for (unsigned i = 0; i != NumElts; ++i) {
15173     int Idx = SVN->getMaskElt(i);
15174     if ((0 <= Idx && Idx < (int)NumElts && isUndefElt(N0, Idx)) ||
15175         ((int)NumElts < Idx && isUndefElt(N1, Idx - NumElts))) {
15176       Changed = true;
15177       Idx = -1;
15178     }
15179     NewMask.push_back(Idx);
15180   }
15181   if (Changed)
15182     return DAG.getVectorShuffle(VT, SDLoc(SVN), N0, N1, NewMask);
15183 
15184   return SDValue();
15185 }
15186 
15187 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
15188 // or turn a shuffle of a single concat into simpler shuffle then concat.
15189 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
15190   EVT VT = N->getValueType(0);
15191   unsigned NumElts = VT.getVectorNumElements();
15192 
15193   SDValue N0 = N->getOperand(0);
15194   SDValue N1 = N->getOperand(1);
15195   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15196 
15197   SmallVector<SDValue, 4> Ops;
15198   EVT ConcatVT = N0.getOperand(0).getValueType();
15199   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15200   unsigned NumConcats = NumElts / NumElemsPerConcat;
15201 
15202   // Special case: shuffle(concat(A,B)) can be more efficiently represented
15203   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15204   // half vector elements.
15205   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15206       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15207                   SVN->getMask().end(), [](int i) { return i == -1; })) {
15208     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15209                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15210     N1 = DAG.getUNDEF(ConcatVT);
15211     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15212   }
15213 
15214   // Look at every vector that's inserted. We're looking for exact
15215   // subvector-sized copies from a concatenated vector
15216   for (unsigned I = 0; I != NumConcats; ++I) {
15217     // Make sure we're dealing with a copy.
15218     unsigned Begin = I * NumElemsPerConcat;
15219     bool AllUndef = true, NoUndef = true;
15220     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15221       if (SVN->getMaskElt(J) >= 0)
15222         AllUndef = false;
15223       else
15224         NoUndef = false;
15225     }
15226 
15227     if (NoUndef) {
15228       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15229         return SDValue();
15230 
15231       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15232         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15233           return SDValue();
15234 
15235       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15236       if (FirstElt < N0.getNumOperands())
15237         Ops.push_back(N0.getOperand(FirstElt));
15238       else
15239         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15240 
15241     } else if (AllUndef) {
15242       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15243     } else { // Mixed with general masks and undefs, can't do optimization.
15244       return SDValue();
15245     }
15246   }
15247 
15248   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15249 }
15250 
15251 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15252 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15253 //
15254 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15255 // a simplification in some sense, but it isn't appropriate in general: some
15256 // BUILD_VECTORs are substantially cheaper than others. The general case
15257 // of a BUILD_VECTOR requires inserting each element individually (or
15258 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15259 // all constants is a single constant pool load.  A BUILD_VECTOR where each
15260 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
15261 // are undef lowers to a small number of element insertions.
15262 //
15263 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15264 // We don't fold shuffles where one side is a non-zero constant, and we don't
15265 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
15266 // non-constant operands. This seems to work out reasonably well in practice.
15267 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15268                                        SelectionDAG &DAG,
15269                                        const TargetLowering &TLI) {
15270   EVT VT = SVN->getValueType(0);
15271   unsigned NumElts = VT.getVectorNumElements();
15272   SDValue N0 = SVN->getOperand(0);
15273   SDValue N1 = SVN->getOperand(1);
15274 
15275   if (!N0->hasOneUse() || !N1->hasOneUse())
15276     return SDValue();
15277   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15278   // discussed above.
15279   if (!N1.isUndef()) {
15280     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15281     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15282     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15283       return SDValue();
15284     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15285       return SDValue();
15286   }
15287 
15288   SmallVector<SDValue, 8> Ops;
15289   SmallSet<SDValue, 16> DuplicateOps;
15290   for (int M : SVN->getMask()) {
15291     SDValue Op = DAG.getUNDEF(VT.getScalarType());
15292     if (M >= 0) {
15293       int Idx = M < (int)NumElts ? M : M - NumElts;
15294       SDValue &S = (M < (int)NumElts ? N0 : N1);
15295       if (S.getOpcode() == ISD::BUILD_VECTOR) {
15296         Op = S.getOperand(Idx);
15297       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
15298         if (Idx == 0)
15299           Op = S.getOperand(0);
15300       } else {
15301         // Operand can't be combined - bail out.
15302         return SDValue();
15303       }
15304     }
15305 
15306     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
15307     // fine, but it's likely to generate low-quality code if the target can't
15308     // reconstruct an appropriate shuffle.
15309     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
15310       if (!DuplicateOps.insert(Op).second)
15311         return SDValue();
15312 
15313     Ops.push_back(Op);
15314   }
15315   // BUILD_VECTOR requires all inputs to be of the same type, find the
15316   // maximum type and extend them all.
15317   EVT SVT = VT.getScalarType();
15318   if (SVT.isInteger())
15319     for (SDValue &Op : Ops)
15320       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
15321   if (SVT != VT.getScalarType())
15322     for (SDValue &Op : Ops)
15323       Op = TLI.isZExtFree(Op.getValueType(), SVT)
15324                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
15325                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
15326   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
15327 }
15328 
15329 // Match shuffles that can be converted to any_vector_extend_in_reg.
15330 // This is often generated during legalization.
15331 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
15332 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15333 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15334                                             SelectionDAG &DAG,
15335                                             const TargetLowering &TLI,
15336                                             bool LegalOperations) {
15337   EVT VT = SVN->getValueType(0);
15338   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15339 
15340   // TODO Add support for big-endian when we have a test case.
15341   if (!VT.isInteger() || IsBigEndian)
15342     return SDValue();
15343 
15344   unsigned NumElts = VT.getVectorNumElements();
15345   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15346   ArrayRef<int> Mask = SVN->getMask();
15347   SDValue N0 = SVN->getOperand(0);
15348 
15349   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15350   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15351     for (unsigned i = 0; i != NumElts; ++i) {
15352       if (Mask[i] < 0)
15353         continue;
15354       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15355         continue;
15356       return false;
15357     }
15358     return true;
15359   };
15360 
15361   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15362   // power-of-2 extensions as they are the most likely.
15363   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15364     if (!isAnyExtend(Scale))
15365       continue;
15366 
15367     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15368     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15369     if (!LegalOperations ||
15370         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15371       return DAG.getBitcast(VT,
15372                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15373   }
15374 
15375   return SDValue();
15376 }
15377 
15378 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15379 // each source element of a large type into the lowest elements of a smaller
15380 // destination type. This is often generated during legalization.
15381 // If the source node itself was a '*_extend_vector_inreg' node then we should
15382 // then be able to remove it.
15383 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15384                                         SelectionDAG &DAG) {
15385   EVT VT = SVN->getValueType(0);
15386   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15387 
15388   // TODO Add support for big-endian when we have a test case.
15389   if (!VT.isInteger() || IsBigEndian)
15390     return SDValue();
15391 
15392   SDValue N0 = peekThroughBitcast(SVN->getOperand(0));
15393 
15394   unsigned Opcode = N0.getOpcode();
15395   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15396       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15397       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15398     return SDValue();
15399 
15400   SDValue N00 = N0.getOperand(0);
15401   ArrayRef<int> Mask = SVN->getMask();
15402   unsigned NumElts = VT.getVectorNumElements();
15403   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15404   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15405   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15406 
15407   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15408     return SDValue();
15409   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15410 
15411   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15412   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15413   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15414   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15415     for (unsigned i = 0; i != NumElts; ++i) {
15416       if (Mask[i] < 0)
15417         continue;
15418       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15419         continue;
15420       return false;
15421     }
15422     return true;
15423   };
15424 
15425   // At the moment we just handle the case where we've truncated back to the
15426   // same size as before the extension.
15427   // TODO: handle more extension/truncation cases as cases arise.
15428   if (EltSizeInBits != ExtSrcSizeInBits)
15429     return SDValue();
15430 
15431   // We can remove *extend_vector_inreg only if the truncation happens at
15432   // the same scale as the extension.
15433   if (isTruncate(ExtScale))
15434     return DAG.getBitcast(VT, N00);
15435 
15436   return SDValue();
15437 }
15438 
15439 // Combine shuffles of splat-shuffles of the form:
15440 // shuffle (shuffle V, undef, splat-mask), undef, M
15441 // If splat-mask contains undef elements, we need to be careful about
15442 // introducing undef's in the folded mask which are not the result of composing
15443 // the masks of the shuffles.
15444 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15445                                      ShuffleVectorSDNode *Splat,
15446                                      SelectionDAG &DAG) {
15447   ArrayRef<int> SplatMask = Splat->getMask();
15448   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15449 
15450   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15451   // every undef mask element in the splat-shuffle has a corresponding undef
15452   // element in the user-shuffle's mask or if the composition of mask elements
15453   // would result in undef.
15454   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15455   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15456   //   In this case it is not legal to simplify to the splat-shuffle because we
15457   //   may be exposing the users of the shuffle an undef element at index 1
15458   //   which was not there before the combine.
15459   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15460   //   In this case the composition of masks yields SplatMask, so it's ok to
15461   //   simplify to the splat-shuffle.
15462   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15463   //   In this case the composed mask includes all undef elements of SplatMask
15464   //   and in addition sets element zero to undef. It is safe to simplify to
15465   //   the splat-shuffle.
15466   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15467                                        ArrayRef<int> SplatMask) {
15468     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15469       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15470           SplatMask[UserMask[i]] != -1)
15471         return false;
15472     return true;
15473   };
15474   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15475     return SDValue(Splat, 0);
15476 
15477   // Create a new shuffle with a mask that is composed of the two shuffles'
15478   // masks.
15479   SmallVector<int, 32> NewMask;
15480   for (int Idx : UserMask)
15481     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15482 
15483   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15484                               Splat->getOperand(0), Splat->getOperand(1),
15485                               NewMask);
15486 }
15487 
15488 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
15489   EVT VT = N->getValueType(0);
15490   unsigned NumElts = VT.getVectorNumElements();
15491 
15492   SDValue N0 = N->getOperand(0);
15493   SDValue N1 = N->getOperand(1);
15494 
15495   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
15496 
15497   // Canonicalize shuffle undef, undef -> undef
15498   if (N0.isUndef() && N1.isUndef())
15499     return DAG.getUNDEF(VT);
15500 
15501   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15502 
15503   // Canonicalize shuffle v, v -> v, undef
15504   if (N0 == N1) {
15505     SmallVector<int, 8> NewMask;
15506     for (unsigned i = 0; i != NumElts; ++i) {
15507       int Idx = SVN->getMaskElt(i);
15508       if (Idx >= (int)NumElts) Idx -= NumElts;
15509       NewMask.push_back(Idx);
15510     }
15511     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
15512   }
15513 
15514   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
15515   if (N0.isUndef())
15516     return DAG.getCommutedVectorShuffle(*SVN);
15517 
15518   // Remove references to rhs if it is undef
15519   if (N1.isUndef()) {
15520     bool Changed = false;
15521     SmallVector<int, 8> NewMask;
15522     for (unsigned i = 0; i != NumElts; ++i) {
15523       int Idx = SVN->getMaskElt(i);
15524       if (Idx >= (int)NumElts) {
15525         Idx = -1;
15526         Changed = true;
15527       }
15528       NewMask.push_back(Idx);
15529     }
15530     if (Changed)
15531       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
15532   }
15533 
15534   // Simplify shuffle mask if a referenced element is UNDEF.
15535   if (SDValue V = simplifyShuffleMask(SVN, N0, N1, DAG))
15536     return V;
15537 
15538   // A shuffle of a single vector that is a splat can always be folded.
15539   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
15540     if (N1->isUndef() && N0Shuf->isSplat())
15541       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
15542 
15543   // If it is a splat, check if the argument vector is another splat or a
15544   // build_vector.
15545   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
15546     SDNode *V = N0.getNode();
15547 
15548     // If this is a bit convert that changes the element type of the vector but
15549     // not the number of vector elements, look through it.  Be careful not to
15550     // look though conversions that change things like v4f32 to v2f64.
15551     if (V->getOpcode() == ISD::BITCAST) {
15552       SDValue ConvInput = V->getOperand(0);
15553       if (ConvInput.getValueType().isVector() &&
15554           ConvInput.getValueType().getVectorNumElements() == NumElts)
15555         V = ConvInput.getNode();
15556     }
15557 
15558     if (V->getOpcode() == ISD::BUILD_VECTOR) {
15559       assert(V->getNumOperands() == NumElts &&
15560              "BUILD_VECTOR has wrong number of operands");
15561       SDValue Base;
15562       bool AllSame = true;
15563       for (unsigned i = 0; i != NumElts; ++i) {
15564         if (!V->getOperand(i).isUndef()) {
15565           Base = V->getOperand(i);
15566           break;
15567         }
15568       }
15569       // Splat of <u, u, u, u>, return <u, u, u, u>
15570       if (!Base.getNode())
15571         return N0;
15572       for (unsigned i = 0; i != NumElts; ++i) {
15573         if (V->getOperand(i) != Base) {
15574           AllSame = false;
15575           break;
15576         }
15577       }
15578       // Splat of <x, x, x, x>, return <x, x, x, x>
15579       if (AllSame)
15580         return N0;
15581 
15582       // Canonicalize any other splat as a build_vector.
15583       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
15584       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
15585       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
15586 
15587       // We may have jumped through bitcasts, so the type of the
15588       // BUILD_VECTOR may not match the type of the shuffle.
15589       if (V->getValueType(0) != VT)
15590         NewBV = DAG.getBitcast(VT, NewBV);
15591       return NewBV;
15592     }
15593   }
15594 
15595   // There are various patterns used to build up a vector from smaller vectors,
15596   // subvectors, or elements. Scan chains of these and replace unused insertions
15597   // or components with undef.
15598   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
15599     return S;
15600 
15601   // Match shuffles that can be converted to any_vector_extend_in_reg.
15602   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
15603     return V;
15604 
15605   // Combine "truncate_vector_in_reg" style shuffles.
15606   if (SDValue V = combineTruncationShuffle(SVN, DAG))
15607     return V;
15608 
15609   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
15610       Level < AfterLegalizeVectorOps &&
15611       (N1.isUndef() ||
15612       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
15613        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
15614     if (SDValue V = partitionShuffleOfConcats(N, DAG))
15615       return V;
15616   }
15617 
15618   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15619   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15620   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15621     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
15622       return Res;
15623 
15624   // If this shuffle only has a single input that is a bitcasted shuffle,
15625   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
15626   // back to their original types.
15627   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
15628       N1.isUndef() && Level < AfterLegalizeVectorOps &&
15629       TLI.isTypeLegal(VT)) {
15630 
15631     // Peek through the bitcast only if there is one user.
15632     SDValue BC0 = N0;
15633     while (BC0.getOpcode() == ISD::BITCAST) {
15634       if (!BC0.hasOneUse())
15635         break;
15636       BC0 = BC0.getOperand(0);
15637     }
15638 
15639     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
15640       if (Scale == 1)
15641         return SmallVector<int, 8>(Mask.begin(), Mask.end());
15642 
15643       SmallVector<int, 8> NewMask;
15644       for (int M : Mask)
15645         for (int s = 0; s != Scale; ++s)
15646           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15647       return NewMask;
15648     };
15649 
15650     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15651       EVT SVT = VT.getScalarType();
15652       EVT InnerVT = BC0->getValueType(0);
15653       EVT InnerSVT = InnerVT.getScalarType();
15654 
15655       // Determine which shuffle works with the smaller scalar type.
15656       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15657       EVT ScaleSVT = ScaleVT.getScalarType();
15658 
15659       if (TLI.isTypeLegal(ScaleVT) &&
15660           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15661           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15662 
15663         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15664         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15665 
15666         // Scale the shuffle masks to the smaller scalar type.
15667         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15668         SmallVector<int, 8> InnerMask =
15669             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15670         SmallVector<int, 8> OuterMask =
15671             ScaleShuffleMask(SVN->getMask(), OuterScale);
15672 
15673         // Merge the shuffle masks.
15674         SmallVector<int, 8> NewMask;
15675         for (int M : OuterMask)
15676           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15677 
15678         // Test for shuffle mask legality over both commutations.
15679         SDValue SV0 = BC0->getOperand(0);
15680         SDValue SV1 = BC0->getOperand(1);
15681         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15682         if (!LegalMask) {
15683           std::swap(SV0, SV1);
15684           ShuffleVectorSDNode::commuteMask(NewMask);
15685           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15686         }
15687 
15688         if (LegalMask) {
15689           SV0 = DAG.getBitcast(ScaleVT, SV0);
15690           SV1 = DAG.getBitcast(ScaleVT, SV1);
15691           return DAG.getBitcast(
15692               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15693         }
15694       }
15695     }
15696   }
15697 
15698   // Canonicalize shuffles according to rules:
15699   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15700   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15701   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15702   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15703       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15704       TLI.isTypeLegal(VT)) {
15705     // The incoming shuffle must be of the same type as the result of the
15706     // current shuffle.
15707     assert(N1->getOperand(0).getValueType() == VT &&
15708            "Shuffle types don't match");
15709 
15710     SDValue SV0 = N1->getOperand(0);
15711     SDValue SV1 = N1->getOperand(1);
15712     bool HasSameOp0 = N0 == SV0;
15713     bool IsSV1Undef = SV1.isUndef();
15714     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15715       // Commute the operands of this shuffle so that next rule
15716       // will trigger.
15717       return DAG.getCommutedVectorShuffle(*SVN);
15718   }
15719 
15720   // Try to fold according to rules:
15721   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15722   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15723   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15724   // Don't try to fold shuffles with illegal type.
15725   // Only fold if this shuffle is the only user of the other shuffle.
15726   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15727       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15728     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15729 
15730     // Don't try to fold splats; they're likely to simplify somehow, or they
15731     // might be free.
15732     if (OtherSV->isSplat())
15733       return SDValue();
15734 
15735     // The incoming shuffle must be of the same type as the result of the
15736     // current shuffle.
15737     assert(OtherSV->getOperand(0).getValueType() == VT &&
15738            "Shuffle types don't match");
15739 
15740     SDValue SV0, SV1;
15741     SmallVector<int, 4> Mask;
15742     // Compute the combined shuffle mask for a shuffle with SV0 as the first
15743     // operand, and SV1 as the second operand.
15744     for (unsigned i = 0; i != NumElts; ++i) {
15745       int Idx = SVN->getMaskElt(i);
15746       if (Idx < 0) {
15747         // Propagate Undef.
15748         Mask.push_back(Idx);
15749         continue;
15750       }
15751 
15752       SDValue CurrentVec;
15753       if (Idx < (int)NumElts) {
15754         // This shuffle index refers to the inner shuffle N0. Lookup the inner
15755         // shuffle mask to identify which vector is actually referenced.
15756         Idx = OtherSV->getMaskElt(Idx);
15757         if (Idx < 0) {
15758           // Propagate Undef.
15759           Mask.push_back(Idx);
15760           continue;
15761         }
15762 
15763         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15764                                            : OtherSV->getOperand(1);
15765       } else {
15766         // This shuffle index references an element within N1.
15767         CurrentVec = N1;
15768       }
15769 
15770       // Simple case where 'CurrentVec' is UNDEF.
15771       if (CurrentVec.isUndef()) {
15772         Mask.push_back(-1);
15773         continue;
15774       }
15775 
15776       // Canonicalize the shuffle index. We don't know yet if CurrentVec
15777       // will be the first or second operand of the combined shuffle.
15778       Idx = Idx % NumElts;
15779       if (!SV0.getNode() || SV0 == CurrentVec) {
15780         // Ok. CurrentVec is the left hand side.
15781         // Update the mask accordingly.
15782         SV0 = CurrentVec;
15783         Mask.push_back(Idx);
15784         continue;
15785       }
15786 
15787       // Bail out if we cannot convert the shuffle pair into a single shuffle.
15788       if (SV1.getNode() && SV1 != CurrentVec)
15789         return SDValue();
15790 
15791       // Ok. CurrentVec is the right hand side.
15792       // Update the mask accordingly.
15793       SV1 = CurrentVec;
15794       Mask.push_back(Idx + NumElts);
15795     }
15796 
15797     // Check if all indices in Mask are Undef. In case, propagate Undef.
15798     bool isUndefMask = true;
15799     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
15800       isUndefMask &= Mask[i] < 0;
15801 
15802     if (isUndefMask)
15803       return DAG.getUNDEF(VT);
15804 
15805     if (!SV0.getNode())
15806       SV0 = DAG.getUNDEF(VT);
15807     if (!SV1.getNode())
15808       SV1 = DAG.getUNDEF(VT);
15809 
15810     // Avoid introducing shuffles with illegal mask.
15811     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
15812       ShuffleVectorSDNode::commuteMask(Mask);
15813 
15814       if (!TLI.isShuffleMaskLegal(Mask, VT))
15815         return SDValue();
15816 
15817       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
15818       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
15819       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
15820       std::swap(SV0, SV1);
15821     }
15822 
15823     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15824     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15825     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15826     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
15827   }
15828 
15829   return SDValue();
15830 }
15831 
15832 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
15833   SDValue InVal = N->getOperand(0);
15834   EVT VT = N->getValueType(0);
15835 
15836   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
15837   // with a VECTOR_SHUFFLE and possible truncate.
15838   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15839     SDValue InVec = InVal->getOperand(0);
15840     SDValue EltNo = InVal->getOperand(1);
15841     auto InVecT = InVec.getValueType();
15842     if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
15843       SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
15844       int Elt = C0->getZExtValue();
15845       NewMask[0] = Elt;
15846       SDValue Val;
15847       // If we have an implict truncate do truncate here as long as it's legal.
15848       // if it's not legal, this should
15849       if (VT.getScalarType() != InVal.getValueType() &&
15850           InVal.getValueType().isScalarInteger() &&
15851           isTypeLegal(VT.getScalarType())) {
15852         Val =
15853             DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
15854         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
15855       }
15856       if (VT.getScalarType() == InVecT.getScalarType() &&
15857           VT.getVectorNumElements() <= InVecT.getVectorNumElements() &&
15858           TLI.isShuffleMaskLegal(NewMask, VT)) {
15859         Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec,
15860                                    DAG.getUNDEF(InVecT), NewMask);
15861         // If the initial vector is the correct size this shuffle is a
15862         // valid result.
15863         if (VT == InVecT)
15864           return Val;
15865         // If not we must truncate the vector.
15866         if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
15867           MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
15868           SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy);
15869           EVT SubVT =
15870               EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(),
15871                                VT.getVectorNumElements());
15872           Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val,
15873                             ZeroIdx);
15874           return Val;
15875         }
15876       }
15877     }
15878   }
15879 
15880   return SDValue();
15881 }
15882 
15883 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15884   EVT VT = N->getValueType(0);
15885   SDValue N0 = N->getOperand(0);
15886   SDValue N1 = N->getOperand(1);
15887   SDValue N2 = N->getOperand(2);
15888 
15889   // If inserting an UNDEF, just return the original vector.
15890   if (N1.isUndef())
15891     return N0;
15892 
15893   // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow
15894   // us to pull BITCASTs from input to output.
15895   if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR)
15896     if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode()))
15897       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2);
15898 
15899   // If this is an insert of an extracted vector into an undef vector, we can
15900   // just use the input to the extract.
15901   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15902       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15903     return N1.getOperand(0);
15904 
15905   // If we are inserting a bitcast value into an undef, with the same
15906   // number of elements, just use the bitcast input of the extract.
15907   // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
15908   //        BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
15909   if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
15910       N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15911       N1.getOperand(0).getOperand(1) == N2 &&
15912       N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
15913           VT.getVectorNumElements()) {
15914     return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
15915   }
15916 
15917   // If both N1 and N2 are bitcast values on which insert_subvector
15918   // would makes sense, pull the bitcast through.
15919   // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
15920   //        BITCAST (INSERT_SUBVECTOR N0 N1 N2)
15921   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
15922     SDValue CN0 = N0.getOperand(0);
15923     SDValue CN1 = N1.getOperand(0);
15924     if (CN0.getValueType().getVectorElementType() ==
15925             CN1.getValueType().getVectorElementType() &&
15926         CN0.getValueType().getVectorNumElements() ==
15927             VT.getVectorNumElements()) {
15928       SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
15929                                       CN0.getValueType(), CN0, CN1, N2);
15930       return DAG.getBitcast(VT, NewINSERT);
15931     }
15932   }
15933 
15934   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15935   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15936   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15937   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15938       N0.getOperand(1).getValueType() == N1.getValueType() &&
15939       N0.getOperand(2) == N2)
15940     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15941                        N1, N2);
15942 
15943   if (!isa<ConstantSDNode>(N2))
15944     return SDValue();
15945 
15946   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15947 
15948   // Canonicalize insert_subvector dag nodes.
15949   // Example:
15950   // (insert_subvector (insert_subvector A, Idx0), Idx1)
15951   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15952   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15953       N1.getValueType() == N0.getOperand(1).getValueType() &&
15954       isa<ConstantSDNode>(N0.getOperand(2))) {
15955     unsigned OtherIdx = N0.getConstantOperandVal(2);
15956     if (InsIdx < OtherIdx) {
15957       // Swap nodes.
15958       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15959                                   N0.getOperand(0), N1, N2);
15960       AddToWorklist(NewOp.getNode());
15961       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15962                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15963     }
15964   }
15965 
15966   // If the input vector is a concatenation, and the insert replaces
15967   // one of the pieces, we can optimize into a single concat_vectors.
15968   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15969       N0.getOperand(0).getValueType() == N1.getValueType()) {
15970     unsigned Factor = N1.getValueType().getVectorNumElements();
15971 
15972     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15973     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15974 
15975     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15976   }
15977 
15978   return SDValue();
15979 }
15980 
15981 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15982   SDValue N0 = N->getOperand(0);
15983 
15984   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15985   if (N0->getOpcode() == ISD::FP16_TO_FP)
15986     return N0->getOperand(0);
15987 
15988   return SDValue();
15989 }
15990 
15991 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15992   SDValue N0 = N->getOperand(0);
15993 
15994   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15995   if (N0->getOpcode() == ISD::AND) {
15996     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15997     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15998       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15999                          N0.getOperand(0));
16000     }
16001   }
16002 
16003   return SDValue();
16004 }
16005 
16006 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
16007 /// with the destination vector and a zero vector.
16008 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
16009 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
16010 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
16011   EVT VT = N->getValueType(0);
16012   SDValue LHS = N->getOperand(0);
16013   SDValue RHS = peekThroughBitcast(N->getOperand(1));
16014   SDLoc DL(N);
16015 
16016   // Make sure we're not running after operation legalization where it
16017   // may have custom lowered the vector shuffles.
16018   if (LegalOperations)
16019     return SDValue();
16020 
16021   if (N->getOpcode() != ISD::AND)
16022     return SDValue();
16023 
16024   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
16025     return SDValue();
16026 
16027   EVT RVT = RHS.getValueType();
16028   unsigned NumElts = RHS.getNumOperands();
16029 
16030   // Attempt to create a valid clear mask, splitting the mask into
16031   // sub elements and checking to see if each is
16032   // all zeros or all ones - suitable for shuffle masking.
16033   auto BuildClearMask = [&](int Split) {
16034     int NumSubElts = NumElts * Split;
16035     int NumSubBits = RVT.getScalarSizeInBits() / Split;
16036 
16037     SmallVector<int, 8> Indices;
16038     for (int i = 0; i != NumSubElts; ++i) {
16039       int EltIdx = i / Split;
16040       int SubIdx = i % Split;
16041       SDValue Elt = RHS.getOperand(EltIdx);
16042       if (Elt.isUndef()) {
16043         Indices.push_back(-1);
16044         continue;
16045       }
16046 
16047       APInt Bits;
16048       if (isa<ConstantSDNode>(Elt))
16049         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
16050       else if (isa<ConstantFPSDNode>(Elt))
16051         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
16052       else
16053         return SDValue();
16054 
16055       // Extract the sub element from the constant bit mask.
16056       if (DAG.getDataLayout().isBigEndian()) {
16057         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
16058       } else {
16059         Bits.lshrInPlace(SubIdx * NumSubBits);
16060       }
16061 
16062       if (Split > 1)
16063         Bits = Bits.trunc(NumSubBits);
16064 
16065       if (Bits.isAllOnesValue())
16066         Indices.push_back(i);
16067       else if (Bits == 0)
16068         Indices.push_back(i + NumSubElts);
16069       else
16070         return SDValue();
16071     }
16072 
16073     // Let's see if the target supports this vector_shuffle.
16074     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
16075     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
16076     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
16077       return SDValue();
16078 
16079     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
16080     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
16081                                                    DAG.getBitcast(ClearVT, LHS),
16082                                                    Zero, Indices));
16083   };
16084 
16085   // Determine maximum split level (byte level masking).
16086   int MaxSplit = 1;
16087   if (RVT.getScalarSizeInBits() % 8 == 0)
16088     MaxSplit = RVT.getScalarSizeInBits() / 8;
16089 
16090   for (int Split = 1; Split <= MaxSplit; ++Split)
16091     if (RVT.getScalarSizeInBits() % Split == 0)
16092       if (SDValue S = BuildClearMask(Split))
16093         return S;
16094 
16095   return SDValue();
16096 }
16097 
16098 /// Visit a binary vector operation, like ADD.
16099 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
16100   assert(N->getValueType(0).isVector() &&
16101          "SimplifyVBinOp only works on vectors!");
16102 
16103   SDValue LHS = N->getOperand(0);
16104   SDValue RHS = N->getOperand(1);
16105   SDValue Ops[] = {LHS, RHS};
16106 
16107   // See if we can constant fold the vector operation.
16108   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
16109           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
16110     return Fold;
16111 
16112   // Try to convert a constant mask AND into a shuffle clear mask.
16113   if (SDValue Shuffle = XformToShuffleWithZero(N))
16114     return Shuffle;
16115 
16116   // Type legalization might introduce new shuffles in the DAG.
16117   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
16118   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
16119   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
16120       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
16121       LHS.getOperand(1).isUndef() &&
16122       RHS.getOperand(1).isUndef()) {
16123     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
16124     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
16125 
16126     if (SVN0->getMask().equals(SVN1->getMask())) {
16127       EVT VT = N->getValueType(0);
16128       SDValue UndefVector = LHS.getOperand(1);
16129       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
16130                                      LHS.getOperand(0), RHS.getOperand(0),
16131                                      N->getFlags());
16132       AddUsersToWorklist(N);
16133       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
16134                                   SVN0->getMask());
16135     }
16136   }
16137 
16138   return SDValue();
16139 }
16140 
16141 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
16142                                     SDValue N2) {
16143   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
16144 
16145   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
16146                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
16147 
16148   // If we got a simplified select_cc node back from SimplifySelectCC, then
16149   // break it down into a new SETCC node, and a new SELECT node, and then return
16150   // the SELECT node, since we were called with a SELECT node.
16151   if (SCC.getNode()) {
16152     // Check to see if we got a select_cc back (to turn into setcc/select).
16153     // Otherwise, just return whatever node we got back, like fabs.
16154     if (SCC.getOpcode() == ISD::SELECT_CC) {
16155       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
16156                                   N0.getValueType(),
16157                                   SCC.getOperand(0), SCC.getOperand(1),
16158                                   SCC.getOperand(4));
16159       AddToWorklist(SETCC.getNode());
16160       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
16161                            SCC.getOperand(2), SCC.getOperand(3));
16162     }
16163 
16164     return SCC;
16165   }
16166   return SDValue();
16167 }
16168 
16169 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
16170 /// being selected between, see if we can simplify the select.  Callers of this
16171 /// should assume that TheSelect is deleted if this returns true.  As such, they
16172 /// should return the appropriate thing (e.g. the node) back to the top-level of
16173 /// the DAG combiner loop to avoid it being looked at.
16174 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
16175                                     SDValue RHS) {
16176 
16177   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16178   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
16179   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
16180     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
16181       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
16182       SDValue Sqrt = RHS;
16183       ISD::CondCode CC;
16184       SDValue CmpLHS;
16185       const ConstantFPSDNode *Zero = nullptr;
16186 
16187       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
16188         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
16189         CmpLHS = TheSelect->getOperand(0);
16190         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
16191       } else {
16192         // SELECT or VSELECT
16193         SDValue Cmp = TheSelect->getOperand(0);
16194         if (Cmp.getOpcode() == ISD::SETCC) {
16195           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
16196           CmpLHS = Cmp.getOperand(0);
16197           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
16198         }
16199       }
16200       if (Zero && Zero->isZero() &&
16201           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
16202           CC == ISD::SETULT || CC == ISD::SETLT)) {
16203         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16204         CombineTo(TheSelect, Sqrt);
16205         return true;
16206       }
16207     }
16208   }
16209   // Cannot simplify select with vector condition
16210   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
16211 
16212   // If this is a select from two identical things, try to pull the operation
16213   // through the select.
16214   if (LHS.getOpcode() != RHS.getOpcode() ||
16215       !LHS.hasOneUse() || !RHS.hasOneUse())
16216     return false;
16217 
16218   // If this is a load and the token chain is identical, replace the select
16219   // of two loads with a load through a select of the address to load from.
16220   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
16221   // constants have been dropped into the constant pool.
16222   if (LHS.getOpcode() == ISD::LOAD) {
16223     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
16224     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
16225 
16226     // Token chains must be identical.
16227     if (LHS.getOperand(0) != RHS.getOperand(0) ||
16228         // Do not let this transformation reduce the number of volatile loads.
16229         LLD->isVolatile() || RLD->isVolatile() ||
16230         // FIXME: If either is a pre/post inc/dec load,
16231         // we'd need to split out the address adjustment.
16232         LLD->isIndexed() || RLD->isIndexed() ||
16233         // If this is an EXTLOAD, the VT's must match.
16234         LLD->getMemoryVT() != RLD->getMemoryVT() ||
16235         // If this is an EXTLOAD, the kind of extension must match.
16236         (LLD->getExtensionType() != RLD->getExtensionType() &&
16237          // The only exception is if one of the extensions is anyext.
16238          LLD->getExtensionType() != ISD::EXTLOAD &&
16239          RLD->getExtensionType() != ISD::EXTLOAD) ||
16240         // FIXME: this discards src value information.  This is
16241         // over-conservative. It would be beneficial to be able to remember
16242         // both potential memory locations.  Since we are discarding
16243         // src value info, don't do the transformation if the memory
16244         // locations are not in the default address space.
16245         LLD->getPointerInfo().getAddrSpace() != 0 ||
16246         RLD->getPointerInfo().getAddrSpace() != 0 ||
16247         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
16248                                       LLD->getBasePtr().getValueType()))
16249       return false;
16250 
16251     // Check that the select condition doesn't reach either load.  If so,
16252     // folding this will induce a cycle into the DAG.  If not, this is safe to
16253     // xform, so create a select of the addresses.
16254     SDValue Addr;
16255     if (TheSelect->getOpcode() == ISD::SELECT) {
16256       SDNode *CondNode = TheSelect->getOperand(0).getNode();
16257       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
16258           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
16259         return false;
16260       // The loads must not depend on one another.
16261       if (LLD->isPredecessorOf(RLD) ||
16262           RLD->isPredecessorOf(LLD))
16263         return false;
16264       Addr = DAG.getSelect(SDLoc(TheSelect),
16265                            LLD->getBasePtr().getValueType(),
16266                            TheSelect->getOperand(0), LLD->getBasePtr(),
16267                            RLD->getBasePtr());
16268     } else {  // Otherwise SELECT_CC
16269       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
16270       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
16271 
16272       if ((LLD->hasAnyUseOfValue(1) &&
16273            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
16274           (RLD->hasAnyUseOfValue(1) &&
16275            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
16276         return false;
16277 
16278       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
16279                          LLD->getBasePtr().getValueType(),
16280                          TheSelect->getOperand(0),
16281                          TheSelect->getOperand(1),
16282                          LLD->getBasePtr(), RLD->getBasePtr(),
16283                          TheSelect->getOperand(4));
16284     }
16285 
16286     SDValue Load;
16287     // It is safe to replace the two loads if they have different alignments,
16288     // but the new load must be the minimum (most restrictive) alignment of the
16289     // inputs.
16290     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
16291     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
16292     if (!RLD->isInvariant())
16293       MMOFlags &= ~MachineMemOperand::MOInvariant;
16294     if (!RLD->isDereferenceable())
16295       MMOFlags &= ~MachineMemOperand::MODereferenceable;
16296     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
16297       // FIXME: Discards pointer and AA info.
16298       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
16299                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
16300                          MMOFlags);
16301     } else {
16302       // FIXME: Discards pointer and AA info.
16303       Load = DAG.getExtLoad(
16304           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
16305                                                   : LLD->getExtensionType(),
16306           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
16307           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
16308     }
16309 
16310     // Users of the select now use the result of the load.
16311     CombineTo(TheSelect, Load);
16312 
16313     // Users of the old loads now use the new load's chain.  We know the
16314     // old-load value is dead now.
16315     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
16316     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
16317     return true;
16318   }
16319 
16320   return false;
16321 }
16322 
16323 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
16324 /// bitwise 'and'.
16325 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
16326                                             SDValue N1, SDValue N2, SDValue N3,
16327                                             ISD::CondCode CC) {
16328   // If this is a select where the false operand is zero and the compare is a
16329   // check of the sign bit, see if we can perform the "gzip trick":
16330   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
16331   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
16332   EVT XType = N0.getValueType();
16333   EVT AType = N2.getValueType();
16334   if (!isNullConstant(N3) || !XType.bitsGE(AType))
16335     return SDValue();
16336 
16337   // If the comparison is testing for a positive value, we have to invert
16338   // the sign bit mask, so only do that transform if the target has a bitwise
16339   // 'and not' instruction (the invert is free).
16340   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
16341     // (X > -1) ? A : 0
16342     // (X >  0) ? X : 0 <-- This is canonical signed max.
16343     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
16344       return SDValue();
16345   } else if (CC == ISD::SETLT) {
16346     // (X <  0) ? A : 0
16347     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
16348     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
16349       return SDValue();
16350   } else {
16351     return SDValue();
16352   }
16353 
16354   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
16355   // constant.
16356   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
16357   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16358   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
16359     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
16360     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
16361     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
16362     AddToWorklist(Shift.getNode());
16363 
16364     if (XType.bitsGT(AType)) {
16365       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16366       AddToWorklist(Shift.getNode());
16367     }
16368 
16369     if (CC == ISD::SETGT)
16370       Shift = DAG.getNOT(DL, Shift, AType);
16371 
16372     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16373   }
16374 
16375   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
16376   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
16377   AddToWorklist(Shift.getNode());
16378 
16379   if (XType.bitsGT(AType)) {
16380     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16381     AddToWorklist(Shift.getNode());
16382   }
16383 
16384   if (CC == ISD::SETGT)
16385     Shift = DAG.getNOT(DL, Shift, AType);
16386 
16387   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16388 }
16389 
16390 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
16391 /// where 'cond' is the comparison specified by CC.
16392 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
16393                                       SDValue N2, SDValue N3, ISD::CondCode CC,
16394                                       bool NotExtCompare) {
16395   // (x ? y : y) -> y.
16396   if (N2 == N3) return N2;
16397 
16398   EVT VT = N2.getValueType();
16399   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16400   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16401 
16402   // Determine if the condition we're dealing with is constant
16403   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16404                               N0, N1, CC, DL, false);
16405   if (SCC.getNode()) AddToWorklist(SCC.getNode());
16406 
16407   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16408     // fold select_cc true, x, y -> x
16409     // fold select_cc false, x, y -> y
16410     return !SCCC->isNullValue() ? N2 : N3;
16411   }
16412 
16413   // Check to see if we can simplify the select into an fabs node
16414   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16415     // Allow either -0.0 or 0.0
16416     if (CFP->isZero()) {
16417       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
16418       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
16419           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
16420           N2 == N3.getOperand(0))
16421         return DAG.getNode(ISD::FABS, DL, VT, N0);
16422 
16423       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
16424       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
16425           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
16426           N2.getOperand(0) == N3)
16427         return DAG.getNode(ISD::FABS, DL, VT, N3);
16428     }
16429   }
16430 
16431   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
16432   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
16433   // in it.  This is a win when the constant is not otherwise available because
16434   // it replaces two constant pool loads with one.  We only do this if the FP
16435   // type is known to be legal, because if it isn't, then we are before legalize
16436   // types an we want the other legalization to happen first (e.g. to avoid
16437   // messing with soft float) and if the ConstantFP is not legal, because if
16438   // it is legal, we may not need to store the FP constant in a constant pool.
16439   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
16440     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
16441       if (TLI.isTypeLegal(N2.getValueType()) &&
16442           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
16443                TargetLowering::Legal &&
16444            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
16445            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
16446           // If both constants have multiple uses, then we won't need to do an
16447           // extra load, they are likely around in registers for other users.
16448           (TV->hasOneUse() || FV->hasOneUse())) {
16449         Constant *Elts[] = {
16450           const_cast<ConstantFP*>(FV->getConstantFPValue()),
16451           const_cast<ConstantFP*>(TV->getConstantFPValue())
16452         };
16453         Type *FPTy = Elts[0]->getType();
16454         const DataLayout &TD = DAG.getDataLayout();
16455 
16456         // Create a ConstantArray of the two constants.
16457         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
16458         SDValue CPIdx =
16459             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
16460                                 TD.getPrefTypeAlignment(FPTy));
16461         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
16462 
16463         // Get the offsets to the 0 and 1 element of the array so that we can
16464         // select between them.
16465         SDValue Zero = DAG.getIntPtrConstant(0, DL);
16466         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
16467         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
16468 
16469         SDValue Cond = DAG.getSetCC(DL,
16470                                     getSetCCResultType(N0.getValueType()),
16471                                     N0, N1, CC);
16472         AddToWorklist(Cond.getNode());
16473         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
16474                                           Cond, One, Zero);
16475         AddToWorklist(CstOffset.getNode());
16476         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
16477                             CstOffset);
16478         AddToWorklist(CPIdx.getNode());
16479         return DAG.getLoad(
16480             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
16481             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
16482             Alignment);
16483       }
16484     }
16485 
16486   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
16487     return V;
16488 
16489   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
16490   // where y is has a single bit set.
16491   // A plaintext description would be, we can turn the SELECT_CC into an AND
16492   // when the condition can be materialized as an all-ones register.  Any
16493   // single bit-test can be materialized as an all-ones register with
16494   // shift-left and shift-right-arith.
16495   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
16496       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
16497     SDValue AndLHS = N0->getOperand(0);
16498     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16499     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
16500       // Shift the tested bit over the sign bit.
16501       const APInt &AndMask = ConstAndRHS->getAPIntValue();
16502       SDValue ShlAmt =
16503         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
16504                         getShiftAmountTy(AndLHS.getValueType()));
16505       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
16506 
16507       // Now arithmetic right shift it all the way over, so the result is either
16508       // all-ones, or zero.
16509       SDValue ShrAmt =
16510         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
16511                         getShiftAmountTy(Shl.getValueType()));
16512       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
16513 
16514       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
16515     }
16516   }
16517 
16518   // fold select C, 16, 0 -> shl C, 4
16519   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
16520       TLI.getBooleanContents(N0.getValueType()) ==
16521           TargetLowering::ZeroOrOneBooleanContent) {
16522 
16523     // If the caller doesn't want us to simplify this into a zext of a compare,
16524     // don't do it.
16525     if (NotExtCompare && N2C->isOne())
16526       return SDValue();
16527 
16528     // Get a SetCC of the condition
16529     // NOTE: Don't create a SETCC if it's not legal on this target.
16530     if (!LegalOperations ||
16531         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
16532       SDValue Temp, SCC;
16533       // cast from setcc result type to select result type
16534       if (LegalTypes) {
16535         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
16536                             N0, N1, CC);
16537         if (N2.getValueType().bitsLT(SCC.getValueType()))
16538           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
16539                                         N2.getValueType());
16540         else
16541           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16542                              N2.getValueType(), SCC);
16543       } else {
16544         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
16545         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16546                            N2.getValueType(), SCC);
16547       }
16548 
16549       AddToWorklist(SCC.getNode());
16550       AddToWorklist(Temp.getNode());
16551 
16552       if (N2C->isOne())
16553         return Temp;
16554 
16555       // shl setcc result by log2 n2c
16556       return DAG.getNode(
16557           ISD::SHL, DL, N2.getValueType(), Temp,
16558           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
16559                           getShiftAmountTy(Temp.getValueType())));
16560     }
16561   }
16562 
16563   // Check to see if this is an integer abs.
16564   // select_cc setg[te] X,  0,  X, -X ->
16565   // select_cc setgt    X, -1,  X, -X ->
16566   // select_cc setl[te] X,  0, -X,  X ->
16567   // select_cc setlt    X,  1, -X,  X ->
16568   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
16569   if (N1C) {
16570     ConstantSDNode *SubC = nullptr;
16571     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
16572          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
16573         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
16574       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
16575     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
16576               (N1C->isOne() && CC == ISD::SETLT)) &&
16577              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
16578       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
16579 
16580     EVT XType = N0.getValueType();
16581     if (SubC && SubC->isNullValue() && XType.isInteger()) {
16582       SDLoc DL(N0);
16583       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
16584                                   N0,
16585                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
16586                                          getShiftAmountTy(N0.getValueType())));
16587       SDValue Add = DAG.getNode(ISD::ADD, DL,
16588                                 XType, N0, Shift);
16589       AddToWorklist(Shift.getNode());
16590       AddToWorklist(Add.getNode());
16591       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
16592     }
16593   }
16594 
16595   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
16596   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
16597   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
16598   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
16599   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
16600   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
16601   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
16602   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
16603   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
16604     SDValue ValueOnZero = N2;
16605     SDValue Count = N3;
16606     // If the condition is NE instead of E, swap the operands.
16607     if (CC == ISD::SETNE)
16608       std::swap(ValueOnZero, Count);
16609     // Check if the value on zero is a constant equal to the bits in the type.
16610     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
16611       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
16612         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
16613         // legal, combine to just cttz.
16614         if ((Count.getOpcode() == ISD::CTTZ ||
16615              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
16616             N0 == Count.getOperand(0) &&
16617             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
16618           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
16619         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
16620         // legal, combine to just ctlz.
16621         if ((Count.getOpcode() == ISD::CTLZ ||
16622              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
16623             N0 == Count.getOperand(0) &&
16624             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
16625           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
16626       }
16627     }
16628   }
16629 
16630   return SDValue();
16631 }
16632 
16633 /// This is a stub for TargetLowering::SimplifySetCC.
16634 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
16635                                    ISD::CondCode Cond, const SDLoc &DL,
16636                                    bool foldBooleans) {
16637   TargetLowering::DAGCombinerInfo
16638     DagCombineInfo(DAG, Level, false, this);
16639   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
16640 }
16641 
16642 /// Given an ISD::SDIV node expressing a divide by constant, return
16643 /// a DAG expression to select that will generate the same value by multiplying
16644 /// by a magic number.
16645 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16646 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
16647   // when optimising for minimum size, we don't want to expand a div to a mul
16648   // and a shift.
16649   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16650     return SDValue();
16651 
16652   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16653   if (!C)
16654     return SDValue();
16655 
16656   // Avoid division by zero.
16657   if (C->isNullValue())
16658     return SDValue();
16659 
16660   std::vector<SDNode*> Built;
16661   SDValue S =
16662       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16663 
16664   for (SDNode *N : Built)
16665     AddToWorklist(N);
16666   return S;
16667 }
16668 
16669 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
16670 /// DAG expression that will generate the same value by right shifting.
16671 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
16672   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16673   if (!C)
16674     return SDValue();
16675 
16676   // Avoid division by zero.
16677   if (C->isNullValue())
16678     return SDValue();
16679 
16680   std::vector<SDNode *> Built;
16681   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
16682 
16683   for (SDNode *N : Built)
16684     AddToWorklist(N);
16685   return S;
16686 }
16687 
16688 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
16689 /// expression that will generate the same value by multiplying by a magic
16690 /// number.
16691 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16692 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
16693   // when optimising for minimum size, we don't want to expand a div to a mul
16694   // and a shift.
16695   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16696     return SDValue();
16697 
16698   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16699   if (!C)
16700     return SDValue();
16701 
16702   // Avoid division by zero.
16703   if (C->isNullValue())
16704     return SDValue();
16705 
16706   std::vector<SDNode*> Built;
16707   SDValue S =
16708       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16709 
16710   for (SDNode *N : Built)
16711     AddToWorklist(N);
16712   return S;
16713 }
16714 
16715 /// Determines the LogBase2 value for a non-null input value using the
16716 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16717 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16718   EVT VT = V.getValueType();
16719   unsigned EltBits = VT.getScalarSizeInBits();
16720   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16721   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16722   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16723   return LogBase2;
16724 }
16725 
16726 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16727 /// For the reciprocal, we need to find the zero of the function:
16728 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
16729 ///     =>
16730 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16731 ///     does not require additional intermediate precision]
16732 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16733   if (Level >= AfterLegalizeDAG)
16734     return SDValue();
16735 
16736   // TODO: Handle half and/or extended types?
16737   EVT VT = Op.getValueType();
16738   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16739     return SDValue();
16740 
16741   // If estimates are explicitly disabled for this function, we're done.
16742   MachineFunction &MF = DAG.getMachineFunction();
16743   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16744   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16745     return SDValue();
16746 
16747   // Estimates may be explicitly enabled for this type with a custom number of
16748   // refinement steps.
16749   int Iterations = TLI.getDivRefinementSteps(VT, MF);
16750   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16751     AddToWorklist(Est.getNode());
16752 
16753     if (Iterations) {
16754       EVT VT = Op.getValueType();
16755       SDLoc DL(Op);
16756       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16757 
16758       // Newton iterations: Est = Est + Est (1 - Arg * Est)
16759       for (int i = 0; i < Iterations; ++i) {
16760         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16761         AddToWorklist(NewEst.getNode());
16762 
16763         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16764         AddToWorklist(NewEst.getNode());
16765 
16766         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16767         AddToWorklist(NewEst.getNode());
16768 
16769         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16770         AddToWorklist(Est.getNode());
16771       }
16772     }
16773     return Est;
16774   }
16775 
16776   return SDValue();
16777 }
16778 
16779 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16780 /// For the reciprocal sqrt, we need to find the zero of the function:
16781 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16782 ///     =>
16783 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16784 /// As a result, we precompute A/2 prior to the iteration loop.
16785 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16786                                          unsigned Iterations,
16787                                          SDNodeFlags Flags, bool Reciprocal) {
16788   EVT VT = Arg.getValueType();
16789   SDLoc DL(Arg);
16790   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16791 
16792   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16793   // this entire sequence requires only one FP constant.
16794   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16795   AddToWorklist(HalfArg.getNode());
16796 
16797   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
16798   AddToWorklist(HalfArg.getNode());
16799 
16800   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
16801   for (unsigned i = 0; i < Iterations; ++i) {
16802     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
16803     AddToWorklist(NewEst.getNode());
16804 
16805     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
16806     AddToWorklist(NewEst.getNode());
16807 
16808     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
16809     AddToWorklist(NewEst.getNode());
16810 
16811     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16812     AddToWorklist(Est.getNode());
16813   }
16814 
16815   // If non-reciprocal square root is requested, multiply the result by Arg.
16816   if (!Reciprocal) {
16817     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
16818     AddToWorklist(Est.getNode());
16819   }
16820 
16821   return Est;
16822 }
16823 
16824 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16825 /// For the reciprocal sqrt, we need to find the zero of the function:
16826 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16827 ///     =>
16828 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
16829 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
16830                                          unsigned Iterations,
16831                                          SDNodeFlags Flags, bool Reciprocal) {
16832   EVT VT = Arg.getValueType();
16833   SDLoc DL(Arg);
16834   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
16835   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
16836 
16837   // This routine must enter the loop below to work correctly
16838   // when (Reciprocal == false).
16839   assert(Iterations > 0);
16840 
16841   // Newton iterations for reciprocal square root:
16842   // E = (E * -0.5) * ((A * E) * E + -3.0)
16843   for (unsigned i = 0; i < Iterations; ++i) {
16844     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
16845     AddToWorklist(AE.getNode());
16846 
16847     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
16848     AddToWorklist(AEE.getNode());
16849 
16850     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
16851     AddToWorklist(RHS.getNode());
16852 
16853     // When calculating a square root at the last iteration build:
16854     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
16855     // (notice a common subexpression)
16856     SDValue LHS;
16857     if (Reciprocal || (i + 1) < Iterations) {
16858       // RSQRT: LHS = (E * -0.5)
16859       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
16860     } else {
16861       // SQRT: LHS = (A * E) * -0.5
16862       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
16863     }
16864     AddToWorklist(LHS.getNode());
16865 
16866     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
16867     AddToWorklist(Est.getNode());
16868   }
16869 
16870   return Est;
16871 }
16872 
16873 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
16874 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
16875 /// Op can be zero.
16876 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
16877                                            bool Reciprocal) {
16878   if (Level >= AfterLegalizeDAG)
16879     return SDValue();
16880 
16881   // TODO: Handle half and/or extended types?
16882   EVT VT = Op.getValueType();
16883   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16884     return SDValue();
16885 
16886   // If estimates are explicitly disabled for this function, we're done.
16887   MachineFunction &MF = DAG.getMachineFunction();
16888   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
16889   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16890     return SDValue();
16891 
16892   // Estimates may be explicitly enabled for this type with a custom number of
16893   // refinement steps.
16894   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
16895 
16896   bool UseOneConstNR = false;
16897   if (SDValue Est =
16898       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16899                           Reciprocal)) {
16900     AddToWorklist(Est.getNode());
16901 
16902     if (Iterations) {
16903       Est = UseOneConstNR
16904             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16905             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16906 
16907       if (!Reciprocal) {
16908         // Unfortunately, Est is now NaN if the input was exactly 0.0.
16909         // Select out this case and force the answer to 0.0.
16910         EVT VT = Op.getValueType();
16911         SDLoc DL(Op);
16912 
16913         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16914         EVT CCVT = getSetCCResultType(VT);
16915         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16916         AddToWorklist(ZeroCmp.getNode());
16917 
16918         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16919                           ZeroCmp, FPZero, Est);
16920         AddToWorklist(Est.getNode());
16921       }
16922     }
16923     return Est;
16924   }
16925 
16926   return SDValue();
16927 }
16928 
16929 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16930   return buildSqrtEstimateImpl(Op, Flags, true);
16931 }
16932 
16933 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16934   return buildSqrtEstimateImpl(Op, Flags, false);
16935 }
16936 
16937 /// Return true if base is a frame index, which is known not to alias with
16938 /// anything but itself.  Provides base object and offset as results.
16939 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16940                            const GlobalValue *&GV, const void *&CV) {
16941   // Assume it is a primitive operation.
16942   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16943 
16944   // If it's an adding a simple constant then integrate the offset.
16945   if (Base.getOpcode() == ISD::ADD) {
16946     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16947       Base = Base.getOperand(0);
16948       Offset += C->getSExtValue();
16949     }
16950   }
16951 
16952   // Return the underlying GlobalValue, and update the Offset.  Return false
16953   // for GlobalAddressSDNode since the same GlobalAddress may be represented
16954   // by multiple nodes with different offsets.
16955   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16956     GV = G->getGlobal();
16957     Offset += G->getOffset();
16958     return false;
16959   }
16960 
16961   // Return the underlying Constant value, and update the Offset.  Return false
16962   // for ConstantSDNodes since the same constant pool entry may be represented
16963   // by multiple nodes with different offsets.
16964   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16965     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16966                                          : (const void *)C->getConstVal();
16967     Offset += C->getOffset();
16968     return false;
16969   }
16970   // If it's any of the following then it can't alias with anything but itself.
16971   return isa<FrameIndexSDNode>(Base);
16972 }
16973 
16974 /// Return true if there is any possibility that the two addresses overlap.
16975 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16976   // If they are the same then they must be aliases.
16977   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16978 
16979   // If they are both volatile then they cannot be reordered.
16980   if (Op0->isVolatile() && Op1->isVolatile()) return true;
16981 
16982   // If one operation reads from invariant memory, and the other may store, they
16983   // cannot alias. These should really be checking the equivalent of mayWrite,
16984   // but it only matters for memory nodes other than load /store.
16985   if (Op0->isInvariant() && Op1->writeMem())
16986     return false;
16987 
16988   if (Op1->isInvariant() && Op0->writeMem())
16989     return false;
16990 
16991   unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16992   unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16993 
16994   // Check for BaseIndexOffset matching.
16995   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
16996   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
16997   int64_t PtrDiff;
16998   if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
16999     return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
17000 
17001   // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
17002   // able to calculate their relative offset if at least one arises
17003   // from an alloca. However, these allocas cannot overlap and we
17004   // can infer there is no alias.
17005   if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
17006     if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
17007       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17008       // If the base are the same frame index but the we couldn't find a
17009       // constant offset, (indices are different) be conservative.
17010       if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
17011                      !MFI.isFixedObjectIndex(B->getIndex())))
17012         return false;
17013     }
17014 
17015   // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
17016   // modified to use BaseIndexOffset.
17017 
17018   // Gather base node and offset information.
17019   SDValue Base0, Base1;
17020   int64_t Offset0, Offset1;
17021   const GlobalValue *GV0, *GV1;
17022   const void *CV0, *CV1;
17023   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
17024                                       Base0, Offset0, GV0, CV0);
17025   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
17026                                       Base1, Offset1, GV1, CV1);
17027 
17028   // If they have the same base address, then check to see if they overlap.
17029   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
17030     return !((Offset0 + NumBytes0) <= Offset1 ||
17031              (Offset1 + NumBytes1) <= Offset0);
17032 
17033   // It is possible for different frame indices to alias each other, mostly
17034   // when tail call optimization reuses return address slots for arguments.
17035   // To catch this case, look up the actual index of frame indices to compute
17036   // the real alias relationship.
17037   if (IsFrameIndex0 && IsFrameIndex1) {
17038     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17039     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
17040     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
17041     return !((Offset0 + NumBytes0) <= Offset1 ||
17042              (Offset1 + NumBytes1) <= Offset0);
17043   }
17044 
17045   // Otherwise, if we know what the bases are, and they aren't identical, then
17046   // we know they cannot alias.
17047   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
17048     return false;
17049 
17050   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
17051   // compared to the size and offset of the access, we may be able to prove they
17052   // do not alias. This check is conservative for now to catch cases created by
17053   // splitting vector types.
17054   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
17055   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
17056   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
17057   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
17058   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
17059       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
17060     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
17061     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
17062 
17063     // There is no overlap between these relatively aligned accesses of similar
17064     // size. Return no alias.
17065     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
17066         (OffAlign1 + NumBytes1) <= OffAlign0)
17067       return false;
17068   }
17069 
17070   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
17071                    ? CombinerGlobalAA
17072                    : DAG.getSubtarget().useAA();
17073 #ifndef NDEBUG
17074   if (CombinerAAOnlyFunc.getNumOccurrences() &&
17075       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
17076     UseAA = false;
17077 #endif
17078 
17079   if (UseAA && AA &&
17080       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
17081     // Use alias analysis information.
17082     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
17083     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
17084     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
17085     AliasResult AAResult =
17086         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
17087                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
17088                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
17089                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
17090     if (AAResult == NoAlias)
17091       return false;
17092   }
17093 
17094   // Otherwise we have to assume they alias.
17095   return true;
17096 }
17097 
17098 /// Walk up chain skipping non-aliasing memory nodes,
17099 /// looking for aliasing nodes and adding them to the Aliases vector.
17100 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
17101                                    SmallVectorImpl<SDValue> &Aliases) {
17102   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
17103   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
17104 
17105   // Get alias information for node.
17106   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
17107 
17108   // Starting off.
17109   Chains.push_back(OriginalChain);
17110   unsigned Depth = 0;
17111 
17112   // Look at each chain and determine if it is an alias.  If so, add it to the
17113   // aliases list.  If not, then continue up the chain looking for the next
17114   // candidate.
17115   while (!Chains.empty()) {
17116     SDValue Chain = Chains.pop_back_val();
17117 
17118     // For TokenFactor nodes, look at each operand and only continue up the
17119     // chain until we reach the depth limit.
17120     //
17121     // FIXME: The depth check could be made to return the last non-aliasing
17122     // chain we found before we hit a tokenfactor rather than the original
17123     // chain.
17124     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
17125       Aliases.clear();
17126       Aliases.push_back(OriginalChain);
17127       return;
17128     }
17129 
17130     // Don't bother if we've been before.
17131     if (!Visited.insert(Chain.getNode()).second)
17132       continue;
17133 
17134     switch (Chain.getOpcode()) {
17135     case ISD::EntryToken:
17136       // Entry token is ideal chain operand, but handled in FindBetterChain.
17137       break;
17138 
17139     case ISD::LOAD:
17140     case ISD::STORE: {
17141       // Get alias information for Chain.
17142       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
17143           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
17144 
17145       // If chain is alias then stop here.
17146       if (!(IsLoad && IsOpLoad) &&
17147           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
17148         Aliases.push_back(Chain);
17149       } else {
17150         // Look further up the chain.
17151         Chains.push_back(Chain.getOperand(0));
17152         ++Depth;
17153       }
17154       break;
17155     }
17156 
17157     case ISD::TokenFactor:
17158       // We have to check each of the operands of the token factor for "small"
17159       // token factors, so we queue them up.  Adding the operands to the queue
17160       // (stack) in reverse order maintains the original order and increases the
17161       // likelihood that getNode will find a matching token factor (CSE.)
17162       if (Chain.getNumOperands() > 16) {
17163         Aliases.push_back(Chain);
17164         break;
17165       }
17166       for (unsigned n = Chain.getNumOperands(); n;)
17167         Chains.push_back(Chain.getOperand(--n));
17168       ++Depth;
17169       break;
17170 
17171     case ISD::CopyFromReg:
17172       // Forward past CopyFromReg.
17173       Chains.push_back(Chain.getOperand(0));
17174       ++Depth;
17175       break;
17176 
17177     default:
17178       // For all other instructions we will just have to take what we can get.
17179       Aliases.push_back(Chain);
17180       break;
17181     }
17182   }
17183 }
17184 
17185 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
17186 /// (aliasing node.)
17187 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
17188   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
17189 
17190   // Accumulate all the aliases to this node.
17191   GatherAllAliases(N, OldChain, Aliases);
17192 
17193   // If no operands then chain to entry token.
17194   if (Aliases.size() == 0)
17195     return DAG.getEntryNode();
17196 
17197   // If a single operand then chain to it.  We don't need to revisit it.
17198   if (Aliases.size() == 1)
17199     return Aliases[0];
17200 
17201   // Construct a custom tailored token factor.
17202   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
17203 }
17204 
17205 // This function tries to collect a bunch of potentially interesting
17206 // nodes to improve the chains of, all at once. This might seem
17207 // redundant, as this function gets called when visiting every store
17208 // node, so why not let the work be done on each store as it's visited?
17209 //
17210 // I believe this is mainly important because MergeConsecutiveStores
17211 // is unable to deal with merging stores of different sizes, so unless
17212 // we improve the chains of all the potential candidates up-front
17213 // before running MergeConsecutiveStores, it might only see some of
17214 // the nodes that will eventually be candidates, and then not be able
17215 // to go from a partially-merged state to the desired final
17216 // fully-merged state.
17217 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
17218   // This holds the base pointer, index, and the offset in bytes from the base
17219   // pointer.
17220   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
17221 
17222   // We must have a base and an offset.
17223   if (!BasePtr.getBase().getNode())
17224     return false;
17225 
17226   // Do not handle stores to undef base pointers.
17227   if (BasePtr.getBase().isUndef())
17228     return false;
17229 
17230   SmallVector<StoreSDNode *, 8> ChainedStores;
17231   ChainedStores.push_back(St);
17232 
17233   // Walk up the chain and look for nodes with offsets from the same
17234   // base pointer. Stop when reaching an instruction with a different kind
17235   // or instruction which has a different base pointer.
17236   StoreSDNode *Index = St;
17237   while (Index) {
17238     // If the chain has more than one use, then we can't reorder the mem ops.
17239     if (Index != St && !SDValue(Index, 0)->hasOneUse())
17240       break;
17241 
17242     if (Index->isVolatile() || Index->isIndexed())
17243       break;
17244 
17245     // Find the base pointer and offset for this memory node.
17246     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
17247 
17248     // Check that the base pointer is the same as the original one.
17249     if (!BasePtr.equalBaseIndex(Ptr, DAG))
17250       break;
17251 
17252     // Walk up the chain to find the next store node, ignoring any
17253     // intermediate loads. Any other kind of node will halt the loop.
17254     SDNode *NextInChain = Index->getChain().getNode();
17255     while (true) {
17256       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
17257         // We found a store node. Use it for the next iteration.
17258         if (STn->isVolatile() || STn->isIndexed()) {
17259           Index = nullptr;
17260           break;
17261         }
17262         ChainedStores.push_back(STn);
17263         Index = STn;
17264         break;
17265       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
17266         NextInChain = Ldn->getChain().getNode();
17267         continue;
17268       } else {
17269         Index = nullptr;
17270         break;
17271       }
17272     } // end while
17273   }
17274 
17275   // At this point, ChainedStores lists all of the Store nodes
17276   // reachable by iterating up through chain nodes matching the above
17277   // conditions.  For each such store identified, try to find an
17278   // earlier chain to attach the store to which won't violate the
17279   // required ordering.
17280   bool MadeChangeToSt = false;
17281   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
17282 
17283   for (StoreSDNode *ChainedStore : ChainedStores) {
17284     SDValue Chain = ChainedStore->getChain();
17285     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
17286 
17287     if (Chain != BetterChain) {
17288       if (ChainedStore == St)
17289         MadeChangeToSt = true;
17290       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
17291     }
17292   }
17293 
17294   // Do all replacements after finding the replacements to make to avoid making
17295   // the chains more complicated by introducing new TokenFactors.
17296   for (auto Replacement : BetterChains)
17297     replaceStoreChain(Replacement.first, Replacement.second);
17298 
17299   return MadeChangeToSt;
17300 }
17301 
17302 /// This is the entry point for the file.
17303 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
17304                            CodeGenOpt::Level OptLevel) {
17305   /// This is the main entry point to this class.
17306   DAGCombiner(*this, AA, OptLevel).Run(Level);
17307 }
17308